<?php

use App\Models\EnquiryModel;
use App\Models\QuotationModel;
use App\Models\PolicyModel;
use App\Models\AgentModel;
use App\Models\StaffModel;



if (!function_exists('trigger_email')) {
    /**
     * Trigger an email based on predefined actions
     *
     * @param string $action
     * @param array $data  // pass extra data needed for subject/body
     * @return array
     */
    function trigger_email(string $action, array $data = [])
    {
        try {

            $enquiryModel            = new EnquiryModel();
            $quotationModel          = new QuotationModel();
            $policyModel             = new PolicyModel();
            $agentModel              = new AgentModel();
            $staffModel              = new StaffModel();

            $to_email = '';
            $subject  = '';
            $message  = '';

            switch ($action) {
                case 'login_otp':
                    $to_email = $data['email'];
                    $subject  = "Your Login OTP";
                    $message  = "<p>Hello {$data['name']},</p><p>Your OTP is <b>{$data['otp']}</b></p>";
                    break;

                case 'enquiry_created':
                    $enquiryData = $enquiryModel->where(['id'  => $data['enquiry_id'] ])->first();
                    $agentData = $agentModel->where(['id'  => $enquiryData['agent_id'] ])->first();
                    $staffData = $staffModel->where(['id'  => $enquiryData['manager_id'] , 'role_id' => 1 ])->first();

                    $to_email = $staffData['email'];
                    $subject  = "New Enquiry Created";
                    $message  = "<p>A new Enquiry #{$data['enquiry_id']} has been created by {$agentData['name']}.</p>";
                    break;

                case 'enquiry_assigned':
                    $enquiryData = $enquiryModel->where(['id'  => $data['enquiry_id'] ])->first();
                    $staffData = $staffModel->where(['id'  => $enquiryData['assigned_to'] , 'role_id' => 2 ])->first();

                    $to_email = $staffData['email'];
                    $subject  = "Enquiry Assigned";
                    $message  = "<p>Enquiry #{$data['enquiry_id']} assigned to {$staffData['name']}.</p>";
                    break;

                case 'quotation_created':
                    $quotationData = $quotationModel->where(['id'  => $data['quotation_id'] ])->first();
                    $agentData = $agentModel->where(['id'  => $quotationData['agent_id'] ])->first();

                    $to_email = $agentData['email'];
                    $subject  = "Proposal Created";
                    $message  = "<p>A new quotation #{$data['quotation_id']} has been created for you.</p>";
                    break;

                case 'quotation_accepted':
                    $quotationData = $quotationModel->where(['id'  => $data['quotation_id'] ])->first();
                    $staffData = $staffModel->where(['id'  => $quotationData['assigned_to'] , 'role_id' => 2 ])->first();

                    $to_email = $staffData['email']; // assigned staff
                    $subject  = "Proposal Accepted";
                    $message  = "<p>Proposal #{$data['quotation_id']} was accepted.</p>";
                    break;

                case 'quotation_rejected':
                    $quotationData = $quotationModel->where(['id'  => $data['quotation_id'] ])->first();
                    $staffData = $staffModel->where(['id'  => $quotationData['assigned_to'] , 'role_id' => 2 ])->first();

                    $to_email = $staffData['email']; // assigned staff
                    $subject  = "Proposal Rejected";
                    $message  = "<p>Proposal #{$data['quotation_id']} was rejected.</p>";
                    break;

                case 'policy_created':
                    $policyData = $policyModel->where(['id'  => $data['policy_id'] ])->first();
                    $agentData = $agentModel->where(['id'  => $policyData['agent_id'] ])->first();

                    $to_email = $agentData['email'];
                    $subject  = "Policy Created";
                    $message  = "<p>Policy #{$policyData['policy_number']} has been created successfully.</p>";
                    break;

                default:
                    log_message('error', "[EMAIL ERROR] Unknown action '{$action}'");
                    return ['status' => 'failed', 'code' => 400, 'message' => 'Unknown email action'];
            }

            return send_email($to_email, $subject, $message);

        } catch (\Exception $e) {
            log_message('error', "[EMAIL ERROR] Exception: " . $e->getMessage());
            return ['status' => 'failed', 'code' => 500, 'message' => $e->getMessage()];
        }
    }
}


if (!function_exists('send_email')) {
    function send_email( $to_email , $subject , $message)
    {
        try {
            // Set up ZeptoMail API request
            $endpoint = "https://api.zeptomail.in/v1.1/email";
            $apiKey = env('ZOHO_API_KEY');
            $sender = env('ZOHO_SENDER_MAIL');

            $payload = [
                "from" => [
                    "address" => $sender,
                    "name" =>  "Nhance-Partner"
                ],
                "to" => [
                    ["email_address" => ["address" => $to_email]]
                ],
                "subject" => $subject,
                "htmlbody" => $message,
            ];

            

            $headers = [
                "Content-Type: application/json",
                "Authorization: Zoho-enczapikey " . $apiKey
            ];

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $endpoint);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

            if (curl_errno($ch)) {
                $error_msg = curl_error($ch);
                log_message('error', "[EMAIL ERROR] Curl failed: {$error_msg}");
                return ['status' => 'failed', 'code' => 500, 'message' => 'Curl error', 'error' => $error_msg];
            }

            curl_close($ch);

            $resp = json_decode($response, true);

            if (isset($resp['data'][0]['message']) && $resp['data'][0]['message'] == 'Email request received') {
                log_message('debug', 'OTP Send Success to agent , email = ' . $to_email);
                return ['status' => 'success', 'code' => 200, 'message' => 'Send Success'];
            } else {
                log_message('error', "[OTP Send FAILED] , email = {$to_email}, HTTP: {$httpCode}, Response: {$response}");
                return ['status' => 'failed', 'code' => 500, 'message' => 'Curl error', 'error' => $response];
            }
                    
            
        } catch (\Exception $e) {
            log_message('debug', 'Exception occurred while sending email to agent: ' . $e->getMessage());
        }
    }
}