<?php
ini_set('display_errors', 1);
date_default_timezone_set('Asia/Kolkata');
require_once '/home/rejoiceysn98/api.rejoicelearning.in/resources/base_path_include.php';

require_once $base_path_to_learning_resources  . "includes/connect.php";
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/mail_system/aws_mail_send.php';

// try{
// NOTES
//  -- status for mail_body_queue means 0 for pending, 1 for ready to be delivered, 2 for delivering, 3 for delivered -1 for rejected
//  -- status for mail_recipient_list 0 means undelivered, 1 means delivered, -1 means rejected

// preparing the query for status update of mail_body
$update_status_mail_body = $conn_rjllearning->prepare("Update mail_body_queue set status = ? where id = ?");

// preparing query for updating the status of mail_body_recipient batch
$update_status_recipient_mail = $conn_rjllearning->prepare("Update mail_recipient_queue set status = ? where id = ?");

// preparing query for getting recipients of mail
$get_receipients_mail = $conn_rjllearning->prepare("Select id, recipient from mail_recipient_queue where mail_body_id = ? and status = ?");

// preparing query for deletion of mail_body and recipient
$delete_mail_body_queue = $conn_rjllearning->prepare("Delete from mail_body_queue where id = ?");
$delete_mail_recipient_queue = $conn_rjllearning->prepare("Delete from mail_recipient_queue where mail_body_id = ?");

// fetching cron job of mail
$sql_fetch_email_cron = "Select running_status from cronjob_activity where activity = ? and status = ? and running_status = ?";
$fetch_email_cron_job = $conn_rjllearning->prepare($sql_fetch_email_cron);
$fetch_email_cron_job->execute(array('mail', 1, 1));
$result_cron_job = $fetch_email_cron_job->fetchAll();
if (count($result_cron_job) != 1) {
    // do nothing but end the file
    die("here");
} else {
    // updating the status of cron job
    $sql_update_cron_job = "Update cronjob_activity set running_status = ?, date = ?, time = ? where activity = ?";
    $update_cron_job = $conn_rjllearning->prepare($sql_update_cron_job);
    $update_cron_job->execute(array('0', date("Y-m-d"), time(), 'mail'));

    $sql_fetch_mail_body = "Select id, sender, subject, message, status, priority, delete_immediate from mail_body_queue where status = ? order by priority asc limit 500";
    $fetch_mail_body = $conn_rjllearning->prepare($sql_fetch_mail_body);
    $fetch_mail_body->execute(array(1));
    while ($temp_mail_body = $fetch_mail_body->fetch(PDO::FETCH_ASSOC)) {

        // put mail body status to delivering
        $update_status_mail_body->execute(array(2, $temp_mail_body['id']));

        // uncomment the below lines if using default php mailer
        // $header= "From:".$temp_mail_body['sender']." \r\n";
        // $header .= "MIME-Version: 1.0\r\n";
        // $header .= "Content-type: text/html\r\n";

        $counter_of_error = 0;
        // get all recipients
        $get_receipients_mail->execute(array($temp_mail_body['id'], 0));
        foreach ($get_receipients_mail->fetchAll() as $temp_recipient) {
            // send mail using normal php mailer
            // if(mail($temp_recipient['recipient'], $temp_mail_body['subject'], $temp_mail_body['message'], $header)) {
            if (mailAWSses($temp_recipient['recipient'], $temp_mail_body['sender'], $temp_mail_body['subject'], $temp_mail_body['message'])) {
                // update recipient status as delivered
                $update_status_recipient_mail->execute(array('1', $temp_recipient['id']));
            } else {
                // update recipient status as rejected
                $update_status_recipient_mail->execute(array('-1', $temp_recipient['id']));
                $counter_of_error++;
            }
        }

        // now that all recipients delivered change status to delivered
        if ($counter_of_error != 0) {
            $update_status_mail_body->execute(array('3', $temp_mail_body['id']));
        } else {
            $update_status_mail_body->execute(array('-1', $temp_mail_body['id']));
        }

        // delete if bool true
        if ($temp_mail_body['delete_immediate'] == 1) {
            $delete_mail_body_queue->execute(array($temp_mail_body['id']));
            $delete_mail_recipient_queue->execute(array($temp_mail_body['id']));
        }
    }

    // updating the cron job to complete status
    $update_cron_job->execute(array('1', date("Y-m-d"), time(), 'mail'));
}
echo "here at success";
// } catch(Exception $e) {
//     die("Error ".$e->getMessage());
// }
