<?

include "../classes/db.class.php";
include "../classes/email.class.php";

$db = new db();
$email_class = new email();

// $no_inspection_records_header = "<br><h1>NO RECORD OF INSPECITONS</h1><br>";
$total_inspections = 0;
$total_inspections_missed = 0;
$yesterday_inspection_records_header = "<br><h2>INSPECTIONS DONE THIS MORNING</h2><br>";
$no_inspections_yesterday_header = "<br><h2>INSPECTIONS NOT DONE THIS MORNING </h2><br>";
$no_inspections = '';
$today = date('Y-m-d');
$yesterday = date('Y-m-d');
$farm_res = $db->exec_query('farms', ['*']);
while ($farm = $farm_res->fetch_assoc()) {
    $assets_res = $db->exec_query('assets', ['*'], '', '', '', '', "farm_id = {$farm['record_id']}");
    while ($asset = $assets_res->fetch_assoc()) {
        echo '<br>' . $asset['asset_id'] . '<br>';

        $inspections_res = $db->exec_query('inspections', ['*'], '', '', '', '', "asset_record_id = {$asset['record_id']} AND date_time BETWEEN '$yesterday 00:00' AND '$today 23:59'");
        if ($inspections_res->num_rows >= 1) {
            $row = $inspections_res->fetch_assoc();
            $inspection_done =  $inspection_done . "<h3>{$asset['fleet_no']} {$asset['description']} DONE AT {$row['date_time']}</h3><br>";
            echo 'INSPECTIONS DONE';
            $total_inspections++;
        } else {
            $inspection_missed =  $inspection_missed . "<h3>{$asset['fleet_no']} {$asset['description']}</h3><br>";
            echo 'INSPECTIONS NOT DONE';
            $total_inspections_missed++;
        }
    }
    $email_list = $db->exec_query('emails', ['*'], '', '', '', '', "(farm_id = {$farm['record_id']} OR farm_id = 0) AND (event_types = 'ALL' OR event_types = 'REPORTS')");
    if ($email_list->num_rows > 0) {

        while ($email = $email_list->fetch_assoc()) {

            $emails[] =  $email['email'];
            $names[] =  $email['name'];
        }

        echo $message = "
    <h1> INSPECTIONS REPORT </h1><br><hr>
    <h2>FARM : <b>{$farm['farm_name']}</b><br><br>
    TOTAL DONE: $total_inspections<br><br>TOTAL NOT DONE:$total_inspections_missed<br><br><hr>
    $yesterday_inspection_records_header<hr>
    $inspection_done<hr>
    $no_inspections_yesterday_header<hr>
    $inspection_missed
    
    ";
        $subject = strtoupper("{$farm['farm_name']} DAILY INSPECTIONS");
        echo $email_class->send_mail($emails, $names, $message, $subject);
    } else {
    }
    $inspection_done = '';
    $inspection_missed = '';
    $total_inspections = 0;
    $total_inspections_missed = 0;
    $emails = [];
    $names =  [];
}
