<?php

namespace App\Services\Settings;

use App\Actions\ImageUpload;
use App\Traits\CrudResponse;
use Illuminate\Http\Request;
use App\Models\Settings\Brand;
use App\Models\Settings\Destination;
use App\Models\Settings\DestinationType;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Auth;
use App\Models\Settings\EquipmentType;

class DestinationService
{
    // Call trait
    use CrudResponse;

    /** Show Form
     * @param int $rowID
     * 
     * @return View
     */
    public function _showForm(int $rowID): View
    {
        // Get data by row ID
        $data = Destination::find($rowID);

        // Get all not deleted brand records
        $destinationTypeRecords = DestinationType::select('id' ,'name')
        ->where('deleted_at', null)->where('active', 1)
        ->get();

        // Return
        return view('backoffice.settings.destination.form', [
            'data' => $data,
            'destinationTypeRecords' => $destinationTypeRecords,
        ]);
    }


    /** Get data
     * @return array
     */
    public function _getData(): array
    {
        // Create model instance
        $criticality = new Destination;

        // Data table field
        $columnsFilter = [
            'name',
        ];

        // Search value
        $searchValue = $_REQUEST['search']['value'] ?? '';

        // Filter
        $status = $_REQUEST['status'] ?? '';

        // Get criticality data
        return $criticality->getModelData($status, $searchValue, $columnsFilter);
    }

    /**
     * @param array $data
     * 
     * @return array
     */
    public function _setData(array $data): array
    {
        
        // Add data to the array
        $updateData = [
            'name' => trim(mb_strtolower($data['name'])),
            'destinationtype_id' => (int) $data['destinationtype_id'],
            'active' => 1,
            'created_by' => Auth::id(),
            'updated_by' => !empty($data['rowID']) ? Auth::id() : null,
        ];

        // Add
        $response = Destination::updateOrCreate(['id' => $data['rowID']], $updateData);

        // Return response
        return [
            'success' => !empty($response['id']),
            'message' => $this->addOrUpdateResponseText(!empty($response['id'])),
        ];
    }


    /**
     * @param int $rowID
     * 
     * @return array
     */
    public function _deleteData(int $rowID): array
    {
        // Find row in database
        $deleted = Destination::find($rowID)->delete();

        // delete if row exist
        if (!empty($deleted)) {
            return
                [
                    'success' => true,
                    'message' => $this->deleteResponseSuccessText()
                ];
        } // end if
        else {
            return
                [
                    'error' => false,
                    'message' => $this->deleteResponseErrorText()
                ];
        }
    }
}
