<?php
if (!function_exists('errorreturn')) {
    function errorreturn($x)
    {
        echo json_encode(array('status' => 0, 'errormsg' => $x), JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE);
        die();
    }
}
// base path must be called before calling this function

function sendMailTemplate1($conn_rjllearning, $from, $to, $subject, $message, $workspace_id, $institution_id = null, $branch_id = null, $userid = null, $institutions_logo = null, $type = null)
{



    require_once $GLOBALS['base_path_to_learning'] . 'functions/common_functions.php';
    if($institution_id!=null){
    $institution_data = getInstitution($conn_rjllearning, $institution_id);
    }
    if($branch_id!=null){
    $additional_data = ['branch_code', 'name', 'city', 'pincode', 'address', 'contact_number'];
    $branch_data = getBranchInfo($GLOBALS['conn_rjllearning_specific'], $institution_id, $branch_id, $additional_data);
    }
    if (!is_array($to)) {
        $to = [$to];
    }
    $message = str_replace('"', "'", $message);
$mail_message_string = "
<html>
    <head>
        <meta charset='utf-8'>
        <meta name='viewport' content='width=device-width, initial-scale=1.0'>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }

            body {
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
                line-height: 1.6;
                background-color: #f9fafb;
                padding: 20px;
                min-height: 100vh;
                color: #4b5563;
                display: flex;
                flex-direction: column;
                justify-content: space-between;
            }

            .container {
                width: 100%;
                max-width: 800px;
                background-color: white;
                box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
                padding: 40px;
                border-radius: 8px;
                margin: 0 auto;
                display: block;
                flex-grow: 1;
            }

            .header {
                display: flex;
                align-items: flex-start;
                gap: 40px;
                margin-bottom: 40px;
                padding-bottom: 20px;
                border-bottom: 1px solid #e5e7eb;
            }

            .logo {
                width: 90px;
                height: 90px;
                object-fit: contain;
                flex-shrink: 0;
            }

            .institution-details {
                flex-grow: 1;
            }

            .institution-name {
                font-size: 18px;
                font-weight: bold; 
                color: #239273;
                margin-bottom: 4px;
            }

            .institution-code,
            .branch-address {
                font-size: 14px;
                margin-bottom: 4px;
            }

            .tag-line {
                font-size: 14px;
                font-style: italic;
                margin-top: 4px;
            }

            .content {
                min-height: 200px;
                font-size: 14px;
                line-height: 1.8;
                
                padding: 0px 0;
            }

            .content h1 {
                color: #dc2626;
                font-size: 24px;
                margin-bottom: 20px;
            }

            .content p {
                margin-bottom: 16px;
            }

            .content strong {
                color: #1f2937;
            }

            .signature {
                margin-top: 40px;
            }

            .footer-content {
                display: flex;
                justify-content: center;
                width: 100%;
                gap: 10px;
            }
            
            .footer-logo {
                width: 125px;
                height: 50px;
                object-fit: contain;
            }
            
            .footer-text {
                font-size: 12px;
                color: #6b7280;
                text-align: left;
            }
            
            .footer-powered-by {
                font-size: 12px;
                font-weight: bold;
                color: #6b7280;
                text-align: center;
                width: 100%;
                margin-bottom: 8px;
            }
            
            .footer {
                margin-top: 40px;
                padding-top: 10px;
                border-top: 1px solid #e5e7eb;
                text-align: center;
                padding-bottom: 10px;
            }

            /* Media query for responsive design */
            @media (max-width: 640px) {
                .container {
                    padding: 20px;
                }
                
                .header {
                    gap: 20px;
                }
                
                .logo {
                    width: 70px;
                    height: 70px;
                }
            }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>";
              
            // Check for institution logo
            if ($institution_id == null) {
                $mail_message_string .= "<img src='https://rejoicebilldesk.in/rjllearning_development/resources/assets/rejoice_learning_no_text_logo.svg' alt='Company Logo' class='logo'>";
            } else {
                $mail_message_string .= "<img src='" . $institution_data['logo'] . "?v=" . time() . "' alt='Institution Logo' class='logo'>";
            }
            
            $mail_message_string .= "
            <div class='institution-details'>";
            
            // Check for institution and branch names
            if (!empty($institution_data['institution_name']) && !empty($branch_data['name'])) {
                $mail_message_string .= "<h1 class='institution-name'>" . $institution_data['institution_name'] . "</h1>";
            } elseif (!empty($institution_data['institution_name'])) {
                $mail_message_string .= "<h1 class='institution-name'>" . $institution_data['institution_name'] . "</h1>";
            } elseif (!empty($branch_data['name'])) {
                $mail_message_string .= "<h1 class='institution-name'>" . $branch_data['name'] . "</h1>";
            } else {
                $mail_message_string .= "<h1 class='institution-name'>Institution Name - Branch Name</h1>"; // Fallback text
            }

            
            $mail_message_string .= "
                <p class='institution-code'>Institution Code: " . (!empty($institution_data['institution_code']) ? $institution_data['institution_code'] : 'N/A') . "</p>
                <p class='branch-address'>" . (!empty($branch_data['address']) ? $branch_data['address'] : 'Branch Address') . "</p>
                <p class='tag-line'>" . (!empty($tag_line) ? $tag_line : '') . "</p>
            </div>
        </div>
        <div class='content'>
            $message
        </div>
        <div class='signature'>
            <p>Thanks and Regards,</p><br><br>
            Sincerely,<br>
            The " . $GLOBALS['web_app_title'] . " Team.
        </div>
        <div class='footer'>
            <p class='footer-powered-by'>Powered by</p>
            <div class='footer-content'>
                <img src='https://rejoicebilldesk.in/rjllearning_development/resources/assets/rejoice_learning_text_logo_png_logo.png' class='footer-logo'>
                <p class='footer-text'>".$GLOBALS['copyright_msg']."</p>
            </div>
        </div>
    </div>
    </body>
</html>";
    // feeding to mail dbs

    try {
        // adding to mail_body_queue table
        $sql = "Insert into mail_body_queue(workspace_id,institution_id,branch_id,userid, sender, subject, message, date, time, status, priority, delete_immediate) values (?,?,?,?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $insert = $conn_rjllearning->prepare($sql);
        $insert->execute(array($workspace_id, $institution_id, $branch_id, $userid, $from, $subject, $mail_message_string, date("Y-m-d"), time(), 0, '1', 1));
        $mail_body_id = $conn_rjllearning->lastInsertId();

        // adding mail recipients to mail_recipient_queue
        $sql = "Insert into mail_recipient_queue(mail_body_id, recipient, status) values(?, ?, ?)";
        $insert = $conn_rjllearning->prepare($sql);
        foreach ($to as $sender) {
            $insert->execute(array($mail_body_id, $sender, '0'));
        }

        // updating mail_body_queue id to be ready for delivery
        $update_delivery_status = $conn_rjllearning->prepare("Update mail_body_queue set status = ? where id = ?");
        $update_delivery_status->execute(array('1', $mail_body_id));

        
        $modules_to_send_immediately = ['real_time'];
        if (in_array($type, $modules_to_send_immediately)) {
            sendMailImmediately($conn_rjllearning, $mail_body_id, $workspace_id, $institution_id, $branch_id);
        }
        return true;
    } catch (Exception $e) {
        successreturn("Workspace has been successfully created. Kindly use the reset password method to set your password." . $e->getMessage());
    }
}






function sendMailImmediately($conn_rjllearning, $mail_body_id, $workspace_id, $institution_id, $branch_id)
{

    require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/mail_system/aws_mail_send.php';
    require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/cron_jobs/function/function.php';
    try {
        // Begin Transaction
        $conn_rjllearning->beginTransaction();

        // Get mail body details
        $fetch_mail_body = $conn_rjllearning->prepare("SELECT id, sender, subject, message, delete_immediate FROM mail_body_queue WHERE id = ? AND status = ?");
        $fetch_mail_body->execute([$mail_body_id, 1]);
        $mail_body = $fetch_mail_body->fetch(PDO::FETCH_ASSOC);

        if (!$mail_body) {
            throw new Exception("Mail body not found or already processed.");
        }

        // Update mail body status to "delivering"
        $update_status_mail_body = $conn_rjllearning->prepare("UPDATE mail_body_queue SET status = ? WHERE id = ?");
        $update_status_mail_body->execute([2, $mail_body['id']]);

        // Get recipients for the mail body
        $get_recipients_mail = $conn_rjllearning->prepare("SELECT id, recipient FROM mail_recipient_queue WHERE mail_body_id = ? AND status = ?");
        $get_recipients_mail->execute([$mail_body['id'], 0]);
        $success_count = 0;
        $error_count = 0;

        foreach ($get_recipients_mail->fetchAll(PDO::FETCH_ASSOC) as $recipient) {


            // Send mail using AWS SES (or replace with your mail function)
            if (mailAWSses($recipient['recipient'], $mail_body['sender'], $mail_body['subject'], $mail_body['message'])) {
                // Mark recipient as delivered
                $update_status_recipient_mail = $conn_rjllearning->prepare("UPDATE mail_recipient_queue SET status = ? WHERE id = ?");
                $update_status_recipient_mail->execute([1, $recipient['id']]);
                $success_count++;
            } else {
                // Mark recipient as rejected
                $update_status_recipient_mail = $conn_rjllearning->prepare("UPDATE mail_recipient_queue SET status = ? WHERE id = ?");
                $update_status_recipient_mail->execute([-1, $recipient['id']]);
                $error_count++;
            }
        }
        if ($success_count > 0) {
            updateMailSmsCount($workspace_id, $institution_id, $branch_id, $success_count, null, null, 'mail', $conn_rjllearning);
        }

        // Update mail body status based on errors
        $final_status = ($error_count === 0) ? 3 : -1;
        $update_status_mail_body->execute([$final_status, $mail_body['id']]);

        // Delete mail body and recipients if delete_immediate is set
        if ($mail_body['delete_immediate'] == 1) {
            $delete_mail_body_queue = $conn_rjllearning->prepare("DELETE FROM mail_body_queue WHERE id = ?");
            $delete_mail_body_queue->execute([$mail_body['id']]);

            $delete_mail_recipient_queue = $conn_rjllearning->prepare("DELETE FROM mail_recipient_queue WHERE mail_body_id = ?");
            $delete_mail_recipient_queue->execute([$mail_body['id']]);
        }

        // Commit Transaction
        $conn_rjllearning->commit();

        return true;
    } catch (Exception $e) {
        $conn_rjllearning->rollBack();
        error_log("Error sending mail: " . $e->getMessage());
        return false;
    }
}
