<?php

namespace Modules\Fleet\Controllers;

use App\Controllers\BaseController;
use App\Libraries\DeleteData\SoftwareSettings\Fleet as DeleteFleetData;
use Modules\Fleet\Models\FleetModel;
use App\Libraries\Rolepermission;
use Modules\Coupon\Models\CouponModel;
use Modules\Fitness\Models\FitnessModel;
use Modules\Fleet\Models\VehicleModel;
use Modules\Trip\Models\SubtripModel;
use Modules\Trip\Models\TripModel;
use Modules\Fleet\Models\Fleetimage;

class Fleet extends BaseController
{
    private $Viewpath;
    protected $fleetModel;
    protected $vehicleModel;
    protected $fitnessModel;
    protected $tripModel;
    protected $subTripModel;
    protected $couponModel;
    protected $session;
    protected $fImageModel;

    public function __construct()
    {
        $this->Viewpath = "Modules\Fleet\Views";
        $this->fleetModel = new FleetModel();
        $this->vehicleModel = new VehicleModel();
        $this->fitnessModel = new FitnessModel();
        $this->tripModel = new TripModel();
        $this->subTripModel = new SubtripModel();
        $this->couponModel = new CouponModel();
        $this->fImageModel = new Fleetimage();
    }

    public function new()
    {
        $data['module'] =    lang("Localize.fleet");
        $data['title']  =    lang("Localize.add_fleet");
        $data['pageheading'] = lang("Localize.add_fleet");

        echo view($this->Viewpath . '\fleet/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);
                }
            }
        }

        if ($this->request->getVar('last_seat') == null) {
            $lastseat = 0;
        } else {
            $lastseat = 1;
        }
        if ($this->request->getVar('forth_seat') == null) {
            $forth_seat = 0;
        } else {
            $forth_seat = 1;
        }
        if ($this->request->getVar('wc') == null) {
            $wc = 0;
        } else {
            $wc = 1;
        }


        $data = array(
            "type" => $this->request->getVar('type'),
            "layout" => $this->request->getVar('layout'),
            "last_seat" => $lastseat,
            "forth_seat" => $forth_seat,
            "wc" => $wc,
            "total_seat" => $this->request->getVar('total_seat'),
            "seat_number" => $this->request->getVar('seat_number'),
            "status" => $this->request->getVar('status'),
            "total_wait" => $this->request->getVar('total_wait'),
            "luggage_service" => $this->request->getVar('luggage_service'),
        );

        if ($this->validation->run($data, 'fleet')) {
            $fleetid = $this->fleetModel->insert($data);
            if (!empty($imgpath)) {
                foreach ($imgpath as $key => $imgvalue) {
                    $storedata[$key] = array(
                        "fleet_id" => $fleetid,
                        "img_path" => $imgvalue,
                    );
                }

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

            return redirect()->route('index-fleet')->with("success", "Data Save");
        } else {
            $data['validation'] = $this->validation;

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

            $data['pageheading'] = lang("Localize.add_fleet");

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

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

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

        $data['pageheading'] = lang("Localize.fleet_list");

        $rolepermissionLibrary = new Rolepermission();
        $add_data = "add_fleet";
        $list_data = "fleet_list";

        $data['add_data'] = $rolepermissionLibrary->create($add_data);
        $data['edit_data'] = $rolepermissionLibrary->edit($list_data);
        $data['delete_data'] = $rolepermissionLibrary->delete($list_data);

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

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

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

        $heading = lang("Localize.edit") . ' ' . lang("Localize.fleet");
        $data['pageheading'] = $heading;

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

    public function update($id)
    {
        $imgpath = array();
        $imgbusold = array();
        $imgbus =  $this->request->getFileMultiple('busimgedit');
        $imgbusold = $this->request->getPost('oldphoto') ?? [];
        foreach ($imgbusold as $oldImagePath) {
            $imgpath[] = $oldImagePath;
        }
        if ($imgbus[0]->isValid()) {
            $vehicaleImage = $this->fImageModel->where('fleet_id', $id)->findAll();
            foreach ($vehicaleImage as $key => $vehicalvalue) {
                $this->fImageModel->delete($vehicalvalue->id);
                if (!in_array($vehicalvalue->img_path, $imgpath)) {
                    if (file_exists($vehicalvalue->img_path)) {
                        @unlink($vehicalvalue->img_path);
                    }
                }
            }
            $this->fImageModel->purgeDeleted();

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

        if ($this->request->getVar('last_seat') == null) {
            $lastseat = 0;
        } else {
            $lastseat = 1;
        }
        if ($this->request->getVar('forth_seat') == null) {
            $forth_seat = 0;
        } else {
            $forth_seat = 1;
        }

        $validdata = array(
            "type" => $this->request->getVar('type'),
            "layout" => $this->request->getVar('layout'),
            "last_seat" => $lastseat,
            "forth_seat" => $forth_seat,
            "total_seat" => $this->request->getVar('total_seat'),
            "seat_number" => $this->request->getVar('seat_number'),
            "status" => $this->request->getVar('status'),
            "total_wait" => $this->request->getVar('total_wait'),
            "luggage_service" => $this->request->getVar('luggage_service'),
        );




        $data = array(
            "id" => $id,
            "type" => $this->request->getVar('type'),
            "layout" => $this->request->getVar('layout'),
            "last_seat" => $lastseat,
            "forth_seat" => $forth_seat,
            "total_seat" => $this->request->getVar('total_seat'),
            "seat_number" => $this->request->getVar('seat_number'),
            "status" => $this->request->getVar('status'),
            "total_wait" => $this->request->getVar('total_wait'),
            "luggage_service" => $this->request->getVar('luggage_service'),
        );

        if ($this->validation->run($validdata, 'fleet')) {
            $this->fleetModel->save($data);
            if (!empty($imgpath)) {
                foreach ($imgpath as $key => $imgvalue) {
                    $storedata[$key] = array(
                        "fleet_id" => $id,
                        "img_path" => $imgvalue,
                    );
                }
                $this->fImageModel->insertBatch($storedata);
            }
            return redirect()->route('index-fleet')->with("success", "Data Update");
        } else {
            $data['validation'] = $this->validation;

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

            echo view($this->Viewpath . '\fleet/edit', $data);
        }
    }
    public function getSeatLayout()
    {
        $subTripId = 1;
        // $fleetId = $this->request->getVar('fleet_id');
        $bookedSeats = $this->request->getVar('booked')??[];
        // $fleetInfo = $this->fleetTypeModel->find($fleetId);
        $fleetTotalSeat = $this->request->getVar('totalSeat');
        // print_r($fleetInfo);die;
        // build seat layout vars
        $seatLayout     = $this->request->getVar('seatLayout');
        $seatLayoutArr  = array_filter(explode('-', $seatLayout));
        $totalSeatInRow = array_sum($seatLayoutArr);
        $tSeatRowWithB  = $totalSeatInRow + count($seatLayoutArr) - 3;
        // print_r($tSeatRowWithB);die;
        $seatNumbers    = array_filter(explode(',', $this->request->getVar('seat_number')));
        // remove last seat
        // if fleet has last seat
        $lastSeat = '';
        // $fleetInfo->last_seat && $lastSeat = array_pop($seatNumbers);
        $seatinfo['forth_seat'] = $this->request->getVar('forth_seat');
        $seatinfo['lastSheet'] = $this->request->getVar('last_seat');
        $seatinfo['wc'] = $this->request->getVar('wc');


        // build seat group/row
        $seatRowGroup = array_chunk($seatNumbers, $totalSeatInRow);
        $seatRows = array_map(function ($singleRow) use ($seatLayoutArr, $tSeatRowWithB, $bookedSeats) {
        // print_r($tSeatRowWithB);die;
            $newSingleRow = array();
            $currentTotalIndex = 0;

            foreach ($singleRow as $seatRowIndex => $singleSeat) {
                $seatRowIndex++;
                $newSingleRow[] = array(
                    'seatName' => $singleSeat,
                    'isBooked' => in_array($singleSeat, $bookedSeats)
                );

                if (($seatRowIndex != count($singleRow)) && (current($seatLayoutArr) + $currentTotalIndex == $seatRowIndex)) {
                    $newSingleRow[] = '';
                    $currentTotalIndex += current($seatLayoutArr);
                    array_shift($seatLayoutArr);
                }
            }

            return array_pad($newSingleRow, $tSeatRowWithB, '');
        }, $seatRowGroup);

// print_r(count($seatRows));
// exit;
if(count($seatRows[count($seatRows)-1]) != count($seatRows[1])){
    $seatRows[count($seatRows)-2] = array_merge($seatRows[count($seatRows)-2],$seatRows[count($seatRows)-1]);
    unset($seatRows[count($seatRows)-1]);
}
// print_r($seatRows[count($seatRows)-2]);
// exit;
        // $lastRow = end($seatRows);
        // if ($previousRowIndex >= 0) {
        //     $previousRow = &$seatRows[$previousRowIndex];
        //     $outstandingSeats = array_splice($previousRow, $totalSeatInRow);
        //     $lastRow = array_merge($lastRow, $outstandingSeats);
        //     $seatRows[count($seatRows) - 1] = $lastRow;
        // }

        // print_r($seatRows);die;
        if ($lastSeat !== '') {
            // last seat exists
            // build last seat info
            $lastSeatInfo =  array(
                'seatName' => $lastSeat,
                'isBooked' => in_array($lastSeat, $bookedSeats) 
            );
            
            if (($lastBlankSpace = array_search('', end($seatRows))) !== false) {
                // an blank space exists in last row
                // last seat place into the last blank space
                $seatRows[count($seatRows) - 1][$lastBlankSpace] = $lastSeatInfo;
            } else {
                // create new row and last seat place into it
                $seatRows[][] = $lastSeatInfo;
            }
        }
        
        // print_r($seatRows);die;

        try {
            //if()
            $filePath = sprintf("%s\\ticket\\seatlayouts\\%s", 'Modules\Ticket\Views', $seatLayout);
            return view($filePath, compact('subTripId', 'seatRows', 'totalSeatInRow'));
        } catch (\Throwable $e) {
            // print_r($filePath);die;
            if($seatLayout =='4-1'){
                $filePath = sprintf("%s\\ticket\\seatlayouts\\layoutfinal2", 'Modules\Ticket\Views');
                return view($filePath, compact('subTripId', 'seatRows', 'totalSeatInRow','fleetTotalSeat','seatinfo'));
            }else if($seatLayout =='1-1'){
                $filePath = sprintf("%s\\ticket\\seatlayouts\\layoutfinal1-1", 'Modules\Ticket\Views');
                return view($filePath, compact('subTripId', 'seatRows', 'totalSeatInRow','fleetTotalSeat','seatinfo'));
            }else if($seatLayout =='1-2' || $seatLayout =='2-1'){
                $filePath = sprintf("%s\\ticket\\seatlayouts\\layoutfinal1-2", 'Modules\Ticket\Views');
                return view($filePath, compact('subTripId', 'seatRows', 'totalSeatInRow','fleetTotalSeat','seatinfo'));
            }else{
                $filePath = sprintf("%s\\ticket\\seatlayouts\\default3", 'Modules\Ticket\Views');
            }
            return view($filePath, compact('subTripId', 'seatRows', 'totalSeatInRow', 'seatinfo'));
        }
    }
    public function imgaeCheck($image)
    {
        $newName = $image->getRandomName();
        $path = 'image/fleet';
        $image->move($path, $newName);
        return $path . '/' . $newName;
    }
}
