<?php

namespace Modules\Ticket\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;
use Modules\Employee\Models\EmployeeModel;
use Modules\Fleet\Models\FleetModel;
use Modules\Fleet\Models\VehicleModel;
use Modules\Location\Models\LocationModel;
use Modules\Location\Models\StandModel;
use Modules\Paymethod\Models\PaymethodModel;
use Modules\Schedule\Models\ScheduleModel;
use Modules\Tax\Models\TaxModel;
use Modules\Ticket\Models\JourneylistModel;
use Modules\Ticket\Models\PartialpaidModel;
use Modules\Ticket\Models\TicketModel;
use Modules\Ticket\Models\MaxtimeModel;
use Modules\Trip\Models\FacilityModel;
use Modules\Trip\Models\PickdropModel;
use Modules\Trip\Models\StuffassignModel;
use Modules\Trip\Models\SubtripModel;
use Modules\Trip\Models\TripModel;
use Modules\User\Models\UserDetailModel;
use Modules\User\Models\UserModel;
use Modules\Company\Models\CompanyModel;
use Modules\Role\Models\RoleModel;

class Journeylist extends BaseController
{
    protected $Viewpath;
    protected $ticketModel;
    protected $tripModel;
    protected $subtripModel;
    protected $stuffassignModel;
    protected $locationModel;
    protected $employeeModel;
    protected $fleetTypeModel;
    protected $scheduleeModel;
    protected $vehicleModel;
    protected $standModel;
    protected $picdropModel;
    protected $facilitypModel;
    protected $taxModel;
    protected $db;
    protected $paymethodModel;
    protected $userModel;
    protected $userDetailModel;
    protected $journeylistModel;
    protected $partialpaidModel;
    protected $maxtimeModel;
    protected $CompanyModel;
    protected $roleModel;

    public function __construct()
    {

        $this->Viewpath = "Modules\Ticket\Views";
        $this->ticketModel = new TicketModel();
        $this->tripModel = new TripModel();
        $this->subtripModel = new SubtripModel();
        $this->stuffassignModel = new StuffassignModel();
        $this->locationModel = new LocationModel();
        $this->employeeModel = new EmployeeModel();
        $this->fleetTypeModel = new FleetModel();
        $this->vehicleModel = new VehicleModel();
        $this->scheduleeModel = new ScheduleModel();
        $this->standModel = new StandModel();
        $this->picdropModel = new PickdropModel();
        $this->facilitypModel = new FacilityModel();
        $this->taxModel = new TaxModel();
        $this->db = \Config\Database::connect();
        $this->paymethodModel = new PaymethodModel();

        $this->userModel = new UserModel();
        $this->userDetailModel = new UserDetailModel();

        $this->journeylistModel = new JourneylistModel();
        $this->partialpaidModel = new PartialpaidModel();

        $this->maxtimeModel = new MaxtimeModel();
        $this->CompanyModel = new CompanyModel();
        $this->roleModel = new RoleModel();
    }


    function new()
    {
        $rolepermissionLibrary = new \App\Libraries\Rolepermission();
        if (!$rolepermissionLibrary->read('journey_list') && (int)session()->get('role_id') != 1) {
            return redirect()->back()->with('fail', 'You do not have permission to access journey lists.');
        }
        $data['pick_location_id'] = null;
        $data['drop_location_id'] = null;
        $data['filterjourneydate'] = null;
        $data['filterreturndate'] = null;
        $data['fleet_id'] = null;

        $data['filterpath'] = $this->Viewpath;
        $data['location'] = $this->locationModel->findAll();
        $data['fleet_type'] = $this->fleetTypeModel->findAll();

        $data['module'] =    lang("Localize.ticket_booking");
        $data['title']  =    lang("Localize.journey_list");

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

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

    public function findtrip()
    {
        $rolepermissionLibrary = new \App\Libraries\Rolepermission();
        if (!$rolepermissionLibrary->read('journey_list') && (int)session()->get('role_id') != 1) {
            return redirect()->back()->with('fail', 'You do not have permission to access journey lists.');
        }
        $pick_location_id = $this->request->getVar('pick_location_id');
        $drop_location_id = $this->request->getVar('drop_location_id');
        $filterjourneydate = $this->request->getVar('filterjourneylistdate');
        $fleet_id = $this->request->getVar('fleet_id');

        $journeyDate = egypt_date((string) $filterjourneydate);
        if ($redirect = $this->redirectIfBackdatedJourneyListDenied($journeyDate)) {
            return $redirect;
        }

        $company_id        = $this->request->getVar('company_id') ?: session('company_id');
        $data['pick_location_id'] = $pick_location_id;
        $data['drop_location_id'] = $drop_location_id;
        $data['filterjourneydate'] = $filterjourneydate;
        $data['company_id'] = $company_id;

        $data['fleet_id'] = $fleet_id;

        $data['filterpath'] = $this->Viewpath;
        $data['location'] = $this->locationModel->findAll();
        $data['fleet_type'] = $this->fleetTypeModel->findAll();

        $checked_company_id = 0;
        if(is_array(session()->get('company_id')) > 0 && session()->get('role_id') != "1"){
            if (strpos(session()->get('company_id'), ',')) { 
                $checked_company_id = explode(',', session()->get('company_id'));
            } else {
                $checked_company_id = [session()->get('company_id')];
            }

            // $checked_company_id = session()->get('company_id');
        } else {
            if (strpos($company_id, ',')) { 
                $checked_company_id = explode(',', $company_id);
            } else {
                $checked_company_id = [$company_id];
            }
            // $checked_company_id = $company_id;
        }


        // bind search query
        //updated on 16-01-2025

        $this->subtripModel
            ->select('trips.id as tripid, trips.*, ' . \App\Libraries\TripDisplaySupport::parentMetricsSelectFragment() . ', fleets.*, schedules.*, vehicles.*, subtrips.id as subtripId, subtrips.*,companies.name as company')

            ->join('trips', 'trips.id = subtrips.trip_id')
            ->join('fleets', 'fleets.id = trips.fleet_id')
            ->join('schedules', 'schedules.id = trips.schedule_id')
            ->join('vehicles', 'vehicles.id = trips.vehicle_id',"left")
            ->join('companies', 'companies.id = trips.company_id',"left")

            ->groupStart()
                ->groupStart()
                    ->where('subtrips.pick_location_id', $pick_location_id)
                    ->where('subtrips.drop_location_id', $drop_location_id)
                ->groupEnd()

                ->orGroupStart()
                    ->whereIn('subtrips.trip_id', function ($subQuery) use ($pick_location_id, $drop_location_id) {
                        $subQuery
                            ->select('sm.trip_id')
                            ->from('subtrips sm')
                            ->where('sm.pick_location_id', $pick_location_id)
                            ->where('sm.drop_location_id', $drop_location_id)
                            ->where('sm.type', 'subtrip');
                    })
                    ->where('subtrips.type', 'main')
                ->groupEnd()
            ->groupEnd()
            ->where('subtrips.status', 1);

            $nonEmptyCompanyId = array_filter($checked_company_id);
            if(!empty($nonEmptyCompanyId)){
                $this->subtripModel->whereIn('trips.company_id', $nonEmptyCompanyId);
            }
                

            $this->subtripModel->orderBy('subtrips.id', 'DESC');

        $fleet_id && $this->subtripModel->where('trips.fleet_id', $fleet_id);

        //OLD query
        // $this->subtripModel
        //     ->select('trips.id as tripid, trips.*, fleets.*, schedules.*, vehicles.*, subtrips.id as subtripId, subtrips.*')

        //     ->join('trips', 'trips.id = subtrips.trip_id')
        //     ->join('fleets', 'fleets.id = trips.fleet_id')
        //     ->join('schedules', 'schedules.id = trips.schedule_id')
        //     ->join('vehicles', 'vehicles.id = trips.vehicle_id',"left")

        //     ->groupStart()
        //     ->where('subtrips.pick_location_id', $pick_location_id)
        //     ->where('subtrips.drop_location_id', $drop_location_id);
        //     if($checked_company_id){
        //         $this->subtripModel->whereIn('trips.company_id', $checked_company_id);   
        //     }
        //     $this->subtripModel->groupEnd()

        //     ->orGroupStart()
        //     ->whereIn('subtrips.trip_id', function ($subQuery) use ($pick_location_id, $drop_location_id, $checked_company_id) {
        //         $subQuery
        //             ->select('sm.trip_id')
        //             ->from('subtrips sm')
        //             ->where('sm.pick_location_id', $pick_location_id)
        //             ->where('sm.drop_location_id', $drop_location_id)
        //             ->where('sm.type', 'subtrip');
        //         if($checked_company_id){
        //             $subQuery->whereIn('trips.company_id', $checked_company_id);
        //         }
        //     })
        //     ->where('subtrips.type', 'main')
        //     ->groupEnd()

        //     ->orderBy('subtrips.id', 'DESC');

        // $fleet_id && $this->subtripModel->where('trips.fleet_id', $fleet_id);

        // $query = $this->subtripModel->builder()->getCompiledSelect();dd($query);

        $alltriplist = $this->subtripModel->findAll();
        foreach ($alltriplist as $tripRow) {
            \App\Libraries\TripDisplaySupport::applyParentTripDistanceAndHours($tripRow);
        }
        $data['alltriplist'] = $alltriplist;
        $data['module'] = lang("Localize.ticket_booking");
        $data['title']  = lang("Localize.journey_list");
        $data['pageheading'] = lang("Localize.journey_list");
        $data['companies'] = $this->CompanyModel->findAll();

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

    public function getJourneylistData($tripid, $date, $print)
    {
        $rolepermissionLibrary = new \App\Libraries\Rolepermission();
        if (!$rolepermissionLibrary->read('journey_list') && (int)session()->get('role_id') != 1) {
            return redirect()->back()->with('fail', 'You do not have permission to access journey lists.');
        }
        $company_id = session()->get('company_id');
        if (strpos($company_id, ',')) { 
            $company_ids = explode(',', $company_id);
        } else {
            $company_ids = [$company_id];
        }

        $searchDate = egypt_date((string) $date);
        if ($redirect = $this->redirectIfBackdatedJourneyListDenied($searchDate)) {
            return $redirect;
        }

        $journeyDateHelper = new \App\Libraries\TripJourneyDateHelper();
        // Admin journey list: search date = bus run / manifest day (e.g. 20 Aug for 21 Aug 3 AM BB→GG boarding).
        $journeyListQuery = $this->journeylistModel
            ->select('journeylists.*, companies.name as company_name, tickets.note as note, trips.seatclass as seatClass, tickets.bookby_user_id as bookby_user_id, tickets.bookby_user_type as bookby_user_type, tickets.journeydata as ticket_journeydata')
            ->join('trips', 'trips.id = journeylists.trip_id')
            ->join('tickets', 'tickets.booking_id = journeylists.booking_id', 'left')
            ->join('companies', 'trips.company_id = companies.id', 'left')
            ->where('journeylists.trip_id', $tripid);
        $journeyDateHelper->applyJourneyListManifestDatePrefetch($journeyListQuery, $searchDate);
        $journeyListQuery
            ->where('tickets.cancel_status', 0)
            ->where('tickets.refund', 0)
            ->orderBy('tickets.seatnumber', 'ASC')
            ->withDeleted();

        if (is_array($company_ids) && !empty($company_ids) && session()->get('role_id') != '1') {
            $journeyListQuery->whereIn('trips.company_id', $company_ids);
        }

        $journeyList = $journeyListQuery->findAll();

        $journeyDateHelper->warmBoardingDateCache($journeyList);

        // Preload tickets for all bookings on this manifest (one query)
        $bookingIds = array_values(array_unique(array_filter(array_map(static function ($row) {
            return $row->booking_id ?? '';
        }, $journeyList))));

        $ticketByBooking = [];
        if (!empty($bookingIds)) {
            foreach ($this->ticketModel
                ->select('booking_id, seatnumber, journeydata')
                ->whereIn('booking_id', $bookingIds)
                ->where('cancel_status', 0)
                ->withDeleted()
                ->findAll() as $ticketRow) {
                $ticketByBooking[$ticketRow->booking_id] = $ticketRow;
            }
        }

        $CheckBookingId = "";
        $NewFirstName = "";
        $NewLastName = "";
        $NewPhone = "";
        $CheckRecordindex = 0;

        foreach ($journeyList as $key => $value) {
            $ticketJourney = isset($ticketByBooking[$value->booking_id ?? ''])
                ? (string) ($ticketByBooking[$value->booking_id]->journeydata ?? '')
                : (string) ($value->ticket_journeydata ?? '');

            $value->boarding_date = $journeyDateHelper->getPassengerBoardingDateForDisplay(
                (int) $value->trip_id,
                (int) $value->subtrip_id,
                $ticketJourney !== '' ? $ticketJourney : $value->journeydate,
                (int) $value->pick_stand_id,
                $searchDate
            );

            $bookUserType = $value->bookby_user_type ?? "";
            
            if ($value->booking_id != $CheckBookingId) {
                $NewFirstName = $value->first_name;
                $NewLastName = $value->last_name;
                $NewPhone = $value->phone;
                $CheckBookingId = $value->booking_id;
                $CheckRecordindex = 0;
            }

            $value->first_name  = $NewFirstName;
            $value->last_name   = $NewLastName;
            $value->phone       = $NewPhone;
            $value->bookby_user_type = $bookUserType ?: "offline";

            if (!empty($value->booking_id) && isset($ticketByBooking[$value->booking_id])) {
                $existSeats = $ticketByBooking[$value->booking_id]->seatnumber ?? "";
                $BookingRecords = array_values(array_filter(explode(',', $existSeats)));
                if (isset($BookingRecords[$CheckRecordindex])) {
                    $value->seatnumbers = $BookingRecords[$CheckRecordindex];
                    $CheckRecordindex++;
                }
            }
        }

        $journeyList = array_values(array_filter($journeyList, function ($row) use ($searchDate, $ticketByBooking) {
            return $this->matchesJourneyListSearchRow($row, $searchDate, $ticketByBooking);
        }));

        usort($journeyList, function ($a, $b) {
            return (int)$a->seatnumbers <=> (int)$b->seatnumbers;
        });
        $data['pageheading'] = lang("Localize.journey_list");


        // show section copu
        $namefacility = array();
        $stopagepoint = array();
        $start = null;
        $destination = null;



        $gettripdata =  $this->tripModel
                            ->join('companies', 'companies.id = trips.company_id', 'left')
                            ->withDeleted()->find($tripid);
        $company_name = $gettripdata->name ?? "" ;

        $subtripIds = array_values(array_unique(array_filter(array_map(static function ($row) {
            return (int) ($row->subtrip_id ?? 0);
        }, $journeyList))));

        $mainSubtrip = $this->subtripModel
            ->select('id')
            ->where('trip_id', $tripid)
            ->where('type', 'main')
            ->first();
        if ($mainSubtrip) {
            $subtripIds[] = (int) $mainSubtrip->id;
        }
        $subtripIds = array_values(array_unique($subtripIds));
        $pickdropTripIds = $this->pickdropTripIdsForJourneyList((int) $tripid, $subtripIds);

        $pickdropById = [];
        if (!empty($pickdropTripIds)) {
            foreach ($this->picdropModel
                ->select('pickdrops.id as pickdropid, pickdrops.time, stands.name')
                ->join('stands', 'stands.id = pickdrops.stand_id')
                ->whereIn('pickdrops.trip_id', $pickdropTripIds)
                ->withDeleted()
                ->findAll() as $pd) {
                $pickdropById[(int) $pd->pickdropid] = $pd;
            }
        }

        $this->applyMissingPickdropStandLabels($journeyList, $pickdropById);

        $locationIds = [(int) ($gettripdata->pick_location_id ?? 0), (int) ($gettripdata->drop_location_id ?? 0)];
        foreach ($journeyList as $row) {
            $locationIds[] = (int) ($row->pick_location_id ?? 0);
            $locationIds[] = (int) ($row->drop_location_id ?? 0);
        }
        if (!empty($gettripdata->stoppage)) {
            foreach (explode(',', (string) $gettripdata->stoppage) as $stopId) {
                $locationIds[] = (int) trim($stopId);
            }
        }
        $locationIds = array_values(array_unique(array_filter($locationIds)));

        $locationMap = [];
        if (!empty($locationIds)) {
            foreach ($this->locationModel->whereIn('id', $locationIds)->withDeleted()->findAll() as $loc) {
                $locationMap[$loc->id] = $loc->name;
            }
        }

        foreach ($journeyList as $picdropvalue) {
            $picdropvalue->pick_loc_name = $locationMap[$picdropvalue->pick_location_id] ?? '';
            $picdropvalue->drop_loc_name = $locationMap[$picdropvalue->drop_location_id] ?? '';

            $pickPd = $pickdropById[(int) ($picdropvalue->pick_stand_id ?? 0)] ?? null;
            if ($pickPd) {
                $picdropvalue->picstand = $pickPd->name . '(' . $pickPd->time . ')';
            }

            $dropPd = $pickdropById[(int) ($picdropvalue->drop_stand_id ?? 0)] ?? null;
            if ($dropPd) {
                $picdropvalue->dropstand = $dropPd->name . '(' . $dropPd->time . ')';
            }
        }

        $start = $locationMap[$gettripdata->pick_location_id] ?? null;
        $destination = $locationMap[$gettripdata->drop_location_id] ?? null;


        $data['from'] = $start;
        $data['to'] = $destination;




        $data['schedule'] = $this->scheduleeModel->withDeleted()->find($gettripdata->schedule_id);

        $getfacility = $gettripdata->facility;

        if (!empty($getfacility)) {

            $facility = explode(",", $getfacility);
            foreach ($facility as $key => $facilityvalue) {
                $facilityname =  $this->facilitypModel->withDeleted()->find($facilityvalue);
                array_push($namefacility, $facilityname->name);
            }
            $data['facility'] = implode(", ", $namefacility);
        } else {
            $data['facility'] = "No facility";
        }


        $getstopagepoint = $gettripdata->stoppage;

        if (!empty($getstopagepoint)) {
            foreach (explode(',', $getstopagepoint) as $stopvalue) {
                $stopId = (int) trim($stopvalue);
                if ($stopId > 0 && isset($locationMap[$stopId])) {
                    $stopagepoint[] = $locationMap[$stopId];
                }
            }
            $data['stopagepoint'] = !empty($stopagepoint) ? implode(', ', $stopagepoint) : 'No Stoppage Point';
        } else {
            $data['stopagepoint'] = "No Stoppage Point";
        }


        $drivername =  array();
        $assistance =  array();
        $driver =  $this->stuffassignModel->select('stuffassigns.*,employees.*')
            ->join('employees', 'employees.id = stuffassigns.employee_id')
            ->where('trip_id', $tripid)
            ->where('DATE(stuffassigns.created_at)', $date)
            ->withDeleted()
            ->findAll();
    
        // print_r($driver);die;
        $data['drivephone'] = "";
        $data['assistphone'] = "";
        foreach ($driver as $key => $dvalue) {
            if ($dvalue->employee_type == 1) {
                array_push($drivername, $dvalue->first_name . ' ' . $dvalue->last_name);
                $data['drivephone'] = $dvalue->phone;
            } else {
                array_push($assistance, $dvalue->first_name . ' ' . $dvalue->last_name);
                $data['assistphone'] = $dvalue->phone;
            }
        }

        $data['drivername'] = implode(", ", $drivername);
        $data['assistance'] = implode(", ", $assistance);


        $data['pageheading'] = lang("Localize.journey_list");
        $data['pickdrop'] = !empty($pickdropTripIds)
            ? $this->picdropModel
                ->select('pickdrops.*,stands.*,pickdrops.id as pickdropid')
                ->join('stands', 'stands.id = pickdrops.stand_id')
                ->whereIn('pickdrops.trip_id', $pickdropTripIds)
                ->withDeleted()
                ->findAll()
            : [];
        $this->db->transStart();
        $classData = $this->db->table('seat_class')
                        ->get()
                        ->getResultArray();
        $this->db->transComplete();

        $classArray = array_column($classData, 'name', 'id');

        foreach($journeyList as $k=>$journeyListData){
            $seatclass = implode(", ", array_values($this->getSeatClasses($journeyListData->seatClass, $journeyListData->seatnumbers, $classArray)));
            $journeyList[$k]->seatclass  = is_array($seatclass) && !empty($seatclass) ? $seatclass[0] : $seatclass;
        }

        $data['journeydate'] = $searchDate;
        $data['journeylist'] = $journeyList;
        $data['tripId'] = $tripid;
        $data['date'] = $searchDate;
        $data['company_name'] = $company_name;
        
        
        // print_r($data);die;

        if ($print == 0) {
// return "gfdgd";
            $data['module'] =    lang("Localize.ticket_booking");
            $data['title']  =    lang("Localize.journey_list");
            return view($this->Viewpath . '\journeylist\show', $data);
        }
        return view($this->Viewpath . '\journeylist\print', $data);
    }

    /**
     * pickdrops.trip_id is usually subtrips.id; main-route rows use trips.id (e.g. Cairo→Dahab on trip 75).
     *
     * @param list<int> $subtripIds
     * @return list<int>
     */
    private function pickdropTripIdsForJourneyList(int $mainTripId, array $subtripIds): array
    {
        $ids = $subtripIds;
        if ($mainTripId > 0) {
            $ids[] = $mainTripId;
        }

        return array_values(array_unique(array_filter(array_map('intval', $ids))));
    }

    /**
     * Resolve stand labels by pickdrops.id when the first query missed (main trip trip_id = trips.id).
     *
     * @param list<object> $journeyList
     * @param array<int, object> $pickdropById
     */
    private function applyMissingPickdropStandLabels(array $journeyList, array &$pickdropById): void
    {
        $missingIds = [];
        foreach ($journeyList as $row) {
            $pickId = (int) ($row->pick_stand_id ?? 0);
            $dropId = (int) ($row->drop_stand_id ?? 0);
            if ($pickId > 0 && !isset($pickdropById[$pickId])) {
                $missingIds[] = $pickId;
            }
            if ($dropId > 0 && !isset($pickdropById[$dropId])) {
                $missingIds[] = $dropId;
            }
        }

        $missingIds = array_values(array_unique($missingIds));
        if ($missingIds === []) {
            return;
        }

        foreach ($this->picdropModel
            ->select('pickdrops.id as pickdropid, pickdrops.time, stands.name')
            ->join('stands', 'stands.id = pickdrops.stand_id')
            ->whereIn('pickdrops.id', $missingIds)
            ->withDeleted()
            ->findAll() as $pd) {
            $pickdropById[(int) $pd->pickdropid] = $pd;
        }

        foreach ($journeyList as $row) {
            if (!isset($row->picstand)) {
                $pickPd = $pickdropById[(int) ($row->pick_stand_id ?? 0)] ?? null;
                if ($pickPd) {
                    $row->picstand = $pickPd->name . '(' . $pickPd->time . ')';
                }
            }
            if (!isset($row->dropstand)) {
                $dropPd = $pickdropById[(int) ($row->drop_stand_id ?? 0)] ?? null;
                if ($dropPd) {
                    $row->dropstand = $dropPd->name . '(' . $dropPd->time . ')';
                }
            }
        }
    }

    /**
     * Manifest filter: bus run day from journeylists.journeydate only (tickets.journeydata ignored).
     */
    private function matchesJourneyListSearchRow(object $row, string $searchDate, array $ticketByBooking = []): bool
    {
        $overnightRun = new \App\Libraries\OvernightTripRunSupport();
        $ticketJourney = isset($ticketByBooking[$row->booking_id ?? ''])
            ? (string) ($ticketByBooking[$row->booking_id]->journeydata ?? '')
            : (string) ($row->ticket_journeydata ?? '');

        $listMode = (string) ($this->request->getVar('list_mode') ?? 'service');
        if ($listMode === 'service') {
            return $overnightRun->driverManifestMatchesSearchDate(
                (int) ($row->trip_id ?? 0),
                (int) ($row->subtrip_id ?? 0),
                (string) $row->journeydate,
                (int) ($row->pick_stand_id ?? 0),
                $searchDate,
                $ticketJourney !== '' ? $ticketJourney : null
            );
        }

        return $overnightRun->passengerListMatchesSearchDate(
            (int) ($row->trip_id ?? 0),
            (int) ($row->subtrip_id ?? 0),
            (int) ($row->pick_stand_id ?? 0),
            $searchDate,
            $ticketJourney !== '' ? $ticketJourney : null,
            (string) ($row->journeydate ?? '')
        );
    }

    function getSeatClasses($seatsData, $seatNumbers, $classData) {
        if (is_string($seatsData)) {
            $seatsData = json_decode($seatsData, true);
        }

        if (!is_array($seatNumbers)) {
            $seatNumbers = explode(",", $seatNumbers);
        }

        $seatClasses = [];
        $seatClassesArray = [];
        // print_r($seatNumbers);exit;
        foreach ($seatNumbers as $seatNo) {
            $found = false; 
            foreach ($seatsData as $seatInfo) {
                if (in_array($seatNo, $seatInfo['seatNo'])) {
                    $seatClasses[$seatNo] = $classData[$seatInfo['seatClass']];
                    $found = true;
                    break;
                }
            }
            if (!$found) {
                $seatClasses[$seatNo] = "Economy";
            }
            $seatClassesArray[] = $seatClasses[$seatNo];
        }
        $uniqueSeatClassesArray = array_unique($seatClassesArray);
        return $uniqueSeatClassesArray;

    }

    private function canSearchBackdatedJourneyList(): bool
    {
        if ((int) session()->get('role_id') === 1) {
            return true;
        }

        $rolepermissionLibrary = new \App\Libraries\Rolepermission();

        return $rolepermissionLibrary->read('journey_list_backdated');
    }

    private function redirectIfBackdatedJourneyListDenied(string $journeyDate)
    {
        if ($journeyDate < egypt_today() && !$this->canSearchBackdatedJourneyList()) {
            return redirect()->back()->with('fail', 'Searching for backdated trips is not allowed for your role.');
        }

        return null;
    }
}
