<?php

include "db.class.php";
include "../email.class.php";
$email = new email();
$db = new db();

$res = $db->query("SELECT * FROM tanks WHERE 1 ORDER BY company_id ASC");
while ($row = $res->fetch_assoc()) {
    // get last time it connected

    $log_res = $db->query("SELECT * FROM tank_level_log WHERE tank_id = " . $row['record_id'] . " ORDER BY record_id DESC LIMIT 1");
    if ($log_res->num_rows > 0) {

        $log = $log_res->fetch_assoc();
        echo $row['name'];
        echo "<br>" . $date_last_connected = $log['date_time_measured'];
        echo "<br>";
        echo
            $time_diff = strtotime("now + 2 hours") - strtotime($date_last_connected);
        echo strtotime("now + 2 hours") . "<br>";
        echo strtotime($date_last_connected) . "<br>";
        echo $time_diff . "<br>";
        // send email only if it's been a multiple of 15 minutes (with a small grace window, e.g., ±30s)
        if ($time_diff >= 900) {
            echo "Tank " . $row['name'] . " has not connected in the last 15 minutes\n";

            $email_res = $db->query("SELECT * FROM email_notifications WHERE company_id = " . $row['company_id']);
            if ($email_res->num_rows > 0) {
                $emails = [];
                $names = [];
                while ($email_data = $email_res->fetch_assoc()) {
                    $emails[] = $email_data['email'];
                    $names[] = $email_data['name'];
                }
                $message = '<html>
                <body style="font-family: Arial, sans-serif; font-size: 14px;">
                    <h3 style="margin: 0px; padding: 0px;">Tank ' . $row['name'] . ' has not connected in the last 15 minutes</h3>
                    <h3 style="margin: 0px; padding: 0px;">Last Heartbeat: ' . $date_last_connected . '</h3>
                </body>
                </html>';

                $email->send_mail($emails, $names, $message, $row['name'] . " NOT CONNECTED");
            }
        }
    }
}




