<?php

namespace App\Services;

use App\Models\Car;
use App\Traits\CrudResponse;
use App\Models\Settings\Brand;
use App\Models\Settings\Color;
use App\Models\Settings\Modele;
use App\Models\Settings\CarType;
use App\Models\Settings\FuelType;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Auth;
use App\Models\Settings\TransmissionType;

class CarService
{
    // Calling traits
    use CrudResponse;

    /**
     * Get all data
     * @return array
     */
    public function get(): array
    {
        // Create model instance
        $car = new Car;

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

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

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

        // Get car data
        return $car->getData($status, $searchValue, $columnsFilter);
    }

    /**
     * Open  form
     *@param int $rowID
     * @return View
     */
    public function form(int $rowID): View
    {
        // Get data
        $data = Car::find($rowID);

        // GET ALL BRAND
        $brands = Brand::where('active', 1)->where('deleted_at', null)->get();

        // GET ALL MODEL
        $modeles = Modele::where('active', 1)->where('deleted_at', null)->get();

        // GET ALL type
        $cartypes = CarType::where('active', 1)->where('deleted_at', null)->get();

        // GET ALL type
        $fueltypes = FuelType::where('active', 1)->where('deleted_at', null)->get();

        // GET ALL type
        $transmissiontypes = TransmissionType::where('active', 1)->where('deleted_at', null)->get();

        // GET ALL type
        $colors = Color::where('active', 1)->where('deleted_at', null)->get();

        // Return
        return view('backoffice.car.form', compact('data', 'modeles', 'brands', 'cartypes', 'fueltypes', 'transmissiontypes', 'colors'));
    }

    /**
     * Set  data
     * @param array $data
     * @return array
     */
    public function set(array $data): array
    {

        // dd('ok');
        // Getv mocel instance
        $car = (!empty($data['rowID'])) ? Car::findOrFail($data['rowID']) : new Car();


        // Add data to save
        $car->brand_id                  = $data['brand_id'];
        $car->modele_id                 = $data['modele_id'];
        $car->cartype_id                = $data['cartype_id'];
        $car->fueltype_id               = $data['fueltype_id'];
        $car->transmissiontype_id       = $data['transmissiontype_id'];
        $car->color_id                  = $data['color_id'];
        $car->price                     = $data['price'];
        $car->number_of_places          = $data['place'];
        $car->immatriculation           = $data['imm'];
        $car->description               = $data['description'];
        $car->status                    = 1;
        $car->created_by                = Auth::id();
        $car->active                    = 1;
        $car->updated_by                = !empty($data['rowID']) ? Auth::id() : null;


        // dd('ok');
        // Save data
        $response = $car->save();

        // Supprimer toutes les images associées au véhicule
        $car->images()->delete();

        // Enregistrer les nouvelles images
        if ($data['files']) {
            foreach ($data['files'] as $image) {
                // $filename = $image->store('car_images');
                $uniqueFileName = uniqid() . '_' . $image->getClientOriginalName();
                $filename = $image->move(public_path('car_images'), $uniqueFileName);
                $car->images()->create(['image_path' => $uniqueFileName]);
            }
        }


        //Process to return message
        if (!empty($response)) {
            return [
                'success'    => true,
                'message'    => $this->addOrUpdateResponseSuccessText()
            ];
        } // end if
        else {
            return [
                'error'    => false,
                'message'    => $this->addOrUpdateResponseErrorText()
            ];
        }
    }

    /**
     * Delete
     * @param int $rowID
     * @return array
     */
    public function delete(int $rowID): array
    {
        // Find row in database
        $deleted = Car::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()
                ];
        }
    }
}
