<?php

namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;
use App\Models\DropdownModel;
use App\Models\DepartmentModel;
use App\Models\TravelStatusModel;
use App\Models\CountryModel;
use App\Models\AirportCodeModel;
use App\Models\TrainStationsModel;
use App\Models\UserModel;
use App\Models\OrganizationModel;
use App\Models\GroupModel;
use App\Models\PolicyModel;
use App\Models\PolicyDetailsModel;
use App\Models\ServiceModel;
use App\Models\ForexPerdiemModel;
use App\Models\HotelModel;
use App\Models\CostCenterModel;
use App\Models\AirlineModel;
use App\Models\MailTemplateModel;

class MasterController extends ResourceController
{
    protected $format    = 'json';
    protected $myLogger;
    protected $dropdownModel;
    protected $departmentModel;
    protected $travelStatusModel;
    protected $countryModel;
    protected $airportCodeModel;
    protected $trainStationsModel;
    protected $userModel;
    protected $organizationModel;
    protected $groupModel;
    protected $policyModel;
    protected $policyDetailsModel;
    protected $serviceModel;
    protected $forexPerdiemModel;
    protected $hotelModel;
    protected $costCenterModel;
    protected $airlineModel;
    protected $mailTemplateModel;

    public function __construct()
    {
        $this->myLogger = \Config\Services::mylogger();
        $this->dropdownModel = new DropdownModel();
        $this->departmentModel = new DepartmentModel();
        $this->travelStatusModel = new TravelStatusModel();
        $this->countryModel = new CountryModel();
        $this->airportCodeModel = new AirportCodeModel();
        $this->trainStationsModel = new TrainStationsModel();
        $this->userModel = new UserModel();
        $this->organizationModel = new OrganizationModel();
        $this->groupModel = new GroupModel();
        $this->policyModel = new PolicyModel();
        $this->policyDetailsModel = new PolicyDetailsModel();
        $this->serviceModel = new ServiceModel();
        $this->forexPerdiemModel = new ForexPerdiemModel();
        $this->hotelModel = new HotelModel();
        $this->costCenterModel = new CostCenterModel();
        $this->airlineModel = new AirlineModel();
        $this->mailTemplateModel = new MailTemplateModel();
    }


    public function getDropdownMaster()
    {
        $data = $this->dropdownModel->select('dropdown')->groupBy('dropdown')->findAll();

        if (!$data) {
            return $this->failNotFound('No data found');
        }

        if ($data) 
        {
            foreach ($data as &$val) 
            {
                $temp[$val['dropdown']] = $this->dropdownModel->where('dropdown', $val['dropdown'])->where('is_active',1)->findAll();
            } 
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $temp]);
    }


    public function getTravelStatusMaster()
    {
        $data = $this->travelStatusModel->where('is_active',1)->findAll();

        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    public function getcountryMaster()
    {
        $data = $this->countryModel->where('is_active',1)->findAll();

        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    public function getAirlineMaster()
    {
        $data = $this->airlineModel->findAll();

        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }


    public function getAirportCodeMaster()
    {
        $type = $this->request->getGet('trip_type');
    
        // Build the query
        $query = $this->airportCodeModel->where('is_active', 1);
        if ($type == 1) {
            $query->where('Country_Code', 'IN');
        }
    
        // Execute the query and get the result
        $data = $query->findAll();
    
        // Check if data exists
        if (empty($data)) {
            return $this->failNotFound('No data found');
        }
    
        // Return success response
        return $this->respond([
            'status' => 200,
            'message' => 'success',
            'data' => $data
        ]);
    }
    
    public function getTrainCodeMaster()
    {
        $data = $this->trainStationsModel->where('is_active',1)->findAll();

        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    public function getFlightAndTrainClass()
    {


        $trip_type = $this->request->getGet('trip_type');
        $user_id = $this->request->getVar('user_id');

        $user = $this->userModel->where('user_id', $user_id)->first();
        
        $groupData = $this->groupModel->find($user['group_id']);
        
        if($groupData)
        {
            if($trip_type == 1) { $policyId = $groupData['domestic_policy_id'];}else{ $policyId = $groupData['international_policy_id'];}
            
            if($policyId != null)
            {
                $minFlightRow = $this->policyDetailsModel->where('policy_id', $policyId)->where('service_id', 1)->get()->getRow();

                $minTrainRow = $this->policyDetailsModel->where('policy_id', $policyId)->where('service_id', 2)->get()->getRow();

                $minHotelRow = $this->policyDetailsModel->where('policy_id', $policyId)->where('service_id', 5)->get()->getRow();

                $minFlightClassKey = $minFlightRow ? $minFlightRow->class : null;
                $minTrainClassKey  = $minTrainRow ? $minTrainRow->class  : null;
                $minHotelClassKey  = $minHotelRow ? $minHotelRow->class  : null;

            }
          

            //flight
            $allFlightClass = $this->dropdownModel->where('dropdown', 'flight_class')->orderBy('dropdown_key','ASC')->findAll();
            $minFlightClassKey = $minFlightClassKey ?? 0;
            $data['flight_class']  = [];
            foreach ($allFlightClass as $key => $value) {

                if((int)$value['dropdown_key'] >= (int)$minFlightClassKey){
                    $value['is_allowed'] = 'yes';
                    array_push($data['flight_class'] , $value);
                }else{
                    $value['is_allowed'] = 'No';
                    array_push($data['flight_class'] , $value);
                }
               
            }
            
            
            //train
            $allTrainClass = $this->dropdownModel->where('dropdown', 'train_class')->orderBy('dropdown_key','ASC')->findAll();
            $minTrainClassKey = $minTrainClassKey ?? 0;
            $data['train_class'] = [];

            foreach ($allTrainClass as $key => $value) {

                if((int)$value['dropdown_key'] >= (int)$minTrainClassKey){
                    $value['is_allowed'] = 'yes';
                    array_push($data['train_class'] , $value);
                }else{
                    $value['is_allowed'] = 'No';
                    array_push($data['train_class'] , $value);
                }
               
            }

            //hotel
            $allHotelClass = $this->dropdownModel->where('dropdown', 'hotel_class')->orderBy('dropdown_key','ASC')->findAll();
            $minHotelClassKey = $minHotelClassKey ?? 0;
            $data['hotel_class'] = [];

            foreach ($allHotelClass as $key => $value) {

                if((int)$value['dropdown_key'] >= (int)$minHotelClassKey){
                    $value['is_allowed'] = 'yes';
                    array_push($data['hotel_class'] , $value);
                }else{
                    $value['is_allowed'] = 'No';
                    array_push($data['hotel_class'] , $value);
                }
                
            }

        }
       
       

        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }


    // Department crud
    public function getDepartmentList()
    {
        $for = $this->request->getVar('for');

        if (isset($for) && $for === 'table_view') 
        {
            $data = $this->dropdownModel->where('dropdown','plan_functional_department')->findAll();
        } else {
            $data = $this->dropdownModel->where('dropdown','plan_functional_department')->where('is_active', 1)->findAll();
        }
        
        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    public function createDepartment()
    {
        $data = $this->request->getJSON(true);

        $data['dropdown'] = 'plan_functional_department';
        $data['is_active'] = 1;
        $existData = $this->dropdownModel->where('dropdown','plan_functional_department')->findAll();
        $data['dropdown_key'] = count($existData) + 1;

        if (!$this->dropdownModel->insert($data)) {
            return $this->failValidationErrors($this->dropdownModel->errors());
        }

        return $this->respondCreated([
            'status'  => 201,
            'message' => 'Department created successfully'
        ]);

    }

    public function findDepartment()
    {

        $id = $this->request->getGet('id');

        $data = $this->dropdownModel->where('id',$id)->find();

        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    public function updateDepartment($id = null)
    {
        $data = $this->request->getJSON(true);

        if (!$this->dropdownModel->find($id)) {
            return $this->failNotFound('Department not found');
        }

        if (!$this->dropdownModel->update($id, $data)) {
            return $this->failValidationErrors($this->dropdownModel->errors());
        }

        return $this->respond([
            'status'  => 200,
            'message' => 'Department updated successfully'
        ]);
    }


    // Purpose of travel crud
    public function getPurposeOfTravelList()
    {
        $for = $this->request->getVar('for');

        if (isset($for) && $for === 'table_view') 
        {
            $data = $this->dropdownModel->where('dropdown','plan_purpose_of_travel')->findAll();
        } else {
            $data = $this->dropdownModel->where('dropdown','plan_purpose_of_travel')->where('is_active', 1)->findAll();
        }
        
        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    public function createPurposeOfTravel()
    {
        $data = $this->request->getJSON(true);

        $data['dropdown'] = 'plan_purpose_of_travel';
        $data['is_active'] = 1;
        $existData = $this->dropdownModel->where('dropdown','plan_purpose_of_travel')->findAll();
        $data['dropdown_key'] = count($existData) + 1;

        if (!$this->dropdownModel->insert($data)) {
            return $this->failValidationErrors($this->dropdownModel->errors());
        }

        return $this->respondCreated([
            'status'  => 201,
            'message' => 'Department created successfully'
        ]);

    }

    public function findPurposeOfTravel()
    {

        $id = $this->request->getGet('id');

        $data = $this->dropdownModel->where('id',$id)->find();

        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    public function updatePurposeOfTravel($id = null)
    {
        $data = $this->request->getJSON(true);

        if (!$this->dropdownModel->find($id)) {
            return $this->failNotFound('Department not found');
        }

        if (!$this->dropdownModel->update($id, $data)) {
            return $this->failValidationErrors($this->dropdownModel->errors());
        }

        return $this->respond([
            'status'  => 200,
            'message' => 'Department updated successfully'
        ]);
    }

    // Cost center crud
    public function getCostCenterMaster()
    {
        $for = $this->request->getVar('for');

        if (isset($for) && $for === 'table_view') 
        {
            $data = $this->costCenterModel->findAll();
        } else {
            $data = $this->costCenterModel->where('is_active', 1)->findAll();
        }
        
        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    public function createCostCenter()
    {
        $data = $this->request->getJSON(true);

        if (!$this->costCenterModel->insert($data)) {
            return $this->failValidationErrors($this->costCenterModel->errors());
        }

        return $this->respondCreated([
            'status'  => 201,
            'message' => 'Cost Center created successfully'
        ]);

    }

    public function findCostCenter()
    {

        $id = $this->request->getGet('cost_center_id');

        $data = $this->costCenterModel->where('cost_center_id',$id)->find();

        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    public function updateCostCenter($id = null)
    {
        $data = $this->request->getJSON(true);

        if (!$this->costCenterModel->find($id)) {
            return $this->failNotFound('Cost Center not found');
        }

        if (!$this->costCenterModel->update($id, $data)) {
            return $this->failValidationErrors($this->costCenterModel->errors());
        }

        return $this->respond([
            'status'  => 200,
            'message' => 'Cost Center updated successfully'
        ]);
    }


    // Forex crud
    public function getForexPerdiemList()
    {

        $for = $this->request->getVar('for');

        if (isset($for) && $for === 'table_view') 
        {
            $data = $this->forexPerdiemModel->findAll();
        } else {
            $data = $this->forexPerdiemModel->where('is_active', 1)->findAll();
        }

        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    public function createForexPerdiem()
    {
       

        try {

            $data = $this->request->getJSON(true);

            if (!$this->forexPerdiemModel->insert($data)) {
                return $this->failValidationErrors($this->forexPerdiemModel->errors());
            }
        
            return $this->respondCreated([
                'status'  => 201,
                'message' => 'Forex Perdiem created successfully'
            ]);
        } catch (\CodeIgniter\Database\Exceptions\DatabaseException $e) {
           
            if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
                return $this->respond([
                    'status'  => 404,
                    'message'   => 'Duplicate entry'
                ],404);
            }
        
            // For other DB-related exceptions
            return $this->failServerError($e->getMessage());
        }
        

    }

    public function findForexPerdiem()
    {

        $id = $this->request->getGet('forex_perdiem_id');
        
        $data = $this->forexPerdiemModel->where('forex_perdiem_id',$id)->find();

        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    public function updateForexPerdiem($id = null)
    {
        try{

            $data = $this->request->getJSON(true);

            if (!$this->forexPerdiemModel->find($id)) {
                return $this->failNotFound('Forex Perdiem not found');
            }


            if (!$this->forexPerdiemModel->update($id, $data)) {
                return $this->failValidationErrors($this->forexPerdiemModel->errors());
            }

            return $this->respond([
                'status'  => 200,
                'message' => 'Forex Perdiem updated successfully'
            ]);

        } catch (\CodeIgniter\Database\Exceptions\DatabaseException $e) {
            
            if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
                return $this->respond([
                    'status'  => 404,
                    'message'   => 'Duplicate entry'
                ]);
            }
        
            // For other DB-related exceptions
            return $this->failServerError($e->getMessage());
        }
    }

    // Hotels crud
    public function getHotels()
    {

        $for = $this->request->getVar('for');

        if (isset($for) && $for === 'table_view') 
        {
            $hotels = $this->hotelModel->select('m_hotels.* , C.country_name')
                                        ->join('m_country C', 'C.country_code = m_hotels.country_code', 'left')
                                        ->findAll();
        } else {
            $hotels = $this->hotelModel->select('m_hotels.* , C.country_name')
                                        ->join('m_country C', 'C.country_code = m_hotels.country_code', 'left')
                                        ->where('m_hotels.is_active', 1)
                                        ->findAll();
        }
    
        
        return $this->response->setJSON([
            'status'  => 200,
            'message' => 'Hotel list fetched successfully',
            'data'    => $hotels
        ]);
    }

    public function createHotels()
    {
        $data = $this->request->getJSON(true);

        if (!$this->hotelModel->insert($data)) {
            return $this->failValidationErrors($this->hotelModel->errors());
        }

        return $this->respondCreated([
            'status'  => 201,
            'message' => 'Hotels created successfully'
        ]);

    }

    public function findHotels()
    {

        $id = $this->request->getGet('hotel_id');

        $data = $this->hotelModel->where('hotel_id',$id)->find();

        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    public function updateHotels($id = null)
    {
        $data = $this->request->getJSON(true);

        if (!$this->hotelModel->find($id)) {
            return $this->failNotFound('Hotels not found');
        }

        if (!$this->hotelModel->update($id, $data)) {
            return $this->failValidationErrors($this->hotelModel->errors());
        }

        return $this->respond([
            'status'  => 200,
            'message' => 'Hotels updated successfully'
        ]);
    }


    public function forex_signature_upload()
    {
       
        $data = $this->request->getPost(); 
       
        // Handle file upload
        $file = $this->request->getFile('signature');
        if ($file && $file->isValid() && !$file->hasMoved()) {
            $newName = $file->getRandomName(); // Generate a unique name
            // $uploadPath = WRITEPATH.'uploads/signature';
            $uploadPath = FCPATH.'public/assets/images/signature';

            // print_r( $uploadPath); die;
            
            // Move file to the specified directory
            $file->move($uploadPath, $newName);

            // Save file path in database
            $path = $uploadPath . '/' . $newName;
        } else {
            return $this->failValidationErrors(['passport_document' => 'Invalid file upload']);
        }

        try {
            
            $this->mailTemplateModel->set(['image_location' => $newName])->where('template_name','forex')->update();

          
            return $this->respondCreated([
                'status'  => 201,
                'message' => 'organization created successfully',
                'data'    => $data
            ]);
        } catch (\Exception $e) {
            return $this->failServerError('Failed to create organization: ' . $e->getMessage());
        }
    }

    // public function getForexSignaturePath()
    // {

    //     $data = $this->mailTemplateModel->where('template_name','forex')->first();

    //     return $this->respond([
    //         'status'  => 200,
    //         'message' => 'success',
    //         'data' => $data

    //     ]);

    // }

    public function getForexSignaturePath()
    {
        $data = $this->mailTemplateModel->where('template_name', 'forex')->first();
    
        if (!$data || empty($data['image_location'])) {
            return $this->respond([
                'status'  => 404,
                'message' => 'Image not found',
                'url'    => null
            ]);
        }
    
        // If the DB stores only the filename, adjust accordingly
        $fileName = basename($data['image_location']); 
    
        
        $imageUrl = base_url('public/assets/images/signature/' . $fileName);
    
        // Add both the URL and ready-made HTML tag
        $data['image_url'] = $imageUrl;
        $data['image_tag'] = '<img src="' . $imageUrl . '" alt="Signature" style="max-width:200px;">';

        return $this->respond([
            'status'  => 200,
            'message' => 'success',
            'url'    => $imageUrl
        ]);
    }
    
    













}
