<?php

namespace App\Services\Settings;

use App\Traits\CrudResponse;
use Illuminate\Contracts\View\View;
use App\Models\Settings\DestinationType;
use Illuminate\Support\Facades\Auth;

class DestinationTypeService
{
    // Call trait
    use CrudResponse;

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

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


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

        // 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'])),
            'active' => 1,
            'created_by' => Auth::id(),
            'updated_by' => !empty($data['rowID']) ? Auth::id() : null,
        ];
 
        $response = DestinationType::updateOrCreate(['id' => $data['rowID']], $updateData);

        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 = DestinationType::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()
                ];
        }
    }
}
