<?php

require_once(__DIR__ . "/vendor/autoload.php");
require_once(__DIR__ . "/config.php");

use SendinBlue\Client\Configuration;
use SendinBlue\Client\Api\TransactionalEmailsApi;
use SendinBlue\Client\Model\SendSmtpEmail;

// Load environment variables (ensure you've set these in a .env or config file)
$sendinblueApiKey = getenv('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');
$senderEmail = getenv('info@londoneyeluxury.com');
$senderName = getenv('api');

// Function to send an email using Sendinblue
if (!function_exists("send_email")) {
    function send_email($to_email, $subject, $msg)
    {
        global $sendinblueApiKey, $senderEmail, $senderName;

        // Fetch building image and branch name (if available)
        $image_building = '';
        if (!empty($_SESSION['objLogin']['building_image'])) {
            $image_building = WEB_URL . 'img/upload/' . $_SESSION['objLogin']['building_image'];
        }

        $branch_name = $_SESSION['objLogin']['branch_name'] ?? '';

        // Load email template with dynamic data
        $variables = [
            'logo' => $image_building,
            'name' => $branch_name,
            'subject' => $subject,
            'message' => $msg,
            'site_url' => "#"
        ];

        $body = loadEmailTemplate("tmp_common.html", $variables);

        // Configure the Sendinblue API
        $config = Configuration::getDefaultConfiguration()->setApiKey('api-key', $sendinblueApiKey);
        $api_instance = new TransactionalEmailsApi(new GuzzleHttp\Client(), $config);

        // Create the email object
        $email = new SendSmtpEmail([
            'subject' => $subject,
            'htmlContent' => $body,
            'sender' => ['email' => $senderEmail, 'name' => $senderName],
            'to' => [['email' => $to_email, 'name' => $to_email]],
            'textContent' => strip_tags($body),
        ]);

        // Send the email
        try {
            $response = $api_instance->sendTransacEmail($email);
            return isset($response['messageId']); // Return true if email is successfully sent
        } catch (Exception $e) {
            echo 'Exception when sending email: ', $e->getMessage(), PHP_EOL;
            return false;
        }
    }
}


// Load email template and replace placeholders
if (!function_exists("loadEmailTemplate")) {
    function loadEmailTemplate($temp_name, $variables = [])
    {
        $template = file_get_contents(ROOT_PATH . "partial/email_templates/" . $temp_name);
        foreach ($variables as $key => $value) {
            $template = str_replace('{{ ' . $key . ' }}', $value ?? '', $template);
        }
        return $template;
    }
}

if (!function_exists("post_input_serilization")) {
    function post_input_serilization($input = null)
    {
        $input = $input ?? $_POST;
        $data = [];
        foreach ($input as $key => $value) {
            $data[$key] = is_array($value) ? post_input_serilization($value) : htmlspecialchars($value);
        }
        return $data;
    }
}

if (!function_exists("get_input_serilization")) {
    function get_input_serilization()
    {
        $input = $_GET;
        $data = [];
        foreach ($input as $key => $value) {
            $data[$key] = htmlspecialchars($value);
        }
        return $data;
    }
}

if (!function_exists("hash_password")) {
    function hash_password($password)
    {
        return password_hash($password, PASSWORD_BCRYPT);
    }
}

if (!function_exists("verify_password")) {
    function verify_password($password, $hash)
    {
        return password_verify($password, $hash);
    }
}

if (!function_exists("check_login")) {
    function check_login()
    {
        return isset($_SESSION["login_type"]) && in_array($_SESSION["login_type"], ["admin", "super"]);
    }
}

if (!function_exists("datetimediff")) {
    function datetimediff($str_interval, $start_date, $end_date, $relative = false)
    {
        if (is_string($start_date)) $start_date = date_create($start_date);
        if (is_string($end_date)) $end_date = date_create($end_date);

        $diff = date_diff($start_date, $end_date, !$relative);

        switch ($str_interval) {
            case "y":
                $total = $diff->y + $diff->m / 12 + $diff->d / 365.25;
                break;
            case "m":
                $total = $diff->y * 12 + $diff->m + $diff->d / 30 + $diff->h / 24;
                break;
            case "d":
                $total = $diff->y * 365.25 + $diff->m * 30 + $diff->d + $diff->h / 24 + $diff->i / 60;
                break;
            case "h":
                $total = ($diff->y * 365.25 + $diff->m * 30 + $diff->d) * 24 + $diff->h + $diff->i / 60;
                break;
            case "i":
                $total = (($diff->y * 365.25 + $diff->m * 30 + $diff->d) * 24 + $diff->h) * 60 + $diff->i + $diff->s / 60;
                break;
            case "s":
                $total = ((($diff->y * 365.25 + $diff->m * 30 + $diff->d) * 24 + $diff->h) * 60 + $diff->i) * 60 + $diff->s;
                break;
        }

        return $diff->invert ? -1 * $total : $total;
    }
}

if (!function_exists("money_print")) {
    function money_print($value)
    {
        // Ensure the value is a valid float, fallback to 0 if null or invalid
        $value = is_numeric($value) ? floatval($value) : 0.0;
        return CURRENCY . " " . number_format($value, 2);
    }
}

if (!function_exists("money_sym")) {
    function money_sym($value)
    {
        // Ensure the value is a valid float, fallback to 0 if null or invalid
        $value = is_numeric($value) ? floatval($value) : 0.0;
        return "$ " . number_format($value, 2);
    }
}


function saveEmail($link, $title, $message, $status, $business_name, $receiver_email, $receiver_phone, $time_created) {
    $stmt = $link->prepare("INSERT INTO messages (subject, message, status, receiver, receiver_email, receiver_phone, time_created, channel) VALUES (?, ?, ?, ?, ?, ?, ?, 'Email')");
    $stmt->bind_param("sssssss", $title, $message, $status, $business_name, $receiver_email, $receiver_phone, $time_created);
    $stmt->execute();
    $stmt->close();
}

function saveSMS($link, $title, $message, $status, $receiver_name, $receiver_phone, $time_created) {
    $stmt = $link->prepare("INSERT INTO messages (subject, message, status, receiver, receiver_phone, time_created, channel) VALUES (?, ?, ?, ?, ?, ?, 'SMS')");
    $stmt->bind_param("ssssss", $title, $message, $status, $receiver_name, $receiver_phone, $time_created);
    $stmt->execute();
    $stmt->close();
}
