<?php

namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use App\Models\QuotationModel;
use App\Models\EnquiryModel;
use App\Models\PolicyModel;

use App\Controllers\Jobs ;
use App\Controllers\JobWorker ;

class QuotationController extends ResourceController
{
    protected $QuotationModel;
    protected $EnquiryModel;
    protected $PolicyModel;
    protected $db;

    public function __construct()
    {
        $this->db = db_connect();
        $this->QuotationModel = new QuotationModel();
        $this->EnquiryModel = new EnquiryModel();
        $this->PolicyModel = new PolicyModel();
    }

    // List quotations
    public function quotationList()
    {
        try {
            
            $manager_id = $this->request->getGet('manager_id');

            $data = $this->QuotationModel->select('partner_quotation.* , pe.reg_no ,  I.name as insurer_name, ipti.insurance_plan_type')
                                        ->join('partner_enquiry pe', 'pe.id = partner_quotation.enquiry_id', 'left')
                                        ->join('insurers I', 'I.id = partner_quotation.insurer_id', 'left')
                                        ->join('partner_insurance_plan_type_master ipti', 'ipti.id = partner_quotation.insurance_plan_type_id', 'left')
                                        ->where('partner_quotation.manager_id',$manager_id)
                                        ->findAll();

            return $this->respond(['status' => 'success', 'code' => 200, 'data' => $data], 200);
        } catch (\Exception $e) {
            return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
        }
    }

    // Find single quotation
    public function findQuotation()
    {
        try {
            $id = $this->request->getGet('id');
            $record = $this->QuotationModel->select('partner_quotation.* , pe.reg_no ,  I.name as insurer_name, ipti.insurance_plan_type')
                                            ->join('partner_enquiry pe', 'pe.id = partner_quotation.enquiry_id', 'left')
                                            ->join('insurers I', 'I.id = partner_quotation.insurer_id', 'left')
                                            ->join('partner_insurance_plan_type_master ipti', 'ipti.id = partner_quotation.insurance_plan_type_id', 'left')
                                            ->where('partner_quotation.id',$id)
                                            ->find();

            if (!$record) {
                return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
            }
            return $this->respond(['status' => 'success', 'code' => 200, 'data' => $record], 200);

        } catch (\Exception $e) {
            return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
        }
    }

    // Create quotation
    public function createQuotation()
    {
        try {
            $data = $this->request->getPost();

            $uploadFile = $this->request->getFile('additional_uploaded_file_name');
            $uploadedFileName = null;

            if ($uploadFile && $uploadFile->isValid()) {
                $uploadPath = WRITEPATH . 'uploads/quotation/';
                if (!is_dir($uploadPath)) {
                    mkdir($uploadPath, 0777, true);
                }
                $uploadedFileName = time() . '_' . $uploadFile->getRandomName();
                $uploadFile->move($uploadPath, $uploadedFileName);
            }

            //get insurer_branch_id
            $query = $this->db->query("SELECT id FROM insurer_branch WHERE insurer_id = ? LIMIT 1", [$data['insurer_id']]);
            $insurerBranchresult = $query->getRowArray();

            $insertData = [
                'enquiry_id'                 => $data['enquiry_id'],
                'insured_declared_value'     => $data['insured_declared_value'],
                'premium_amount'             => $data['premium_amount'],
                'insurance_plan_type_id'     => $data['insurance_plan_type_id'],
                'insurer_id'                 => $data['insurer_id'],
                'insurer_branch_id'          => $insurerBranchresult['id'] ?? 0,
                'additional_uploaded_file_name' => $uploadedFileName,
                'created_by'                 => $data['created_by'],
                'manager_id'                 => $data['manager_id']
            ];

            $id = $this->QuotationModel->insert($insertData, true);

            // trigger_email('quotation_created', ['quotation_id' => $id]);

            //update enquiry status
            $enquiryData = $this->EnquiryModel->where('id',$data['enquiry_id'])->where('status','Awaiting Proposal')->first();
            if (!empty($enquiryData)){ $this->EnquiryModel->update($data['enquiry_id'], ['status'=>'Proposal Created']); }

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

        } catch (\Exception $e) {
            return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
        }
    }

    // Update quotation
    public function updateQuotation()
    {
        try {
            $data = $this->request->getPost();
            if (!isset($data['id'])) {
                return $this->respond(['status' => 'failed', 'code' => 200, 'data' => 'ID Required'], 200);
            }

            $id = $data['id'];
            $quotation = $this->QuotationModel->find((int)$id);
            if (!$quotation) {
                return $this->respond(['status' => 'failed', 'code' => 200, 'data' => 'Data Not Found'], 200);
            }

            //get insurer_branch_id
            $query = $this->db->query("SELECT id FROM insurer_branch WHERE insurer_id = ? LIMIT 1", [$data['insurer_id']]);
            $insurerBranchresult = $query->getRowArray();

            $updateData = [
                'enquiry_id'             => $data['enquiry_id'] ?? $quotation['enquiry_id'],
                'insured_declared_value' => $data['insured_declared_value'] ?? $quotation['insured_declared_value'],
                'insurer_id'             => $data['insurer_id'] ?? $quotation['insurer_id'],
                'insurer_branch_id'      => $insurerBranchresult['id'] ?? $quotation['insurer_branch_id'],
                'premium_amount'         => $data['premium_amount'] ?? $quotation['premium_amount'],
                'insurance_plan_type_id' => $data['insurance_plan_type_id'] ?? $quotation['insurance_plan_type_id'],
                'status'                 => $data['status'] ?? $quotation['status'],
                'reject_reason'          => $data['reject_reason'] ?? $quotation['reject_reason'],
                'updated_by'             => $data['updated_by'] ?? null
            ];

            // File upload
            $uploadFile = $this->request->getFile('additional_uploaded_file_name');
            if ($uploadFile && $uploadFile->isValid()) {
                $uploadPath = WRITEPATH . 'uploads/quotation/';
                if (!is_dir($uploadPath)) {
                    mkdir($uploadPath, 0777, true);
                }
                $uploadedFileName = time() . '_' . $uploadFile->getRandomName();
                $uploadFile->move($uploadPath, $uploadedFileName);
                $updateData['additional_uploaded_file_name'] = $uploadedFileName;
            }

            $this->QuotationModel->update($id, $updateData);

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

        } catch (\Exception $e) {
            return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
        }
    }

    // Proposal status update
    public function acceptOrRejectQuotation()
    {
        try {
            $data = $this->request->getJSON(true);
            if (!isset($data['id'])) {
                return $this->respond(['status' => 'failed', 'code' => 200, 'data' => 'ID Required'], 200);
            }

            $id = $data['id'];

            $quotation = $this->QuotationModel->find((int)$id);
            if (!$quotation) {
                return $this->respond(['status' => 'failed', 'code' => 200, 'data' => 'Data Not Found'], 200);
            }

            $newStatus = $data['status'];

            $this->QuotationModel->update($id, ['status' => $newStatus, 'action_by' => $data['action_by'], 'action_user' => $data['action_user']]);

            //update enquiry status
            $enquiryData = $this->EnquiryModel->where('id',$quotation['enquiry_id'])
                                                ->groupStart()
                                                ->where('status', 'Proposal Created')
                                                ->orWhere('status', 'Proposal Rejected')
                                                ->groupEnd()
                                                ->first();
            $enqStatus = 'Proposal '.$data['status'];
            if (!empty($enquiryData)){ 
                $this->EnquiryModel->update($quotation['enquiry_id'], ['status'=> $enqStatus , 'insurer_id' => $quotation['insurer_id'] ,  'insurer_branch_id' => $quotation['insurer_branch_id'] ]); 
                if( $newStatus == 'Accepted'){
                    $this->QuotationModel
                        ->where('enquiry_id', $quotation['enquiry_id'])
                        ->where('id !=', $id)
                        ->set(['status' => 'Rejected', 'action_by' => $data['action_by'], 'action_user' => $data['action_user'], 'updated_on' => date('Y-m-d H:i:s')])
                        ->update();
                    $this->EnquiryModel->update($quotation['enquiry_id'], ['is_quick_quote' => 0]);
                }
            }

            if( $newStatus == 'Accepted')
            {
                // trigger_email('quotation_accepted', ['quotation_id' => $id]);
            }else{
                // trigger_email('quotation_rejected', ['quotation_id' => $id]);
            }
            
            

            return $this->respond(['status' => 'success', 'code' => 200, 'data' => 'Updated Successfully'], 200);

        } catch (\Exception $e) {
            return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
        }
    }

    // Download additional file
    public function downloadAdditionalUploadedFile()
    {
        try {
            $id = $this->request->getGet('id');

            if (!$id) {
                return $this->respond(['status' => 'failed', 'code' => 400, 'data' => 'ID is required'], 200);
            }

            // Fetch record from DB
            $fileRecord = $this->QuotationModel->where('is_active',1)->find((int)$id);

            if (!$fileRecord) {
                return $this->respond(['status' => 'failed', 'code' => 404, 'data' => 'File not found'], 200);
            }

            $filePath = WRITEPATH . 'uploads/quotation/' . $fileRecord['additional_uploaded_file_name'];

            if (!file_exists($filePath)) {
                return $this->respond(['status' => 'failed', 'code' => 404, 'data' => 'File missing on server'], 200);
            }

            // Force file download
            return $this->response->download($filePath, null);

        } catch (\Exception $e) {
            return $this->respond(['status' => 'failed', 'code' => 500, 'message' => $e->getMessage()], 500);
        }
    }



    public function proceedQuotationOld()
    {
        try {
            $data = $this->request->getPost();

           
            //get insurer_branch_id
            $query = $this->db->query("SELECT id FROM insurer_branch WHERE insurer_id = ? LIMIT 1", [$data['insurer_id']]);
            $insurerBranchresult = $query->getRowArray();

            // create quotation
            $insertData = [
                'enquiry_id'                 => $data['enquiry_id'],
                'insured_declared_value'     => $data['insured_declared_value'],
                'premium_amount'             => $data['premium_amount'],
                'insurance_plan_type_id'     => $data['insurance_plan_type_id'],
                'insurer_id'                 => $data['insurer_id'],
                'insurer_branch_id'          => $insurerBranchresult['id'] ?? 0,
                'created_by'                 => $data['created_by'],
                'status'		             => 'Accepted',
                'manager_id'                 => $data['manager_id'],
                'payment_mode_id'            => $data['payment_mode_id'] ?? 0 ,
            ];

            $quotationId = $this->QuotationModel->insert($insertData, true);

            // update enquiry
            $enquiryArray = [
                'status'=> 'Proposal Accepted' 
            ];
            $this->EnquiryModel->update($data['enquiry_id'], $enquiryArray ); 


            //create policy file
            $uploadPath = WRITEPATH . 'uploads/policy/';
            $policyPdf = $this->request->getFile('policy_pdf_file_name');
            $pdfFileName = null;
            // PDF Upload
            if ($policyPdf && $policyPdf->isValid()) {
                $pdfPath = $uploadPath . 'policy_pdf/';
                if (!is_dir($pdfPath)) {
                    mkdir($pdfPath, 0777, true);
                }
                $pdfFileName = time() . '_' . $policyPdf->getRandomName();
                $policyPdf->move($pdfPath, $pdfFileName);


                 //fetch enquiry_id & agent_id
                $quotData = $this->QuotationModel->select('partner_quotation.*,E.agent_id,E.name')
                    ->join('partner_enquiry E', 'E.id = partner_quotation.enquiry_id', 'left')
                    ->where('partner_quotation.id',$quotationId)
                    ->first();
                $insertPolicyData = [
                    'enquiry_id'                       => $quotData['enquiry_id'],
                    'quotation_id'                     => $quotationId,
                    'insured_name'                     => $quotData['name'],
                    'manager_id'                       => $quotData['manager_id'],
                    'agent_id'                         => $quotData['agent_id'],
                    'policy_pdf_file_name'             => $pdfFileName,
                    'created_by'                       => $data['created_by']
                ];

                $policyId = $this->PolicyModel->insert($insertPolicyData);

                //update enquiry status
                if (!empty($quotData)){  
                    $this->EnquiryModel->update($quotData['enquiry_id'], ['status'=> 'Policy Created'] ); 
                }

            }
           

            
            
        

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

        } catch (\Exception $e) {
            return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
        }
    }


    public function proceedQuotation()
    {
        try {
            $data = $this->request->getPost();
            $quotationId = $data['id'] ?? null;               // For update
            $policyId    = $data['policy_id'] ?? null;        // For policy update
            $policyPdf   = $this->request->getFile('policy_pdf_file_name');

            /* ------------------------------------------------------
            *  Update Policy (policy_id + file uploaded)
            * ------------------------------------------------------ */
            if (!empty($policyId) && $policyPdf && $policyPdf->isValid()) {

                $uploadPath = WRITEPATH . 'uploads/policy/policy_pdf/';
                if (!is_dir($uploadPath)) {
                    mkdir($uploadPath, 0777, true);
                }

                $pdfFileName = time() . '_' . $policyPdf->getRandomName();
                $policyPdf->move($uploadPath, $pdfFileName);

                $updateData = [
                    'policy_pdf_file_name' => $pdfFileName,
                    'updated_by'           => $data['created_by'],
                ];

                $this->PolicyModel->update($policyId, $updateData);

            }


            /* ------------------------------------------------------
            *  Get insurer_branch_id
            * ------------------------------------------------------ */
            $query = $this->db->query(
                "SELECT id FROM insurer_branch WHERE insurer_id = ? LIMIT 1",
                [$data['insurer_id']]
            );
            $insurerBranch = $query->getRowArray();
            $insurerBranchId = $insurerBranch['id'] ?? 0;


            /* ------------------------------------------------------
            *  Prepare common quotation data
            * ------------------------------------------------------ */
            $quotationData = [
                'enquiry_id'             => $data['enquiry_id'],
                'insured_declared_value' => $data['insured_declared_value'],
                'premium_amount'         => $data['premium_amount'],
                'insurance_plan_type_id' => $data['insurance_plan_type_id'],
                'insurer_id'             => $data['insurer_id'],
                'insurer_branch_id'      => $insurerBranchId,
                'manager_id'             => $data['manager_id'],
                'payment_mode_id'        => $data['payment_mode_id'] ?? 0,
            ];


            /* ------------------------------------------------------
            *  CASE 2: Update Quotation
            * ------------------------------------------------------ */
            if (!empty($quotationId)) {

                $quotationData['updated_by'] = $data['created_by'];

                $this->QuotationModel->update($quotationId, $quotationData);

            }


            /* ------------------------------------------------------
            *  CASE 3: Create New Quotation
            * ------------------------------------------------------ */
            if (empty($quotationId)) 
            {
                $quotationData['created_by'] = $data['created_by'] ?? 0;
                $quotationData['status']     = 'Accepted';

                $newQuotationId = $this->QuotationModel->insert($quotationData, true);

                /* --------------------------------------------
                * Update Enquiry (Quotation Accepted)
                * -------------------------------------------- */
                $this->EnquiryModel->update($data['enquiry_id'], ['status'  => 'Proposal Accepted']);

            }
           
            /* ------------------------------------------------------
            *  If file uploaded → Create Policy
            * ------------------------------------------------------ */
            if (empty($policyId) &&  $policyPdf && $policyPdf->isValid()) {

                $uploadDir = WRITEPATH . 'uploads/policy/policy_pdf/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0777, true);
                }

                $pdfFileName = time() . '_' . $policyPdf->getRandomName();
                $policyPdf->move($uploadDir, $pdfFileName);

                // fetch enquiry + agent
                $quot = $this->QuotationModel
                    ->select('partner_quotation.*,E.agent_id,E.name')
                    ->join('partner_enquiry E', 'E.id = partner_quotation.enquiry_id')
                    ->where('partner_quotation.id', $newQuotationId ?? $quotationId)
                    ->first();

                $policyInsert = [
                    'enquiry_id'           => $quot['enquiry_id'],
                    'quotation_id'         => $newQuotationId ?? $quotationId,
                    'insured_name'         => $quot['name'],
                    'manager_id'           => $quot['manager_id'],
                    'agent_id'             => $quot['agent_id'],
                    'policy_pdf_file_name' => $pdfFileName,
                    'created_by'           => $data['created_by'] ?? 0,
                ];

                $newPolicyId = $this->PolicyModel->insert($policyInsert);

                // Update enquiry status → Policy Created
                $this->EnquiryModel->update($quot['enquiry_id'], ['status' => 'Policy Created']);

                Jobs::addJob(['job_name' => 'readFileAndCalculateCommission','payload' => ['policy_id' => $newPolicyId]]);
                log_message("info",'readFileAndCalculateCommission job pushed');

                // Call helper to create BDS record after creating client,clientPolicy,vehicle records
                // $policyData = $this->PolicyModel->select('partner_policy.*,Q.insurer_id,Q.insurer_branch_id,E.name as client_name,E.mobile as client_mobile,E.email as client_email,E.reg_no,E.vehicle_type_id,A.id as agent_id,A.agent_code')
                //                                 ->join('partner_quotation Q', 'Q.id = partner_policy.quotation_id AND Q.status = "Accepted"', 'left')
                //                                 ->join('partner_enquiry E', 'E.id = partner_policy.enquiry_id', 'left')
                //                                 ->join('partner_agent A', 'A.id = partner_policy.agent_id', 'left')
                //                                 ->where('partner_policy.id',$newPolicyId)
                //                                 ->first();
                // $bdsLogs = createBDS($policyData, $newPolicyId);
                // if (!empty($bdsLogs)) {
                //     foreach ($bdsLogs as $msg) {
                //         log_message('info', '[BDS Entry] ' . $msg);
                //     }
                // }
            }


            return $this->respond([
                'status' => 'success',
                'code'   => 200,
                'msg'    => 'Quotation created successfully'
            ], 200);


        } catch (\Exception $e) {
            return $this->respond([
                'status' => 'failed',
                'code'   => 500,
                'error'  => $e->getMessage()
            ], 500);
        }
    }


    public function updateQuoteData()
    {
        try {

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


            if (empty($quotationData['quotation_id'])) {
                return $this->respond([
                    'status'  => 'failed',
                    'code'    => 400,
                    'message' => 'quotation_id is required'
                ], 400);
            }

            $quotationId = $quotationData['quotation_id'];
            unset($quotationData['quotation_id']);

            // Remove empty values so DB won't overwrite with null
            $quotationData = array_filter($quotationData, function ($value) {
                return $value !== "" && $value !== null;
            });


            $this->QuotationModel->update($quotationId, $quotationData);

            return $this->respond(['status' => 'success','code'   => 200,'message'=> 'Quotation updated'], 200);


        } catch (\Exception $e) {
            return $this->respond(['status' => 'failed','code'   => 500,'error'  => $e->getMessage() ], 500);
        }
    }


    public function testPolicy($policyId = 81){
         $policyData = $this->PolicyModel->select('partner_policy.*,Q.insurer_id,Q.insurer_branch_id,E.name as client_name,E.mobile as client_mobile,E.email as client_email,E.reg_no,E.vehicle_type_id,A.id as agent_id,A.agent_code')
                                                ->join('partner_quotation Q', 'Q.id = partner_policy.quotation_id AND Q.status = "Accepted"', 'left')
                                                ->join('partner_enquiry E', 'E.id = partner_policy.enquiry_id', 'left')
                                                ->join('partner_agent A', 'A.id = partner_policy.agent_id', 'left')
                                                ->where('partner_policy.id',$policyId)
                                                ->first();

          return $this->respond([
                'status' => 'success',
                'code'   => 200,
                'error'  => $policyData
            ], 200);
    }







}
