<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once('C:/xampp/htdocs/property/vendor/autoload.php');
include_once('C:/xampp/htdocs/property/config.php');
include_once('C:/xampp/htdocs/property/functions.php');
include_once('C:/xampp/htdocs/property/Zenoph/Notify/AutoLoader.php');

// include_once('../config.php');
// include_once('../functions.php');

use SendinBlue\Client\Configuration;
use SendinBlue\Client\Api\TransactionalEmailsApi;
use SendinBlue\Client\Model\SendSmtpEmail;
use Zenoph\Notify\Enums\AuthModel;
use Zenoph\Notify\Enums\SMSType;
use Zenoph\Notify\Request\SMSRequest;

// Current date and time
date_default_timezone_set('Africa/Accra'); // Set the timezone to Accra, Ghana

$current_date = date("Y-m-d"); // Current date
$trigger_time = "14:00:00"; // Trigger time set to 2:00 PM

// Query to fetch tenants whose end_date is today and time is less than or equal to 2:00 PM
$tenants_query = $link->query("
    SELECT * FROM rent_tenant_unit_view 
    WHERE DATE(end_date) = '$current_date' 
    AND TIME(end_date) <= '$trigger_time'
");
$message_query = $link->query("SELECT * FROM message_templates WHERE `name` = 'checkout_reminder'");
$message_template = mysqli_fetch_assoc($message_query);
$cur_time = date("Y-m-d H:i:s");

while ($tenant = mysqli_fetch_array($tenants_query)) {
    // Prepare the message body
    $body = str_replace("{end_date}", date("jS F, Y", strtotime($tenant["end_date"])), $message_template["message"],);
    $body = str_replace("{unit_no}", $tenant["unit_no"], $body);

    // Send Email Reminder
    try {
        $api_key = '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';
        $config = Configuration::getDefaultConfiguration()->setApiKey('api-key', $api_key);
        $email_api = new TransactionalEmailsApi(new GuzzleHttp\Client(), $config);

        $email_template_path = ROOT_PATH . "templates/email/checkout_message.html";
        if ($email_content = file_get_contents($email_template_path)) {
            $email_content = str_replace("{name}", ucfirst($tenant["r_name"]), $email_content);
            $email_content = str_replace("{message}", nl2br($body), $email_content);
        } else {
            throw new Exception("Email template not found");
        }

        $email = new SendSmtpEmail([
            'subject' => ucfirst($message_template["subject"]),
            'htmlContent' => $email_content,
            'sender' => ['email' => 'info@londoneyeluxury.com', 'name' => 'London Eye Luxury Apartments'],
            'to' => [['email' => $tenant["r_email"], 'name' => ucfirst($tenant["r_name"])]],
            'textContent' => strip_tags($body),
        ]);

        $email_response = $email_api->sendTransacEmail($email);
        $email_status = isset($email_response['messageId']) ? 'delivered' : 'failed';

        saveEmail($link, $message_template["subject"], $body, $email_status, $tenant["r_name"], $tenant["r_email"], $tenant["r_contact"], $cur_time);
    } catch (Exception $e) {
        saveEmail($link, $message_template["subject"], $body, "failed", $tenant["r_name"], $tenant["r_email"], $tenant["r_contact"], $cur_time);
    }

    // Send SMS Reminder
    try {
        $sms_request = new SMSRequest();
        $sms_request->setHost('api.smsonlinegh.com');
        $sms_request->setAuthModel(AuthModel::API_KEY);
        $sms_request->setAuthApiKey('9fd9d812b64966b33328ef33341e799c2b6344177b69636510baa520db7bc975');
        $sms_request->setSMSType(SMSType::GSM_DEFAULT);
        $sms_request->setSender('NK Property');
        $sms_request->setMessage($body);
        $sms_request->addDestination($tenant["r_contact"]);

        $sms_response = $sms_request->submit();
        $sms_status = $sms_response ? 'sent' : 'failed';

        saveSMS($link, $message_template["subject"], $body, $sms_status, $tenant["r_name"], $tenant["r_contact"], $cur_time);
    } catch (Exception $e) {
        saveSMS($link, $message_template["subject"], $body, "failed", $tenant["r_name"], $tenant["r_contact"], $cur_time);
    }
}

?>
