<?php
session_start();
$_SESSION['user_id'] = 0;
include "../classes/db.class.php";
include "../classes/functions.class.php";
include "../classes/email.class.php";

$db = new db();
$email = new email();

// 1. Setup Time Variables
$now_ts = strtotime("+2 Hours"); // Adjust to your local timezone
$today_date = date("Y-m-d", $now_ts);
$current_time = date("H:i", $now_ts);
$base_url = 'https://dev.jev.elegantwork.co.za/';

// 2. Fetch Active Tasks
$tasks = $db->query("automated_emails", "SELECT * FROM automated_emails WHERE status = 'ACTIVE'");

while ($task = $tasks->fetch_assoc()) {
    
    $scheduled_time = date("H:i", strtotime($task['sent_at']));
    $last_sent_date = ($task['last_sent']) ? date("Y-m-d", strtotime($task['last_sent'])) : '1970-01-01';

    // --- THE SELF-HEALING LOGIC ---
    
    // 1. Is it currently past the scheduled time?
    $is_past_time = ($current_time >= $scheduled_time);
    
    // 2. Have we already sent a report today?
    $already_sent_today = ($last_sent_date === $today_date);

    // Only proceed if it is past the time AND we haven't successfully sent one today
    if ($is_past_time && !$already_sent_today) {
        
        // C. Calculate Date Range based on frequency
        $to = date("Y-m-d H:i", $now_ts);
        if ($task['send_every'] == 'Day') {
            $from = date("Y-m-d H:i", strtotime("-1 day", $now_ts));
            $interval = 60;
        } elseif ($task['send_every'] == 'Week') {
            $from = date("Y-m-d H:i", strtotime("-7 days", $now_ts));
            $interval = 360;
        } elseif ($task['send_every'] == 'Month') {
            $from = date("Y-m-d H:i", strtotime("-1 month", $now_ts));
            $interval = 720;
        }

        // D. Build the URL
        $params = http_build_query([
            'to' => $to,
            'from' => $from,
            'intervals' => $interval,
            'tanks' => $task['tank_ids'],
            'no_buttons' => 1 
        ]);
        
        $url = $base_url . 'email_report.php?' . $params;

        // E. Fetch HTML Content
        $html = file_get_contents($url);
        if ($html === false) continue;

        // F. Process Styles (Inlining CSS for Email)
        $dom = new DOMDocument();
        @$dom->loadHTML($html);
        $xpath = new DOMXPath($dom);
        $css_files = $xpath->query('//link[@rel="stylesheet"]');
        $css_contents = '';
        foreach ($css_files as $css_node) {
            $href = $css_node->getAttribute('href');
            $css_url = (strpos($href, 'http') === 0) ? $href : $base_url . ltrim($href, '/');
            $css_contents .= @file_get_contents($css_url);
        }

        $message = preg_replace('/<link rel="stylesheet".*?>/i', '', $html);
        $message = preg_replace('/<script.*?>.*?<\/script>/is', '', $message);
        $message = str_replace('</head>', '<style>' . $css_contents . '</style></head>', $message);

        // G. Get Recipients
        $u_ids = $task['user_ids'];
        $user_res = $db->query("users", "SELECT email, username FROM users WHERE record_id IN ($u_ids)");
        
        $recipients = [];
        $names = [];
        while($u = $user_res->fetch_assoc()){
            $recipients[] = $u['email'];
            $names[] = $u['username'];
        }

        // H. Send and Mark as Sent
        if (!empty($recipients)) {
            $subject = "Inventory Report (" . $task['send_every'] . "): " . $task['task_name'];
            $success = $email->send_mail($recipients, $names, $message, $subject);
            
            if ($success) {
                // We update last_sent with NOW() so the 'already_sent_today' check 
                // prevents this from running again until tomorrow.
                $db->query("automated_emails", "UPDATE automated_emails SET last_sent = NOW() WHERE record_id = " . $task['record_id']);
                echo "Successfully sent: " . $task['task_name'] . "<br>";
            }
        }
    } else {
        // Either it's too early in the day, or we already finished this task.
        echo "Skipping " . $task['task_name'] . " (Already sent or not time yet)<br>";
    }
}