<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;
use Modules\Coupon\Models\CouponModel;
use Modules\Coupon\Models\CouponDetailsModel;
use Modules\Fleet\Models\Vehicalimage;
use Modules\Fleet\Models\Fleetimage;
use Modules\Fleet\Models\VehicleModel;
use Modules\Localize\Models\LanguageModel;
use Modules\Location\Models\StandModel;
use Modules\Trip\Models\TripModel;
use Modules\Trip\Models\SubtripModel;
use Modules\User\Models\UserDetailModel;
use Modules\User\Models\UserModel;
use Modules\Agent\Models\AgentModel;
use Modules\Role\Models\RoleModel;

class AjaxController extends BaseController
{

    protected $fleetModel;
    protected $vImageModel;
    protected $fImageModel;
    protected $standModel;

    protected $userModel;
    protected $userDetailModel;
    protected $db;
    protected $subtripModel;
    protected $tripModel;

    protected $couponModel;
    protected $couponDetailsModel;
    protected $agentModel;

    protected $languageModel;

    use ResponseTrait;
    public function __construct()
    {

        $this->Viewpath = "Modules\Fleet\Views";

        $this->vehicleModel = new VehicleModel();
        $this->vImageModel = new Vehicalimage();
        $this->fImageModel = new Fleetimage();
        $this->standModel = new StandModel();
        $this->userModel = new UserModel();
        $this->userDetailModel = new UserDetailModel();

        $this->tripModel = new TripModel();
        $this->subtripModel = new SubtripModel();

        $this->couponModel = new CouponModel();
        $this->couponDetailsModel = new CouponDetailsModel();
        $this->db = \Config\Database::connect();

        $this->languageModel = new LanguageModel();
        $this->agentModel = new AgentModel();
    }

    public function getVehicleByFleetId($fleet_id)
    {
        $vehiclelist = $this->vehicleModel->where('fleet_id', $fleet_id)->findAll();
        echo json_encode($vehiclelist);
    }

    public function getallStand()
    {
        $standlist = $this->standModel->findAll();
        echo json_encode($standlist);
    }

    public function picdelete()
    {
        $id = (int) $this->request->getVar('picid');
        if ($id <= 0) {
            return $this->response->setJSON([
                'status' => 'failed',
                'response' => 422,
                'message' => 'Invalid image id.',
            ]);
        }

        $uriseg = $this->vImageModel->find($id);
        if ($uriseg === null) {
            return $this->response->setJSON([
                'status' => 'failed',
                'response' => 404,
                'message' => 'Image not found.',
            ]);
        }

        $vehicleId = (int) $uriseg->vehicle_id;
        \App\Libraries\PublicImageStorage::delete($uriseg->img_path ?? '');
        $this->vImageModel->delete($id);
        $this->vImageModel->purgeDeleted();

        return $this->response->setJSON([
            'status' => 'success',
            'response' => 200,
            'data' => json_encode($this->vImageModel->where('vehicle_id', $vehicleId)->findAll()),
        ]);
    }

    public function picfleetdelete()
    {
        $id = (int) $this->request->getVar('picid');
        if ($id <= 0) {
            return $this->response->setJSON([
                'status' => 'failed',
                'response' => 422,
                'message' => 'Invalid image id.',
            ]);
        }

        $uriseg = $this->fImageModel->find($id);
        if ($uriseg === null) {
            return $this->response->setJSON([
                'status' => 'failed',
                'response' => 404,
                'message' => 'Image not found.',
            ]);
        }

        $fleetId = (int) $uriseg->fleet_id;
        \App\Libraries\PublicImageStorage::delete($uriseg->img_path ?? '');
        $this->fImageModel->delete($id);
        $this->fImageModel->purgeDeleted();

        return $this->response->setJSON([
            'status' => 'success',
            'response' => 200,
            'data' => json_encode($this->fImageModel->where('fleet_id', $fleetId)->findAll()),
        ]);
    }

    public function getPassanger($segment, $type)
    {
        if ($type == "email") {
            $userdetail = $this->userModel->join('user_details', 'user_details.user_id = users.id', 'left')->where('login_email', $segment)->first();
        }

        if ($type == "mobile") {
            $userdetail = $this->userModel->join('user_details', 'user_details.user_id = users.id', 'left')->where('login_mobile', $segment)->first();
        }

        if (empty($userdetail)) {
            $data = [
                'status' => "fail",
                'response' => 204,
                'data' => 'Passanger not found'
            ];
            return $this->response->setJSON($data);
        } else if ($userdetail->role_id != 3) {
            $data = [
                'status' => "fail",
                'response' => 401,
                'data' => 'Requested email/mobile is not a Passanger'
            ];
            return $this->response->setJSON($data);
        }

        $data = [
            'status' => "success",
            'response' => 200,
            'data' => json_encode($userdetail),
        ];

        return $this->response->setJSON($data);
    }

    public function getAllCountry()
    {
        $builder = $this->db->table('country');
        $query = $builder->get();
        $country = $query->getResult();

        if (empty($country)) {
            $data = [
                'status' => "fail",
                'response' => 204,
                'message' => 'no data found',
            ];
            return $this->response->setJSON($data);
        } else {
            $data = [
                'status' => "success",
                'response' => 200,
                'data' => $country,
            ];

            return $this->response->setJSON($data);
        }
    }

    public function couponValidation($coupon, $subtripId, $journeyDate)
    {
        // $couponDetail = $this->couponModel->where('code',$coupon)->where('subtrip_id',$subtripId)->findAll();
        // $validDetail = $this->couponModel->where('code', $coupon)
        //     ->where('subtrip_id', $subtripId)
        //     ->where('end_date >=', $journeyDate)
        //     ->where('start_date <=', $journeyDate)
        //     ->findAll();

        $validDetail = $this->couponDetailsModel
                            ->join('coupons', 'coupons.id = coupon_details.coupon_id', 'left')
                            ->where('coupons.code', $coupon)
                            ->where('coupons.coupon_for', 0)
                            ->where("JSON_CONTAINS(coupon_details.sub_trip_id, '\"$subtripId\"')")
                            ->where('coupons.end_date >=', $journeyDate)
                            ->where('coupons.start_date <=', $journeyDate)
                            ->findAll();

        if (count($validDetail) == 0) {
            $data = [
                'status' => "fail",
                'response' => 204,
                'message' => 'coupon is not valid',
                'data' => json_encode($validDetail),
            ];
            return $this->response->setJSON($data);
        } else {
            $data = [
                'status' => "success",
                'response' => 200,
                'discount' => $validDetail[0]->discount??$validDetail[0]['discount'],
                'discount_type' => $validDetail[0]->discount_type??$validDetail[0]['discount_type'],
                'data' => json_encode($validDetail),
            ];

            return $this->response->setJSON($data);
        }
    }

    public function getMainTrip($company_id)
    {

        $tripQuery = $this->tripModel->select('trips.id as tripid,trips.*,schedules.*,a.name as pickup_location_name,b.name as drop_location_name')
            ->join('schedules', 'schedules.id = trips.schedule_id', 'left')
            ->join('locations a', 'a.id = trips.pick_location_id', 'left')
            ->join('locations b', 'b.id = trips.drop_location_id', 'left')
            ->join('companies d', 'trips.company_id = d.id')
            ->where('trips.status', 1)
            ->where('d.status', 1);

        if ($company_id != "all") {
            $tripQuery->where('trips.company_id', $company_id);
        }

        $tripDetails = $tripQuery->findAll();

        $subtripQuery = $this->subtripModel->select('subtrips.id as subtripsid,subtrips.*,a.name as pickup_location_name,b.name as drop_location_name, c.company_id')
                ->join('locations a', 'a.id = subtrips.pick_location_id', 'left')
                ->join('locations b', 'b.id = subtrips.drop_location_id', 'left')
                ->join('trips c', 'c.id = subtrips.trip_id')
                ->join('companies d', 'd.id = c.company_id');
        
        if ($company_id != "all") {
            $subtripQuery->where('d.id', $company_id);
        }
        $subtripDetails = $subtripQuery->where('c.status', 1)
                            ->where('d.status', 1)
                            ->where('subtrips.status', 1)
                            ->findAll();

        $data = [
            'status' => "success",
            'response' => 200,
            'maintrips' => $tripDetails,
            'subtrips' => $subtripDetails,
        ];

        return $this->response->setJSON($data);

        echo "<pre>";print_r($tripDetails);exit;


        
        if ($company_id == "all") {

            

        }else{

            $tripQuery = $this->tripModel->select('trips.id as tripid,trips.*,schedules.*,a.name as pickup_location_name,b.name as drop_location_name')
            ->join('schedules', 'schedules.id = trips.schedule_id', 'left')
            ->join('locations a', 'a.id = trips.pick_location_id', 'left')
            ->join('locations b', 'b.id = trips.drop_location_id', 'left')
            ->where('trips.status', 1);

            if ($company_id != "all") {
                $tripQuery->join('companies', 'trips.company_id = companies.id', 'left')
                        ->where('companies.id', $company_id);
            }

            $tripDetails = $tripQuery->findAll();

            // ->findAll();


            // $tripQuery = $this->tripModel->select('
            //         trips.id as tripid,
            //         trips.*,
            //         schedules.*,
            //         a.name as pickup_location_name,
            //         b.name as drop_location_name
            //     ')
            //     ->join('schedules', 'schedules.id = trips.schedule_id', 'left')
            //     ->join('locations a', 'a.id = trips.pick_location_id', 'left')
            //     ->join('locations b', 'b.id = trips.drop_location_id', 'left')
            //     ->where('trips.status', 1);

            // if ($company_id != "all") {
            //     $tripQuery->join('coupon_details', 'coupon_details.main_trip_id = trips.id', 'left')
            //             ->where('coupon_details.company_id', $company_id);
            // }

            // $tripDetails = $tripQuery->findAll();

            $data = [
                'status' => "success",
                'response' => 200,
                'data' => json_encode($tripDetails),
            ];

            return $this->response->setJSON($data);
        }
    }


    public function getSubTrip($maintrip_id)
    {
        if ($maintrip_id == "all") {

            $data = [
                'status' => "success",
                'response' => 200,
                'data' => json_encode($maintrip_id),
            ];

            return $this->response->setJSON($data);
        } else {
            $subtripDetails = $this->subtripModel->select('subtrips.id as subtripsid,subtrips.*,a.name as pickup_location_name,b.name as drop_location_name')
                ->join('locations a', 'a.id = subtrips.pick_location_id', 'left')
                ->join('locations b', 'b.id = subtrips.drop_location_id', 'left')
                ->where('subtrips.trip_id', $maintrip_id)
                ->where('subtrips.status', 1)
                ->findAll();

            $data = [
                'status' => "success",
                'response' => 200,
                'data' => json_encode($subtripDetails),
            ];

            return $this->response->setJSON($data);
        }
    }

    public function getComapnySubTrip()
    {
        $company_id = $this->request->getVar('company_id');
        $maintrip_id = $this->request->getVar('maintrip_id');

        $subtripDetails = $this->subtripModel->select('subtrips.id as subtripsid,subtrips.*,a.name as pickup_location_name,b.name as drop_location_name')
            ->join('locations a', 'a.id = subtrips.pick_location_id', 'left')
            ->join('locations b', 'b.id = subtrips.drop_location_id', 'left')
            ->join('trips c', 'c.id = subtrips.trip_id')
            ->join('companies d', 'd.id = c.company_id')
            ->where('subtrips.status', 1)
            ->where('c.status', 1)
            ->where('d.status', 1);
        
        if($maintrip_id != "all"){
            $subtripDetails->where('c.id', $maintrip_id);
        }
        if($company_id != "all"){
            $subtripDetails->where('d.id', $company_id);
        }
        $subtripDetails = $subtripDetails->findAll();

        //echo "<pre>";print_r($subtripDetails);exit;

        $data = [
            'status' => "success",
            'response' => 200,
            'subtrips' => $subtripDetails,
        ];

        return $this->response->setJSON($data);

        echo "<pre>";print_r($tripDetails);exit;

        if ($maintrip_id == "all") {

            $data = [
                'status' => "success",
                'response' => 200,
                'data' => json_encode($maintrip_id),
            ];

            return $this->response->setJSON($data);
        } else {
            $subtripDetails = $this->subtripModel->select('subtrips.id as subtripsid,subtrips.*,a.name as pickup_location_name,b.name as drop_location_name')
                ->join('locations a', 'a.id = subtrips.pick_location_id', 'left')
                ->join('locations b', 'b.id = subtrips.drop_location_id', 'left')
                ->where('subtrips.trip_id', $maintrip_id)
                ->where('subtrips.status', 1)
                ->findAll();

            $data = [
                'status' => "success",
                'response' => 200,
                'data' => json_encode($subtripDetails),
            ];

            return $this->response->setJSON($data);
        }
    }


    public function getAgentListByCompany($company_id)
    {
        $userRole = $this->session->get('role_id');

        $this->userModel
            ->select('users.id, agents.id AS agent_id, agents.first_name, agents.last_name, GROUP_CONCAT(DISTINCT companies.name SEPARATOR ", ") AS company_names')
            ->join('agents', 'agents.user_id = users.id', 'left')
            ->join('companies', 'FIND_IN_SET(agents.user_id, companies.user_id)', 'left')
            ->where('role_id', 2);

        // Filter by selected company
        if ($company_id !== 'all') {
            $this->userModel->where('companies.id', $company_id);
        }

        $this->userModel->groupBy('users.id')->orderBy('users.id', 'DESC');

        $agents = $this->userModel->findAll();
        // var_dump($agents);
        // exit;

        if (empty($agents)) {
            return $this->response->setJSON(['data' => 'all']);
        }

        return $this->response->setJSON(['data' => json_encode($agents)]);
    }




    public function getLanguageCode($languageId)

    {
        $langCode = $this->languageModel->find($languageId);

        echo json_encode($langCode);
    }

    public function getTripsByCompany()
    {
        $companyIds = $this->request->getGet('companyIds');

        if (!$companyIds) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'No company IDs provided'
            ]);
        }

        $tripData = $this->subtripModel->getTripsByCompany($companyIds);

        return $this->response->setJSON([
            'success' => true,
            'data' => $tripData
        ]);
    }

    public function getRolesByCompany($companyId = null)
    {
        $companyId = (int) ($companyId ?? $this->request->getGet('company_id'));
        if ($companyId <= 0) {
            return $this->response->setJSON(['success' => true, 'data' => []]);
        }

        $roleId = (int) session()->get('role_id');
        if (! is_global_admin_role()) {
            $allowedCompanyIds = session_company_ids();
            if (! in_array($companyId, $allowedCompanyIds, true)) {
                return $this->response->setJSON(['success' => false, 'message' => 'Access denied']);
            }
        }

        $roleModel = new RoleModel();
        $roles = $roleModel
            ->select('id, name')
            ->whereNotIn('id', [1, 2, 3])
            ->where('company_id', $companyId)
            ->where('status', 1)
            ->orderBy('name', 'ASC')
            ->findAll();

        $data = array_map(static function ($role) {
            return [
                'id' => (int) $role->id,
                'name' => $role->name,
            ];
        }, $roles);

        return $this->response->setJSON([
            'success' => true,
            'data' => $data,
        ]);
    }
}
