<?php

namespace Modules\Fleet\Controllers;

use App\Controllers\BaseController;
use Modules\Fleet\Models\VehicleModel;
use Modules\Fleet\Models\FleetModel;
use Modules\Fleet\Models\Vehicalimage;
use App\Libraries\Rolepermission;
use App\Models\BusTypesModel;
use Modules\Company\Models\CompanyModel;

class Vehicle extends BaseController
{
    private $Viewpath;
    protected $vehiclModel;
    protected $fleetModel;
    protected $vImageModel;
    protected $session;
    protected $busTypesModel;
    protected $CompanyModel;

    public function __construct()
    {
        $this->Viewpath = "Modules\Fleet\Views";
        $this->vehiclModel = new VehicleModel();
        $this->fleetModel = new FleetModel();
        $this->vImageModel = new Vehicalimage();
        $this->busTypesModel = new BusTypesModel();
        $this->CompanyModel = new CompanyModel();
    }

    public function index(bool $showDeletedOnly = false)
    {
        $role_id = session()->get('role_id');
        $logged_company_id = session()->get('company_id');
        
        if(($this->request->getVar('company_id') || $this->request->getVar('company_id') == 0) && session()->get('role_id') == "1"){
            $company_id = $this->request->getVar('company_id') ?? 0;
        } else {
            if(session('search_company_id')){
                $company_id = session('search_company_id');
            }
        }

        $data['module'] =    lang("Localize.fleet");
        $data['title']  =    lang("Localize.vehicle_list");
        $data['pageheading'] = lang("Localize.vehicle_list");

        $rolepermissionLibrary = new Rolepermission();
        $data['add_data'] = $rolepermissionLibrary->create("add_vehicle");
        $data['edit_data'] = $rolepermissionLibrary->edit("vehicle_list");
        $data['delete_data'] = $rolepermissionLibrary->delete("vehicle_list");

        $this->vehiclModel->select('vehicles.*,fleets.id,fleets.type,vehicles.id as vehicleid, companies.name AS company_name')
            ->join('fleets', 'fleets.id = vehicles.fleet_id')
            ->join('companies', 'companies.id = vehicles.company_id');

        if(!in_array($role_id,[1,2]) && $logged_company_id){
            $this->vehiclModel->where('company_id', $logged_company_id);
        }
        if ($showDeletedOnly) {
            $data['trash_view'] = true;
            $this->vehiclModel->onlyDeleted();
        }

        $data['role_id'] = $role_id;
        $data['logged_company_id'] = $logged_company_id;

        $data['vehical'] =  $this->vehiclModel->findAll();
        return view($this->Viewpath . '\vehical\index', $data);
    }

    public function new()
    {
        $data['fleet'] = $this->fleetModel->findAll();
        $data['busTypes'] = $this->busTypesModel->findAll();

        $data['module'] =    lang("Localize.fleet");
        $data['title']  =    lang("Localize.add_vehicle");
        $data['pageheading'] = lang("Localize.add_vehicle");
        
        $data['company_id'] = 0;
        $data['companies'] = $this->CompanyModel->findAll();

        $data['role_id'] = session()->get('role_id');
        $data['logged_company_id'] = session()->get('company_id');


        return view($this->Viewpath . '\vehical/new', $data);
    }

    public function create()
    {
        $imgpath = array();
        $imgbus =  $this->request->getFileMultiple('busimg');

        if (!empty($imgbus)) {
            foreach ($imgbus as $key => $imgvalue) {
                if ($imgvalue->isValid() && !$imgvalue->hasMoved()) {
                    $busimag = $this->imgaeCheck($imgvalue);
                    array_push($imgpath, $busimag);
                }
            }
        }

        $validation = \Config\Services::validation();

        $rules = [
            'fleet_id'     => 'required',
            'company_id'   => 'required',
            'reg_no'       => 'required|is_unique[vehicles.reg_no,id,{id}]',
            'bus_type'     => 'required',
            'ownership'    => 'required',
            'status'       => 'required',
            'assign'       => 'required',
        ];

        $ownership = $this->request->getPost('ownership');
        if ($ownership === 'rented') {
            // Add additional rules for rented ownership
            $rules['woner'] = 'required';
            $rules['woner_mobile'] = 'required';
        }

        // Set custom error messages
        $errors = [
            'reg_no' => [
                'is_unique' => 'There is already a vehicle registered with this registration number',
            ],
            'woner' => [
                'required' => 'Owner name is required for rented vehicles',
            ],
            'woner_mobile' => [
                'required' => 'Owner mobile is required for rented vehicles',
            ],
        ];

        // Validate the input data
        if (!$this->validate($rules, $errors)) {
            
            session()->setFlashdata('fail', $validation->listErrors());
            return redirect()->back()->withInput();
        }

        $vehicalData = $this->vehiclModel
                            ->where('company_id', $this->request->getVar('company_id'))
                            ->orderBy('bus_plate_no', 'DESC')
                            ->first();
        $currentMax = isset($vehicalData->bus_plate_no) ? (int)$vehicalData->bus_plate_no : 0;
        $nextBusPlateNo = $currentMax + 1;
        if($ownership === 'rented'){
            $nextBusPlateNo = 0;
        }

        $data = array(
            "fleet_id" => $this->request->getVar('fleet_id'),
            "reg_no" => $this->request->getVar('reg_no'),
            "engine_no" => $this->request->getVar('engine_no'),
            "model_no" => $this->request->getVar('model_no'),
            "chasis_no" => $this->request->getVar('chasis_no'),
            "ownership" => $this->request->getVar('ownership'),
            "bus_type" => $this->request->getVar('bus_type'),
            "woner" => $this->request->getVar('woner'),
            "woner_mobile" => $this->request->getVar('woner_mobile'),
            "company_id" => $this->request->getVar('company_id'),
            "status" => $this->request->getVar('status'),
            "assign" => $this->request->getVar('assign'),
            "bus_plate_no" => $nextBusPlateNo,

        );
        $vehicleid =  $this->vehiclModel->insert($data);

        if (!empty($imgpath)) {
            foreach ($imgpath as $key => $imgvalue) {
                $storedata[$key] = array(
                    "vehicle_id" => $vehicleid,
                    "img_path" => $imgvalue,
                );
            }

            $this->vImageModel->insertBatch($storedata);
        }

        session()->setFlashdata('success', "Data Save");
        return redirect()->route('index-vehicle')->with("success", "Data Save");

    }

    public function edit($id)
    {
        $data['vehical'] = $this->vehiclModel->find($id);
        $data['imagevehical'] = $this->vImageModel->where('vehicle_id', $id)->findAll();
        $data['fleet'] = $this->fleetModel->findAll();

        $data['module'] =    lang("Localize.fleet");
        $data['title']  =    lang("Localize.vehicle_list");
        $data['busTypes'] = $this->busTypesModel->findAll();

        $data['company_id'] = 0;
        if(!empty($data['vehical'])){
            $vehical = $data['vehical'];
            $data['company_id'] = $vehical->company_id;
        }
        $data['companies'] = $this->CompanyModel->findAll();

        $data['role_id'] = session()->get('role_id');
        $data['logged_company_id'] = session()->get('company_id');
        
        $heading = lang("Localize.edit") . ' ' . lang("Localize.vehicle_list");
        $data['pageheading'] = $heading;

        echo view($this->Viewpath . '\vehical/edit', $data);
    }

    public function update($id)
    {
        $imgpath = array();
        $imgbus =  $this->request->getFileMultiple('busimgedit');


        if ($imgbus[0]->isValid()) {
            $vehicaleImage = $this->vImageModel->where('vehicle_id', $id)->findAll();
            foreach ($vehicaleImage as $key => $vehicalvalue) {
                $this->vImageModel->delete($vehicalvalue->id);
                
                if (file_exists($vehicalvalue->img_path)) {
                    @unlink($vehicalvalue->img_path);
                }
            }
            $this->vImageModel->purgeDeleted();

            foreach ($imgbus as $key => $imgvalue) {
                if ($imgvalue->isValid() && !$imgvalue->hasMoved()) {
                    $busimag     = $this->imgaeCheck($imgvalue);
                    array_push($imgpath, $busimag);
                }
            }
        }

        $validation = \Config\Services::validation();

        // Base validation rules
        $rules = [
            'company_id'     => 'required',
            'fleet_id'     => 'required',
            'reg_no'       => "required|is_unique[vehicles.reg_no,id,$id]",
            'bus_type'     => 'required',
            'ownership'    => 'required',
            'status'       => 'required',
            'assign'       => 'required',
        ];

        // Check the ownership value
        $ownership = $this->request->getPost('ownership');
        if ($ownership === 'rented') {
            // Add additional rules for rented ownership
            $rules['woner'] = 'required';
            $rules['woner_mobile'] = 'required';
        }

        // Set custom error messages
        $errors = [
            'reg_no' => [
                'is_unique' => 'There is already a vehicle registered with this registration number',
            ],
            'woner' => [
                'required' => 'Owner name is required for rented vehicles',
            ],
            'woner_mobile' => [
                'required' => 'Owner mobile is required for rented vehicles',
            ],
        ];

        // Validate the input data
        if (!$this->validate($rules, $errors)) {
            
            session()->setFlashdata('fail', $validation->listErrors());
            return redirect()->back()->withInput();
        }

        $data = array(
            "id" => $id,
            "fleet_id" => $this->request->getVar('fleet_id'),
            "reg_no" => $this->request->getVar('reg_no'),
            "engine_no" => $this->request->getVar('engine_no'),
            "model_no" => $this->request->getVar('model_no'),
            "chasis_no" => $this->request->getVar('chasis_no'),
            "ownership" => $this->request->getVar('ownership'),
            "bus_type" => $this->request->getVar('bus_type'),
            "woner" => $this->request->getVar('woner'),
            "woner_mobile" => $this->request->getVar('woner_mobile'),
            "company_id" => $this->request->getVar('company_id'),
            "status" => $this->request->getVar('status'),
            "assign" => $this->request->getVar('assign'),
        );

        $this->vehiclModel->save($data);

        if (!empty($imgpath)) {
            foreach ($imgpath as $key => $imgvalue) {
                $storedata[$key] = array(
                    "vehicle_id" => $id,
                    "img_path" => $imgvalue,
                );
            }
            $this->vImageModel->insertBatch($storedata);
        }

        session()->setFlashdata('success', "Data Updated");
        return redirect()->route('index-vehicle')->with("success", "Data Updated");
    }

    public function delete($id)
    {
        $this->vehiclModel->delete($id);
        return redirect()->route('index-vehicle')->with("fail", "Data Deleted");
    }

    public function restore($id)
    {
        $this->vehiclModel->set('deleted_at', null)->update($id);
        return redirect()->route('trash-index-vehicle')->with("success", "Data restored");
    }

    public function imgaeCheck($image)
    {
        $newName = $image->getRandomName();
        $path = 'image/bus';
        $image->move($path, $newName);
        return $path . '/' . $newName;
    }
}
