<?php

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');
require_once('../config.php');
require_once('./money_format.php');


if (isset($_POST['generate_loi'])) {
    try {
        // {"generate_loi":"true","loi_subject":"Letter of Intent for Customer Support Executive at Jobaaj Group","applicant_id":"126113","aid":"19922","date_of_joining":"2025-08-18","offer_position":"Customer Support Executive","applicant_name":"DEVANSHI","applicant_email":"sdevanshi641@gmail.com","applicant_mobile":9632587410,"employement_type":"internship","is_on_trial":"1","trial_period_days":"7","internship_period":"3"}
    
        // $loi_reference_id = $_POST['loi_reference_id'];
        $loi_subject = mysqli_real_escape_string($db, $_POST['loi_subject']);
        $applicant_id = mysqli_real_escape_string($db, $_POST['applicant_id']); // int
        $aid = mysqli_real_escape_string($db, $_POST['aid']); // int
        $applicant_name = mysqli_real_escape_string($db, $_POST['applicant_name']);     // varchar
        $applicant_email = mysqli_real_escape_string($db, $_POST['applicant_email']);   // varchar
        $applicant_mobile = mysqli_real_escape_string($db, $_POST['applicant_mobile']); // varchar

        $date_of_joining = mysqli_real_escape_string($db, $_POST['date_of_joining']);   // date
        $offer_position = mysqli_real_escape_string($db, $_POST['offer_position']);     // varchar

        $is_on_trial = mysqli_real_escape_string($db, $_POST['is_on_trial']);           // int
        $trial_period_days = mysqli_real_escape_string($db, empty($_POST['trial_period_days']) ? 0 : $_POST['trial_period_days']); // int

        $employment_type = mysqli_real_escape_string($db, $_POST['employement_type']); // varchar (full_time, part_time, internship)
        $internship_period = mysqli_real_escape_string($db, empty($_POST['internship_period']) ? 0 : $_POST['internship_period']); // int (months)

        // $total_payout = [
        //     "offer_ctc" => "",
        //     "internship_stipend" => [],
        //     "trial_period_stipend" => ""
        // ];
        $mail_log = json_encode([
            "status" => "Not Sent"
        ]);

        // insert data in table by mysqli_query()
        $insert_loi_sql = "INSERT INTO letters_of_intent (loi_subject, applicant_id, aid, applicant_name, applicant_email, applicant_mobile, date_of_joining, offer_position, is_on_trial, trial_period_days, employment_type, internship_period, mail_log) VALUES ('$loi_subject', '$applicant_id', '$aid', '$applicant_name', '$applicant_email', '$applicant_mobile', '$date_of_joining', '$offer_position', '$is_on_trial', '$trial_period_days', '$employment_type', '$internship_period', '$mail_log')";

        if (mysqli_query($db, $insert_loi_sql)) {
            echo json_encode(["status" => 200, "message" => "Data Inserted Successfully"]);
        } else {
            echo json_encode(["status" => 500, "message" => "Data Insertion Failed", "error" => mysqli_error($db)]);
        }
    } catch (\Throwable $th) {
        echo json_encode(["status" => 500, "message" => "Internal Server Error", "error" => $th->getMessage()]);
    }
    exit;
}

if(isset($_POST['add_loi'])){

    try {
        $loi_subject = mysqli_real_escape_string($db, $_POST['loi_subject']);
        $applicant_name = mysqli_real_escape_string($db, $_POST['applicant_name']);
        $applicant_email = mysqli_real_escape_string($db, $_POST['applicant_email']);
        $applicant_mobile = mysqli_real_escape_string($db, $_POST['applicant_mobile']);

        $date_of_joining = mysqli_real_escape_string($db, $_POST['date_of_joining']);
        $offer_position = mysqli_real_escape_string($db, $_POST['offer_position']);

        $is_on_trial = mysqli_real_escape_string($db, $_POST['is_on_trial']);
        $trial_period_days = mysqli_real_escape_string($db, empty($_POST['trial_period_days']) ? 0 : $_POST['trial_period_days']);

        $employment_type = mysqli_real_escape_string($db, $_POST['employment_type']);
        $internship_period = mysqli_real_escape_string($db, empty($_POST['internship_period']) ? 0 : $_POST['internship_period']);

        // $_POST['internship_stipend'] this is an array correct this
        $internship_stipend = [];
        if(isset($_POST['internship_stipend'])) {
            foreach ($_POST['internship_stipend'] as $value) {
                $internship_stipend[] = mysqli_real_escape_string($db, $value);
            }
        }
        $total_payout = [
            "offer_ctc" => mysqli_real_escape_string($db, empty($_POST['offer_ctc']) ? 0 : $_POST['offer_ctc']),
            "internship_stipend" => $internship_stipend,
            "trial_period_stipend" => mysqli_real_escape_string($db, empty($_POST['trial_period_stipend']) ? 0 : $_POST['trial_period_stipend'])
        ];
        $total_payout = json_encode($total_payout);

        $mail_log = json_encode([
            "status" => "Not Sent"
        ]);

        // insert data in table by mysqli_query()
        $insert_loi_sql = "INSERT INTO letters_of_intent (loi_subject, applicant_name, applicant_email, applicant_mobile, date_of_joining, offer_position, is_on_trial, trial_period_days, employment_type, internship_period, total_payout, mail_log) VALUES ('$loi_subject', '$applicant_name', '$applicant_email', '$applicant_mobile', '$date_of_joining', '$offer_position', '$is_on_trial', '$trial_period_days', '$employment_type', '$internship_period', '$total_payout', '$mail_log')";

        if (mysqli_query($db, $insert_loi_sql)) {
            echo json_encode(["status" => 200, "message" => "Data Inserted Successfully"]);
        } else {
            echo json_encode(["status" => 500, "message" => "Data Insertion Failed", "error" => mysqli_error($db)]);
        }
    } catch (\Throwable $th) {
        echo json_encode(["status" => 500, "message" => "Internal Server Error", "error" => $th->getMessage()]);
    }
    exit;
}


if(isset($_POST['add_loi_from_ccd'])){

    try {
        $loi_reference_id = mysqli_real_escape_string($db, $_POST['loi_reference_id']);
        $loi_subject = mysqli_real_escape_string($db, $_POST['loi_subject']);
        $applicant_id = mysqli_real_escape_string($db, $_POST['applicant_id']);
        $aid = mysqli_real_escape_string($db, $_POST['aid']);
        $applicant_name = mysqli_real_escape_string($db, $_POST['applicant_name']);
        $applicant_email = mysqli_real_escape_string($db, $_POST['applicant_email']);
        $applicant_mobile = mysqli_real_escape_string($db, $_POST['applicant_mobile']);

        $date_of_joining = mysqli_real_escape_string($db, $_POST['date_of_joining']);
        $offer_position = mysqli_real_escape_string($db, $_POST['offer_position']);

        $is_on_trial = mysqli_real_escape_string($db, $_POST['is_on_trial']);
        $trial_period_days = mysqli_real_escape_string($db, empty($_POST['trial_period_days']) ? 0 : $_POST['trial_period_days']);

        $employment_type = mysqli_real_escape_string($db, $_POST['employment_type']);
        $internship_period = mysqli_real_escape_string($db, empty($_POST['internship_period']) ? 0 : $_POST['internship_period']);

        // $_POST['internship_stipend'] this is an array
        $internship_stipend = [];
        if(isset($_POST['internship_stipend'])) {
            foreach ($_POST['internship_stipend'] as $value) {
                $internship_stipend[] = mysqli_real_escape_string($db, $value);
            }
        }
        $total_payout = [
            "offer_ctc" => mysqli_real_escape_string($db, empty($_POST['offer_ctc']) ? 0 : $_POST['offer_ctc']),
            "internship_stipend" => $internship_stipend,
            "trial_period_stipend" => mysqli_real_escape_string($db, empty($_POST['trial_period_stipend']) ? 0 : $_POST['trial_period_stipend'])
        ];
        $total_payout = json_encode($total_payout);

        // {"status":"Accepted","sent_at":"2025-08-21 17:13:50","sent_to":"iqbalshah9368@gmail.com", "sent_by":"employee_id","CC":"shivamsinghal160@gmail.com","subject":"Letter of Intent for SWE at Jobaaj Group","accepted_at":"2025-08-21 11:46:06"}
        $mail_log = json_encode($_POST['mail_log']);

        $content = mysqli_real_escape_string($db, $_POST['content']);

        // // create js object for all data which is above with same key name
        // $js_data = [
        //     "loi_reference_id" => $loi_reference_id,
        //     "loi_subject" => $loi_subject,
        //     "applicant_id" => $applicant_id,
        //     "aid" => $aid,
        //     "applicant_name" => $applicant_name,
        //     "applicant_email" => $applicant_email,
        //     "applicant_mobile" => $applicant_mobile,
        //     "date_of_joining" => $date_of_joining,
        //     "offer_position" => $offer_position,
        //     "is_on_trial" => $is_on_trial,
        //     "trial_period_days" => $trial_period_days,
        //     "employment_type" => $employment_type,
        //     "internship_period" => $internship_period,
        //     "internship_stipend" => $internship_stipend,    // array []
        //     "trial_period_stipend" => $trial_period_stipend,
        //     "offer_ctc" => $offer_ctc,
        //     "mail_log" => ["status"=>"Accepted","sent_at"=>"2025-08-21 17:13:50","sent_to"=>"iqbalshah9368@gmail.com","CC"=>"shivamsinghal160@gmail.com","subject"=>"Letter of Intent for SWE at Jobaaj Group","accepted_at"=>"2025-08-21 11:46:06"],
        //     "content" => $content,
        //     "add_loi_from_ccd" => 1
        // ];

        // insert data in table by mysqli_query()
        $insert_loi_sql = "INSERT INTO letters_of_intent (loi_reference_id, loi_subject, applicant_id, aid, applicant_name, applicant_email, applicant_mobile, date_of_joining, offer_position, is_on_trial, trial_period_days, employment_type, internship_period, total_payout, mail_log, content) VALUES ('$loi_reference_id', '$loi_subject', '$applicant_id', '$aid', '$applicant_name', '$applicant_email', '$applicant_mobile', '$date_of_joining', '$offer_position', '$is_on_trial', '$trial_period_days', '$employment_type', '$internship_period', '$total_payout', '$mail_log', '$content')";

        if (mysqli_query($db, $insert_loi_sql)) {
            echo json_encode(["status" => 200, "message" => "Data Inserted Successfully"]);
        } else {
            echo json_encode(["status" => 500, "message" => "Data Insertion Failed", "error" => mysqli_error($db)]);
        }
    } catch (\Throwable $th) {
        echo json_encode(["status" => 500, "message" => "Internal Server Error", "error" => $th->getMessage()]);
    }
    exit;
}


if(isset($_POST['update_loi'])){
    try {
        $edit_id = mysqli_real_escape_string($db, $_POST['edit_id']);
        $loi_subject = mysqli_real_escape_string($db, $_POST['loi_subject']);
        $applicant_name = mysqli_real_escape_string($db, $_POST['applicant_name']);
        $applicant_email = mysqli_real_escape_string($db, $_POST['applicant_email']);
        $applicant_mobile = mysqli_real_escape_string($db, $_POST['applicant_mobile']);

        $date_of_joining = mysqli_real_escape_string($db, $_POST['date_of_joining']);
        $offer_position = mysqli_real_escape_string($db, $_POST['offer_position']);

        $is_on_trial = mysqli_real_escape_string($db, $_POST['is_on_trial']);
        $trial_period_days = mysqli_real_escape_string($db, empty($_POST['trial_period_days']) ? 0 : $_POST['trial_period_days']);

        $employment_type = mysqli_real_escape_string($db, $_POST['employment_type']);
        $internship_period = mysqli_real_escape_string($db, empty($_POST['internship_period']) ? 0 : $_POST['internship_period']);

        $internship_stipend = [];
        if(isset($_POST['internship_stipend'])) {
            foreach ($_POST['internship_stipend'] as $value) {
                $internship_stipend[] = mysqli_real_escape_string($db, $value);
            }
        }
        $total_payout = [
            "offer_ctc" => mysqli_real_escape_string($db, empty($_POST['offer_ctc']) ? 0 : $_POST['offer_ctc']),
            "internship_stipend" => $internship_stipend,
            "trial_period_stipend" => mysqli_real_escape_string($db, empty($_POST['trial_period_stipend']) ? 0 : $_POST['trial_period_stipend'])
        ];
        $total_payout = json_encode($total_payout);

        // update data in table by mysqli_query()
        $update_loi_sql = "UPDATE letters_of_intent SET loi_subject='$loi_subject', applicant_name='$applicant_name', applicant_email='$applicant_email', applicant_mobile='$applicant_mobile', date_of_joining='$date_of_joining', offer_position='$offer_position', is_on_trial='$is_on_trial', trial_period_days='$trial_period_days', employment_type='$employment_type', internship_period='$internship_period', total_payout='$total_payout' WHERE id='$edit_id'";

        if (mysqli_query($db, $update_loi_sql)) {
            echo json_encode(["status" => 200, "message" => "Data Updated Successfully"]);
        } else {
            echo json_encode(["status" => 500, "message" => "Data Update Failed", "error" => mysqli_error($db)]);
        }
    } catch (\Throwable $th) {
        echo json_encode(["status" => 500, "message" => "Internal Server Error", "error" => $th->getMessage()]);
    }
    exit;
}

// Function to get current financial year (Apr–Mar)
function getFinancialYear() {
    $year = date('Y');
    $month = date('n'); // 1–12

    if ($month >= 4) {
        // April onwards -> currentYear-nextYear
        $nextYear = date('y', strtotime('+1 year'));
        return $year . '-' . $nextYear;
    } else {
        // Jan–Mar -> previousYear-currentYear
        $prevYear = $year - 1;
        $nextYear = date('y');
        return $prevYear . '-' . $nextYear;
    }
}
if(isset($_POST['get_loi_content_id'])) {
    $loi_id = mysqli_real_escape_string($db, $_POST['get_loi_content_id']);
    $loi_id = base64_decode($loi_id);
    $loi_template = mysqli_real_escape_string($db, $_POST['loi_template']);
    if(empty($loi_id) || empty($loi_template)) {
        echo json_encode(["status" => 400, "message" => "Invalid request."]);
        exit;
    }

    // Fetch LOI content from the database
    $loi_content = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM letters_of_intent WHERE id='$loi_id'"));
    if(empty($loi_content)) {
        echo json_encode(["status" => 404, "message" => "LOI not found."]);
        exit;
    }
    $total_payout = json_decode($loi_content['total_payout'], true);

    $name = $loi_content['applicant_name'] ?? 'Candidate';
    $email = $loi_content['applicant_email'] ?? 'candidate@gmail.com';
    $company_name = "Jobaaj Group";
    $parent_company_name = 'Nishtya India Private Limited';
    $doj = $loi_content['date_of_joining'] ?? '';
    $job_name = ucwords($loi_content['offer_position'] ?? '');
    $trial_period = $loi_content['trial_period_days'] ?? 0;
    $internship_period = $loi_content['internship_period'] ?? 0;

    $trial_pay_per_month = $total_payout['trial_period_stipend'] ?? 0;
    $internship_payout = $total_payout['internship_stipend'] ?? [];
    $ctc = $total_payout['offer_ctc'] ?? 0;

    // convert money format when not empty
    $formatted_trial_pay = !empty($trial_pay_per_month) ? IND_money_format($trial_pay_per_month) : '';
    $formatted_internship_pay = !empty($internship_payout) ? array_map('IND_money_format', $internship_payout) : [];
    $formatted_ctc = !empty($ctc) ? IND_money_format($ctc) : '';

    $subject = $loi_content['loi_subject'] ?? "Letter of Intent for $job_name at $company_name";

    // ########################################### Check if LOI content and reference ID are available
    if(!empty($loi_content['content']) && !empty($loi_content['loi_reference_id'])) {
        echo json_encode(["status" => 200, "message" => "LOI Exist.", "subject" => $subject, "applicant_email" => $email, "loi_reference_id" => $loi_content['loi_reference_id'], "content" => $loi_content['content']]);
        exit();
    }
    // ########################################### Check if LOI content and reference ID are available


    // ########################################### LOI not generated
    $last_loi_reference_id = mysqli_fetch_assoc(mysqli_query($db, "SELECT loi_reference_id
            FROM letters_of_intent
            WHERE loi_reference_id LIKE CONCAT('LOI/NIPL/', 
                CONCAT(
                    YEAR(CURDATE()) - IF(MONTH(CURDATE()) < 4, 1, 0),
                    '-',
                    RIGHT(YEAR(CURDATE()) + IF(MONTH(CURDATE()) >= 4, 1, 0), 2)
                ), '/%')
            ORDER BY CAST(SUBSTRING_INDEX(loi_reference_id, '/', -1) AS UNSIGNED) DESC
            LIMIT 1;"))['loi_reference_id'] ?? '';


    // ############################################### Generate the next reference ID based on the last one
    // LOI/NIPL/2025-26/0045 create like this
    $currentFY = getFinancialYear();
    if (!empty($last_loi_reference_id)) {
        $parts = explode('/', $last_loi_reference_id);
        if (count($parts) == 4 && $parts[0] == 'LOI' && $parts[1] == 'NIPL') {
            $lastFY = $parts[2];
            $lastNumber = intval($parts[3]);

            if ($lastFY == $currentFY) {
                // Same financial year → increment
                $year = $lastFY;
                $next_number = $lastNumber + 1;
            } else {
                // New financial year → reset to 0001
                $year = $currentFY;
                $next_number = 1;
            }
        }
    } else {
        // First time → start fresh
        $year = $currentFY;
        $next_number = 1;
    }
    $loi_reference_id = 'LOI/NIPL/' . $year . '/' . str_pad($next_number, 4, '0', STR_PAD_LEFT);
    // ############################################### Generate the next reference ID based on the last one


    
    // ################################################################### Create LOI template
    if ($loi_template === 'internship') {
        $ctc = ['internship_amount' => $formatted_internship_pay, 'internship_period'=>$internship_period];
    }
    $templateFile = "../loi_template/loi_{$loi_template}.php";
    if (!file_exists($templateFile)) {
        echo json_encode(["status" => 500 ,"message" => "Template file not found."]);
        exit;
    }
    require_once $templateFile;
    $loi_data = array(
        $loi_reference_id,
        $doj,
        $name,
        $job_name,
        $ctc,
        $trial_period,
        $trial_pay_per_month,
        $company_name,
        $parent_company_name
    );
    $content = generateLOIContent($loi_data);
    // ################################################################### Create LOI template

    if(!$content) {
        echo json_encode(["status" => 500 ,"message" => "Failed to generate LOI content."]);
        exit;
    }

    $loi_reference_id = mysqli_real_escape_string($db, $loi_reference_id);
    $loi_content = mysqli_real_escape_string($db, $content);
    // echo "UPDATE letters_of_intent SET loi_reference_id='$loi_reference_id', content='$content' WHERE id='$loi_id'";
    $q = mysqli_query($db, "UPDATE letters_of_intent SET loi_reference_id='$loi_reference_id', content='$loi_content' WHERE id='$loi_id'");
    if(!$q) {
        echo json_encode(["status" => 500, 'message'=>'Failed to update LOI', "error" => mysqli_error($db)]);
        exit;
    }

    echo json_encode(["status" => 200, "message" => "LOI updated successfully.", "subject" => $subject, "applicant_email" => $email, "loi_reference_id" => $loi_reference_id, "content" => $content]);
    // ########################################### LOI not generated

    exit;
}


function sendCurlRequest($url, $postFields = [], $isJson = false, $headers = [])
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); // Set timeout

    if (!empty($postFields)) {
        curl_setopt($ch, CURLOPT_POST, true);
        if ($isJson) {
            $postData = json_encode($postFields);
            $headers[] = 'Content-Type: application/json';
        } else {
            $postData = http_build_query($postFields);
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    }

    if (!empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Disable SSL verification if needed

    $response = curl_exec($ch);
    if ($response === false) {
        $error = curl_error($ch);
        curl_close($ch);
        return 'Curl error: ' . $error;
    }

    curl_close($ch);
    return $response;
}

if (isset($_POST['generateLoi_mail_body'])) {
    require_once('../mail/loi_mail.php');

    $data = json_decode($_POST['generateLoi_mail_body'], true);

    $c_date = date("Y-m-d H:i:s");

    $ccEmails = (isset($data['LOICCEmails']) && !empty($data['LOICCEmails'])) ? $data['LOICCEmails'] : '';

    $mail_status = loi_mail([$data['LOIEmail'], $ccEmails, $data['LOISubject'], $data['mailBody']]);

    if ($mail_status != '1') {
        echo json_encode(["status" => 500, "message" => "Mail Not Sent !"]);
        exit();
    }


    $loi_data = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM `letters_of_intent` WHERE `loi_reference_id`='$data[reference_id]'"));
    $mail_log = !empty($loi_data['mail_log']) ? json_decode($loi_data['mail_log'], true) : [];
    $mail_log['status'] = 'Sent';
    $mail_log['sent_at'] = $c_date;
    $mail_log['sent_to'] = $data['LOIEmail'];
    $mail_log['sent_by'] = $_SESSION['emp_id'];
    $mail_log['CC'] = $data['LOICCEmails'];
    $mail_log['subject'] = $data['LOISubject'];
    $mail_log = mysqli_real_escape_string($db, json_encode($mail_log));

    $update = mysqli_query($db, "UPDATE `letters_of_intent` SET mail_log='$mail_log' WHERE `loi_reference_id`='$data[reference_id]'");
    if (!$update) {
        echo json_encode(["status" => 500, "message" => "Failed to update mail log.", "error" => mysqli_error($db)]);
        exit();
    }


    // ################################################ send curl request
    try {
        $email = mysqli_real_escape_string($db, $data['LOIEmail']);
        $ccEmails = mysqli_real_escape_string($db, $ccEmails ?? '');
        $loi_reference_id = mysqli_real_escape_string($db, $loi_data['loi_reference_id']);
        $emp_type = mysqli_real_escape_string($db, $loi_data['employment_type']);
        $applicant_id = mysqli_real_escape_string($db, $loi_data['applicant_id']);
        $aid = mysqli_real_escape_string($db, $loi_data['aid']);
        $subject = mysqli_real_escape_string($db, $data['LOISubject']);
        $curl_response = sendCurlRequest("https://ccd.digitalprominds.com/fun/external_apis", [
            'email' => $email,
            'ccEmails' => $ccEmails,
            'loi_reference_id' => $loi_reference_id,
            'emp_type' => $emp_type,
            'applicant_id' => $applicant_id,
            'aid' => $aid,
            'subject' => $subject,
            'loi_mail_sent' => '1'
        ], true);
    } catch (\Throwable $th) {
        error_log("Error sending CURL request: " . $th->getMessage());
    }
    // ################################################

    echo json_encode(["status" => 200, "message" => "Mail Sent Successfully!", "loi_reference_id" => $data['reference_id'], 'curl_response' => $curl_response]);
    exit();
}

if(isset($_POST['loi_accepted'])){
    // select data
    $loi_reference_id = mysqli_real_escape_string($db, $_POST['loi_reference_id']);
    $loi_data = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM `letters_of_intent` WHERE `loi_reference_id` = '$loi_reference_id'"));
    $mail_log = json_decode($loi_data['mail_log'], true);
    $mail_log['status'] = 'Accepted';
    $mail_log['accepted_at'] = date("Y-m-d H:i:s");
    $mail_log = mysqli_real_escape_string($db, json_encode($mail_log));

    mysqli_query($db, "UPDATE `letters_of_intent` SET `mail_log` = '$mail_log' WHERE `loi_reference_id` = '$loi_reference_id'");
}