<?php
session_start();
$_SESSION['user_id'] = 0;
include "../classes/db.class.php";
include "../classes/functions.class.php";

$functions = new functions();
// get the notification_setups from the db
$setup_res = $db->query("notification_setup", "SELECT * FROM notification_setup WHERE status = 'ACTIVE' AND (last_date_time_sent = '' OR last_date_time_sent < DATE_SUB(NOW(), INTERVAL 1 MINUTE))");
while ($setup = $setup_res->fetch_assoc()) {
    // get the setup detail to identify what needs to be checked
    $notification_type = $setup['notification_type'];
    $tank_ids_involved = explode(",", $setup['tank_ids']);
    $users_involved = explode(",", $setup['user_ids']);
    if ($notification_type == 0) {
        $subject = "TANKS OFFLINE";
        $email_html_body = "";
        $offline_minuts = $setup['offline_for'];
        $email_html_body = "
                <style>
                    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; color: #1d1d1f; line-height: 1.5; margin: 0; padding: 20px; background-color: #f5f5f7; }
                    .container { max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 12px; padding: 32px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
                    h1 { font-size: 24px; font-weight: 600; letter-spacing: -0.02em; margin-bottom: 24px; color: #1d1d1f; }
                    table { width: 100%; border-collapse: collapse; margin-top: 10px; }
                    th { text-align: left; font-size: 12px; text-transform: uppercase; color: #86868b; letter-spacing: 0.05em; padding: 12px 0; border-bottom: 1px solid #d2d2d7; }
                    td { padding: 16px 0; font-size: 15px; border-bottom: 1px solid #f5f5f7; color: #1d1d1f; }
                    .status-tag { color: #ff3b30; font-weight: 500; font-size: 13px; }
                </style>
                <div class='container'>
                    <h1>Tanks Offline</h1>
                    <table>
                        <thead>
                            <tr>
                                <th>Tank Name</th>
                                <th>Last Heartbeat</th>
                            </tr>
                        </thead>
                        <tbody>";
        // loop through the tanks involved and get the latest dat time reading and match weather its more than the offline_minuts ago
        foreach ($tank_ids_involved as $tank_id) {
            $tank_log_res = $db->query("tank_level_log", "SELECT * FROM tank_level_log WHERE tank_id = '$tank_id' ORDER BY record_id DESC LIMIT 1");
            $tank_log = $tank_log_res->fetch_assoc();
            $tank_res = $db->query("tanks", "SELECT * FROM tanks WHERE record_id = '$tank_id'");
            $tank = $tank_res->fetch_assoc();
            $tank_offline_time = $tank_log['date_time_measured'];
            $tank_offline_time = strtotime($tank_offline_time);
            $current_time = time();
            $diff = $current_time - $tank_offline_time;
            $diff = $diff / 60;

            if ($diff > $offline_minuts) {
                $email_html_body .= "
                <tr>
                    <td style='font-weight: 500;'>{$tank['name']}</td>
                    <td>{$tank_log['date_time_measured']}</td>
                </tr>";
            }
        }
        $email_html_body .= "</tbody></table></div>";
        $functions->add_to_handler(0, $setup['tank_ids'], $setup['user_ids'], $subject, $functions->ready_to_save($email_html_body));
        $db->query("notification_setup", "UPDATE notification_setup SET last_date_time_sent = NOW() WHERE record_id = '$setup[record_id]'");
        echo "UPDATE notification_setup SET last_date_time_sent = NOW() WHERE record_id = '$setup[record_id]'";
    } else {
        $subject = "TANKS REACHING MIN THRESHOLD";
        $email_html_body = "";
        $email_html_body = "
                <style>
                    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; color: #1d1d1f; line-height: 1.5; margin: 0; padding: 20px; background-color: #f5f5f7; }
                    .container { max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 12px; padding: 32px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
                    h1 { font-size: 24px; font-weight: 600; letter-spacing: -0.02em; margin-bottom: 24px; color: #1d1d1f; }
                    table { width: 100%; border-collapse: collapse; margin-top: 10px; }
                    th { text-align: left; font-size: 12px; text-transform: uppercase; color: #86868b; letter-spacing: 0.05em; padding: 12px 0; border-bottom: 1px solid #d2d2d7; }
                    td { padding: 16px 0; font-size: 15px; border-bottom: 1px solid #f5f5f7; color: #1d1d1f; }
                    .status-tag { color: #ff3b30; font-weight: 500; font-size: 13px; }
                </style>
                <div class='container'>
                    <h1>Tanks Reaching Min Threshold</h1>
                    <table>
                        <thead>
                            <tr>
                                <th>Tank Name</th>
                                <th>Current</th>
                            </tr>
                        </thead>
                        <tbody>";
        $min_theshold = $setup['min_threshold'];
        // match the min_theshold with the latest reading
        foreach ($tank_ids_involved as $tank_id) {
            $tank_log_res = $db->query("tank_level_log", "SELECT * FROM tank_level_log WHERE tank_id = '$tank_id' ORDER BY record_id DESC LIMIT 1");
            $tank_log = $tank_log_res->fetch_assoc();
            $tank_reading = $tank_log['distance'];
            // get the tank details from tank table
            $tank_res = $db->query("tanks", "SELECT * FROM tanks WHERE record_id = '$tank_id'");
            $tank = $tank_res->fetch_assoc();

            if ($tank['tank_type'] == "H_C") {
                $data = $functions->calculate_horizontal_cylinder_volume($tank['radius_mm'], ($tank['radius_mm'] * 2) - ($tank_reading + $tank['add_to_distance']), $tank['length_mm']);
            } else {
                $data = $functions->calculate_vertical_cylinder_volume($tank['radius_mm'], ($tank['radius_mm'] * 2) - ($tank_reading + $tank['add_to_distance']), $tank['length_mm']);
            }
            if ($data['percentage_filled'] <= $min_theshold) {
                $email_html_body .= "
                <tr>
                    <td style='font-weight: 500;'>{$tank['name']}</td>
                    <td>{$data['percentage_filled']} %</td>
                </tr>";
            }
        }
        $email_html_body .= "</tbody></table></div>";
        $functions->add_to_handler(0, $setup['tank_ids'], $setup['user_ids'], $subject, $functions->ready_to_save($email_html_body));
    }

    $db->query("notification_setup", "UPDATE notification_setup SET last_date_time_sent = NOW() WHERE record_id = '$setup[record_id]'");
    echo "UPDATE notification_setup SET last_date_time_sent = NOW() WHERE record_id = '$setup[record_id]'";
}


$functions = new functions();
$db = new db();