<?php

namespace Modules\Trip\Controllers;

use App\Controllers\BaseController;
use App\Libraries\Rolepermission;
use CodeIgniter\Database\RawSql;
use Modules\Trip\Models\SubtripModel;
use Modules\Location\Models\LocationModel;
use Modules\Trip\Models\TripModel;
use Modules\Location\Models\StandModel;
use Modules\Trip\Models\PickdropModel;
class Subtrip extends BaseController
{

    protected $Viewpath;
    protected $tripModel;
    protected $subtripModel;
    protected $locationModel;
    protected $picdropModel;
    protected $standModel;
    protected $db;

    public function __construct()
    {
        $this->Viewpath = "Modules\Trip\Views";
        $this->tripModel = new TripModel;
        $this->subtripModel = new SubtripModel;
        $this->locationModel = new LocationModel;
        $this->standModel = new StandModel();
        $this->picdropModel = new PickdropModel();
        $this->db = \Config\Database::connect();
    }

    public function index($id)
    {
        $heading = lang("Localize.sub") . ' ' . lang("Localize.trip") . ' ' . lang("Localize.list");
        $data['pageheading'] = $heading;

        $subtrip_list = $this->subtripModel->where('trip_id', $id)->where('type', 'subtrip')->find();
        $FairHtml = "";

        $this->db->transStart();
        $classData = $this->db->table('seat_class')
                      ->select('id, name')
                      ->get()
                      ->getResultArray(); // Fetch data as an associative array
        // Convert into [id] => name format
        $seatClasses = array_column($classData, 'name', 'id');
        $this->db->transComplete();
        
        if(!empty($subtrip_list)){

            for ($i = 0; $i < count($subtrip_list); $i++){
                
                $FairHtml .= lang("Localize.adult")." ".lang("Localize.fair").": ".$subtrip_list[$i]->adult_fair;
            
                if(!empty($subtrip_list[$i]->subtrip_seatclass)){
                    $seatClassArr = json_decode($subtrip_list[$i]->subtrip_seatclass, 1);
                    if(!empty($seatClassArr)){
                        for($p = 0; $p < count($seatClassArr); $p++){
                            if($seatClassArr[$p]['seatClass'] && $seatClassArr[$p]['fare']){
                                $SeatClassNaem = "";
                                if(isset($seatClasses[$seatClassArr[$p]['seatClass']])){
                                    $SeatClassNaem = $seatClasses[$seatClassArr[$p]['seatClass']];
                                }
                                $FairHtml .= "</br>".$SeatClassNaem.": ".$seatClassArr[$p]['fare'];
                            }                        
                        }
                    }
                }
                $subtrip_list[$i]->FairHtml = $FairHtml;
            }
        }
        $data['subtrip'] = $subtrip_list;
        // /echo "<pre>";print_r($data['subtrip']);exit;
        $data['createTrip'] = $id;
        $data['delete_data'] = (new Rolepermission)->delete("trip_list");

        return view($this->Viewpath . '\subtrip\index', $data);
    }

    public function new($id)
    {
        $data['maintripid'] =  $id;

        // Build trip stopages
        $tripInfo = $this->tripModel->select('trips.stoppage')->where('trips.id', $id);
        
        $data['location'] = $this->locationModel
            ->where(new RawSql('FIND_IN_SET(locations.id, (' . $tripInfo->builder()->getCompiledSelect() . '))'))
            ->findAll();

        $this->db->transStart();
        $classData = $this->db->table('seat_class')
                      ->select('id, name')
                      ->get()
                      ->getResultArray(); // Fetch data as an associative array
        // Convert into [id] => name format
        $seatClasses = array_column($classData, 'name', 'id');
        $this->db->transComplete();

        $tripData = $this->tripModel->where('trips.id', $id)->first();
        $seatsFairArr = [];
        if(!empty($tripData) && (isset($tripData->seatclass) && $tripData->seatclass != "")){
            $seatsexistingdata = json_decode($tripData->seatclass, 1);
            if(is_array ($seatsexistingdata) && !empty($seatsexistingdata)){
                $seatsFairArr = $seatsexistingdata;
                for($p = 0; $p < count($seatsFairArr); $p++){
                    $seatsFairArr[$p]['seatClassName'] = "";
                    if(isset($seatClasses[$seatsFairArr[$p]['seatClass']])){
                        $seatsFairArr[$p]['seatClassName'] = $seatClasses[$seatsFairArr[$p]['seatClass']];
                    }
                }
            }
        }
        //echo "<pre>";print_r($seatsFairArr);exit;
        $data['seatsFairArr'] = $seatsFairArr;

        $heading = lang("Localize.add") . ' ' . lang("Localize.sub") . ' ' . lang("Localize.trip");
        $data['pageheading'] = $heading;
        $data['stand'] = $this->standModel->findAll();
        
        // print_r($data);die;

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

    public function create()
    {
        
        $picupdata = array();
        $dropdata = array();
        $show = $this->request->getVar('show') ?: 0;
        $pickLocation =  $this->request->getVar('pick_location_id');
        $dropLocation =  $this->request->getVar('drop_location_id');
        
        $busStandTime = $this->request->getVar('picktime');
        $busStandlocation = $this->request->getVar('picstand');
        $standDetails = $this->request->getVar('detail');
        $busStandtype = $this->request->getVar('type');
        $dropbusStandTime = $this->request->getVar('droptime');
        $dropbusStandlocation = $this->request->getVar('dropstand');
        $dropstandDetails = $this->request->getVar('dropdetail');
        $dropbusStandtype = $this->request->getVar('droptype');
         $distance = $this->request->getVar('distance');
        $tripimage = $this->request->getFile('imagesubtrip');
        $tripId = $this->request->getVar('id');
        

        $existingSubtrip = $this->subtripModel->where('pick_location_id', $pickLocation)->where('drop_location_id', $dropLocation)->where('trip_id', $tripId)->first();
        if(isset($existingSubtrip) && !empty($existingSubtrip)){
            return redirect()->back()->withInput()->with('fail', 'Subtrip already exists');
        }


        $tripImagePath = null;

        $stoppage = array_merge([$pickLocation], (array) $this->request->getVar('stoppage'), [$dropLocation]);
        $stoppage = implode(",", array_filter($stoppage));

        if ($show == 1) {
            if ($tripimage->isValid() && !$tripimage->hasMoved()) {
                $tripImagePath = $this->imgaeCheck($tripimage);
            } else {
                return redirect()->back()->withInput()->with('fail', 'image fill reqired');
            }
        }

        $mergedData = [];
        if(isset($_POST['seatClass']) && !empty($_POST['seatClass'])){
            foreach ($_POST['seatClass'] as $key => $seatClass) {

                $seats = "";
                if(isset($_POST['seatNo'][$key][0]) && $_POST['seatNo'][$key][0] != ""){
                    $seats = explode(", ", $_POST['seatNo'][$key][0]);
                }
                $mergedData[] = [
                    'seatClass' => $seatClass,
                    'seatNo' => $seats,
                    'fare' => $_POST['fares'][$key]
                ];
            }

        }
        

        $subtripData = array(
            "trip_id" => $this->request->getVar('id'),
            "pick_location_id" => $this->request->getVar('pick_location_id'),
            "drop_location_id" => $this->request->getVar('drop_location_id'),
            "stoppage" => $stoppage,
            "adult_fair" => $this->request->getVar('adult_fair'),
            "child_fair" => $this->request->getVar('child_fair'),
            "special_fair" => $this->request->getVar('special_fair'),
            "type" => 'subtrip',
            "distance" => $distance,
            "status" => $this->request->getVar('status'),
            "show" => $show,
            "imglocation" => $tripImagePath,
            "subtrip_seatclass" => json_encode($mergedData),
            "journey_hour" => $this->request->getVar('journey_hour'),
        );

        if ($this->validation->run($subtripData, 'subtrip')) {
                
            $subtripid = $this->subtripModel->insert($subtripData);
            $maintripid = $this->request->getVar('id');
        // print_r($subtripid);die;
           foreach ($busStandTime as $key => $pickupvalue) {
                $picupdata[$key] = array(
                    "stand_id" => $busStandlocation[$key],
                    "trip_id" => $subtripid,
                    "time" => $pickupvalue,
                    "trip_type" => 2,
                    "type" => (int) $busStandtype[$key],
                    "detail" => $standDetails[$key],
                );
            }

            foreach ($dropbusStandTime as $dkey => $dropvalue) {
                $dropdata[$dkey] = array(
                    "stand_id" => $dropbusStandlocation[$dkey],
                    "trip_id" => $subtripid,
                    "time" => $dropvalue,
                    "trip_type" => 2,
                    "type" => (int) $dropbusStandtype[$dkey],
                    "detail" => $dropstandDetails[$dkey],
                );
            }

            // insert pick stands
            // and insert drop stands
            $this->picdropModel->insertBatch($picupdata);
            $this->picdropModel->insertBatch($dropdata);


            $trip = array();
            array_push($trip, $maintripid);

            return redirect()->route('index-Subtrip', $trip)->with("success", "Data Save");
        }

        return redirect()->back()->withInput()->with('fail', $this->validation->listErrors());
    }

    public function edit($id)
    {   
        $data['viewpath'] = $this->Viewpath;
        $data['subtrip'] = $subtripInfo = $this->subtripModel->find($id);
        
        $this->db->transStart();
        $classData = $this->db->table('seat_class')
                      ->select('id, name')
                      ->get()
                      ->getResultArray(); // Fetch data as an associative array
        // Convert into [id] => name format
        $seatClasses = array_column($classData, 'name', 'id');
        $this->db->transComplete();

        $seatsFairArr = [];
        if(isset($data['subtrip']->subtrip_seatclass) && $data['subtrip']->subtrip_seatclass != ""){
            $seatsexistingdata = json_decode($data['subtrip']->subtrip_seatclass, 1);
            if(is_array ($seatsexistingdata) && !empty($seatsexistingdata)){
                $seatsFairArr = $seatsexistingdata;
                for($p = 0; $p < count($seatsFairArr); $p++){
                    $seatsFairArr[$p]['seatClassName'] = "";
                    if(isset($seatClasses[$seatsFairArr[$p]['seatClass']])){
                        $seatsFairArr[$p]['seatClassName'] = $seatClasses[$seatsFairArr[$p]['seatClass']];
                    }
                }
            }
        }
        if(empty($seatsFairArr)){
            $tripData = $this->tripModel->where('id', $subtripInfo->trip_id)->first();
            if(isset($tripData->seatclass) && $tripData->seatclass != ""){


                $seatsexistingdata = json_decode($tripData->seatclass, 1);
                if(is_array ($seatsexistingdata) && !empty($seatsexistingdata)){
                    $seatsFairArr = $seatsexistingdata;
                    for($p = 0; $p < count($seatsFairArr); $p++){
                        $seatsFairArr[$p]['seatClassName'] = "";
                        if(isset($seatClasses[$seatsFairArr[$p]['seatClass']])){
                            $seatsFairArr[$p]['seatClassName'] = $seatClasses[$seatsFairArr[$p]['seatClass']];
                        }
                    }
                }
            }
        }
        $data['seatsFairArr'] = $seatsFairArr;

        // Build trip stopages
        $tripInfo = $this->tripModel->select('trips.stoppage')->where('trips.id', $subtripInfo->trip_id);

        $data['location'] = $this->locationModel
            ->where(new RawSql('FIND_IN_SET(locations.id, (' . $tripInfo->builder()->getCompiledSelect() . '))'))
            ->findAll();
        $data['arrival'] = $this->picdropModel->where('trip_id', $subtripInfo->trip_id)->where('type', 1)->where('trip_type',2)->findAll();
        if(empty($data['arrival'])){
            $data['arrival'] = $this->picdropModel->where('trip_id', $subtripInfo->id)->where('type', 1)->where('trip_type',2)->findAll();
        }
        $data['departure'] = $this->picdropModel->where('trip_id', $subtripInfo->trip_id)->where('type', 0)->where('trip_type',2)->findAll();
        if(empty($data['departure'])){
            $data['departure'] = $this->picdropModel->where('trip_id', $subtripInfo->id)->where('type', 0)->where('trip_type',2)->findAll();
        }

        $data['stoppage'] = explode(",", $subtripInfo->stoppage);

        $heading = lang("Localize.edit") . ' ' . lang("Localize.sub") . ' ' . lang("Localize.trip");
        $data['pageheading'] = $heading;
        $data['stand'] = $this->standModel->findAll();
        // print_r($data);
        // exit;
        return view($this->Viewpath . '\subtrip/edit', $data);
    }

    public function update($subtrip_id)
    {   
        // print_r($subtrip_id);die;
        $show = $this->request->getVar('show') ?: 0;
        $pickLocation =  $this->request->getVar('pick_location_id');
        $dropLocation =  $this->request->getVar('drop_location_id');
        
        $busStandTime = $this->request->getVar('picktime');
        $busStandlocation = $this->request->getVar('picstand');
        $standDetails = $this->request->getVar('detail');
        $busStandtype = $this->request->getVar('type');
        $dropbusStandTime = $this->request->getVar('droptime');
        $dropbusStandlocation = $this->request->getVar('dropstand');
        $dropstandDetails = $this->request->getVar('dropdetail');
        $dropbusStandtype = $this->request->getVar('droptype');
        $distance = $this->request->getVar('distance');
        
        $tripimage = $this->request->getFile('imagesubtrip');
        $tripImagePath = $this->request->getVar('imagepath');
        if(!empty($busStandTime)){
            foreach ($busStandTime as $key => $pickupvalue) {
                $picupdata[$key] = array(
                    "stand_id" => $busStandlocation[$key],
                    "trip_id" => $subtrip_id,
                    "trip_type" => 2,
                    "time" => $busStandTime[$key],
                    "type" => (int) $busStandtype[$key],
                    "detail" => $standDetails[$key],
                );
            }
        }

        if(!empty($dropbusStandTime)){
            foreach ($dropbusStandTime as $dkey => $dropvalue) {
                $dropdata[$dkey] = array(
                    "stand_id" => $dropbusStandlocation[$dkey],
                    "trip_id" => $subtrip_id,
                    "trip_type" => 2,
                    "time" => $dropbusStandTime[$dkey],
                    "type" => (int) $dropbusStandtype[$dkey],
                    "detail" => $dropstandDetails[$dkey],
                );
            }
        }
        
        //$this->picdropModel->where('trip_id', $subtrip_id)->where('trip_type',2)->delete('', true);
        $this->picdropModel->where('trip_id', $subtrip_id)->where('trip_type', 2)->delete();


        if(isset($picupdata)){
            $this->picdropModel->insertBatch($picupdata);    
        }
        if(isset($dropdata)){
            $this->picdropModel->insertBatch($dropdata);    
        }


        $stoppage = array_merge([$pickLocation], (array) $this->request->getVar('stoppage'), [$dropLocation]);
        $stoppage = implode(",", array_filter($stoppage));

        if ($show == 1) {
            if ($tripimage->isValid() && !$tripimage->hasMoved()) {
                $tripImagePath = $this->imgaeCheck($tripimage);
            } elseif (empty($tripImagePath)) {
                return redirect()->back()->withInput()->with('fail', 'image fill reqired');;
            }
        }

        $mergedData = [];
        if(isset($_POST['seatClass']) && !empty($_POST['seatClass'])){
            foreach ($_POST['seatClass'] as $key => $seatClass) {

                $seats = "";
                if(isset($_POST['seatNo'][$key][0]) && $_POST['seatNo'][$key][0] != ""){
                    $seats = explode(", ", $_POST['seatNo'][$key][0]);
                }
                $mergedData[] = [
                    'seatClass' => $seatClass,
                    'seatNo' => $seats,
                    'fare' => $_POST['fares'][$key]
                ];
            }
        }


        $subtripData = array(
            "id" => $subtrip_id,
            "trip_id" => $this->request->getVar('trip_id'),
            "pick_location_id" => $pickLocation,
            "drop_location_id" => $dropLocation,
            "stoppage" => $stoppage,
            "adult_fair" => $this->request->getVar('adult_fair'),
            "child_fair" => $this->request->getVar('child_fair'),
            "special_fair" => $this->request->getVar('special_fair'),
            "type" => 'subtrip',
            "distance" => $distance,
            "status" => $this->request->getVar('status'),
            "show" => $show,
            "imglocation" => $tripImagePath,
            "subtrip_seatclass" => json_encode($mergedData),
            "journey_hour" => $this->request->getVar('journey_hour'),
        );

        if ($this->validation->run($subtripData, 'subtrip')) {
            $this->subtripModel->save($subtripData);
            $maintripid = $this->request->getVar('trip_id');
            
            

            $trip = array();
            array_push($trip, $maintripid);
            return redirect()->route('index-Subtrip', $trip)->with("success", "Data Save");
        }

        return redirect()->back()->withInput()->with('fail', $this->validation->listErrors());
    }

    public function delete($id)
    {
        $mainid = $this->subtripModel->where('id', $id)->where('type', 'subtrip')->first();
        $this->subtripModel->delete($id);
        $trip = array();
        array_push($trip, $mainid->trip_id);
        return redirect()->route('index-Subtrip', $trip)->with("fail", "Data Deleted");
    }

    public function imgaeCheck($image)
    {
        $newName = $image->getRandomName();
        $path = 'image/subtrip';
        $image->move($path, $newName);
        return $path . '/' . $newName;
    }
    public function status($subTripId)
    {
        $subTripStatus = $this->subtripModel->find($subTripId);

        if ($subTripStatus->status == 1) {
            $upData = array(
                "id" => $subTripId,
                "status" => 0
            );
            $this->subtripModel->save($upData);

        }
        if ($subTripStatus->status == 0) {
            if($subTripStatus->trip_id > 0){
                $tripData = $this->tripModel->find($subTripStatus->trip_id);
                if($tripData->status == 0){
                    return redirect()->route('index-Subtrip',[$subTripStatus->trip_id])->with("fail", "please activate the trip");
                }
            }
            $upData = array(
                "id" => $subTripId,
                "status" => 1
            );
            $this->subtripModel->save($upData);
        }
        return redirect()->route('index-Subtrip',[$subTripStatus->trip_id])->with("success", "Data Update");
    }
}
