<?php
/**
 * Patrol System Scheduled Tasks
 * Run this script every minute via cron job
 * 
 * Cron setup:
 * * * * * * php /path/to/ssci/app/scheduled-tasks.php >> /path/to/ssci/logs/cron.log 2>&1
 */

require_once __DIR__ . '/../config/bootstrap.php';

$db = $GLOBALS['db'];
$notification = $GLOBALS['notification'];

// Check if running within correct minute boundaries
$now = new DateTime();
$minute = (int)$now->format('i');

// Run patrol reminders every 50 minutes (10 minutes before hour ends)
if ($minute == 50) {
    sendPatrolReminders();
}

// Run patrol hour reset at the end of each hour (59 minutes)
// This ensures new patrol records are created for next hour
if ($minute == 59) {
    resetPatrols();
}

function sendPatrolReminders()
{
    global $db, $notification;

    if (!$notification || !$db) {
        error_log("Patrol reminder: Missing dependencies");
        return;
    }

    try {
        // Get all incomplete patrols for current hour
        $now = new DateTime();
        $currentHour = $now->format('Y-m-d H');

        $incompletePatrols = $db->fetchAll(
            "SELECT id, post_id, score FROM patrols 
             WHERE patrol_hour = ? AND status != 'Completed' AND reminder_sent = FALSE",
            [$currentHour]
        );

        if (empty($incompletePatrols)) {
            error_log("[" . date('Y-m-d H:i:s') . "] No incomplete patrols found for reminders");
            return;
        }

        error_log("[" . date('Y-m-d H:i:s') . "] Found " . count($incompletePatrols) . " patrols needing reminders");

        foreach ($incompletePatrols as $patrol) {
            $patrol_obj = new \SSCI\Classes\Patrol($db);
            $patrol_obj->sendReminder($patrol['id'], $notification);
        }

        error_log("[" . date('Y-m-d H:i:s') . "] Sent reminders for " . count($incompletePatrols) . " patrols");
    } catch (Exception $e) {
        error_log("Patrol reminder error: " . $e->getMessage());
    }
}

function resetPatrols()
{
    global $db;

    if (!$db) {
        error_log("Patrol reset: Missing database");
        return;
    }

    try {
        // Get all posts
        $posts = $db->fetchAll("SELECT id FROM posts WHERE status = 'Active'");

        if (empty($posts)) {
            error_log("[" . date('Y-m-d H:i:s') . "] No active posts for patrol reset");
            return;
        }

        $patrol_obj = new \SSCI\Classes\Patrol($db);

        foreach ($posts as $post) {
            // This will create a new patrol record for the next hour if it doesn't exist
            $patrol_obj->getOrCreateCurrentPatrol($post['id']);
        }

        error_log("[" . date('Y-m-d H:i:s') . "] Created new patrol records for " . count($posts) . " posts");
    } catch (Exception $e) {
        error_log("Patrol reset error: " . $e->getMessage());
    }
}

// Log task execution
error_log("[" . date('Y-m-d H:i:s') . "] Scheduled tasks executed (minute: " . $minute . ")");
