<?php
/**
 * EduTrack Canteen — Daily Cron Job
 *
 * Schedule (server crontab — Ghana time GMT+0):
 *   0 5 * * * curl -s "https://your-domain.com/canteen/cron.php?token=CANTEEN_CRON_TOKEN" > /dev/null
 *
 * Tasks:
 *   5am daily:  1) Auto-create entitlements for recurring sessions
 *               2) Prime offline prefetch cache
 *               3) Mark yesterday's pending entitlements absent
 *   7am Monday: 4) Trigger AI weekly feeding summary
 *               5) Flag at-risk students (3+ consecutive absences)
 */

// Token guard — CLI or authenticated HTTP
$_is_cli = php_sapi_name() === 'cli';
if (!$_is_cli) {
    $token = $_GET['token'] ?? ($_SERVER['HTTP_X_CRON_TOKEN'] ?? '');
    if (!defined('CANTEEN_CRON_TOKEN') || $token !== CANTEEN_CRON_TOKEN || $token === '') {
        http_response_code(403);
        exit("Forbidden.\n");
    }
}

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/canteen_helpers.php';

if (!canteen_is_active()) {
    exit("Canteen module not active.\n");
}

set_time_limit(300);
$conn  = getDBConnection();
$today = date('Y-m-d');
$log   = [];

function cron_log(string $msg): void {
    global $log;
    $log[] = '[' . date('H:i:s') . '] ' . $msg;
    echo $msg . "\n";
    flush();
}

cron_log("=== Canteen Cron — {$today} ===");

// ── Task 1: Auto-create entitlements for today's scheduled sessions ──────────
cron_log("Task 1: Auto-create entitlements...");

$sess_stmt = $conn->prepare(
    "SELECT id, session_name, classes_enrolled FROM canteen_sessions
     WHERE school_id = 1 AND session_date = ? AND status = 'scheduled'"
);
$sess_stmt->bind_param('s', $today);
$sess_stmt->execute();
$sessions = $sess_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$sess_stmt->close();

$total_created = 0;
$expires       = $today . ' 23:59:59';

$ins = $conn->prepare(
    "INSERT IGNORE INTO canteen_entitlements
        (student_id, session_id, qr_token, qr_token_expires_at, status)
     VALUES (?, ?, ?, ?, 'pending')"
);

foreach ($sessions as $sess) {
    $session_id  = (int) $sess['id'];
    $enrolled_classes = json_decode($sess['classes_enrolled'] ?? '[]', true) ?: [];

    if (empty($enrolled_classes)) {
        // No class filter — enroll all active students
        $stu_res = $conn->query("SELECT id FROM students WHERE status = 'active'");
    } else {
        $placeholders = implode(',', array_fill(0, count($enrolled_classes), '?'));
        $stu_stmt     = $conn->prepare(
            "SELECT id FROM students WHERE status = 'active' AND class IN ({$placeholders})"
        );
        $types = str_repeat('s', count($enrolled_classes));
        $stu_stmt->bind_param($types, ...$enrolled_classes);
        $stu_stmt->execute();
        $stu_res = $stu_stmt->get_result();
    }

    $created = 0;
    while ($stu = $stu_res->fetch_assoc()) {
        $student_id = (int) $stu['id'];
        $token = canteen_generate_session_token($student_id, $session_id);
        $ins->bind_param('iiss', $student_id, $session_id, $token, $expires);
        $ins->execute();
        if ($conn->affected_rows > 0) $created++;
    }

    // Update total_enrolled
    $conn->query(
        "UPDATE canteen_sessions SET total_enrolled =
            (SELECT COUNT(*) FROM canteen_entitlements WHERE session_id = {$session_id})
         WHERE id = {$session_id}"
    );

    $total_created += $created;
    cron_log("  Session '{$sess['session_name']}': {$created} entitlement(s) created.");
}
$ins->close();
cron_log("Task 1 done: {$total_created} total entitlement(s) created.");

// ── Task 2: Prime offline prefetch cache ─────────────────────────────────────
cron_log("Task 2: Priming prefetch cache...");
$prefetch_url = rtrim(BASE_URL, '/') . '/ajax/canteen_prefetch.php';
// Use file_get_contents with a dummy authenticated context is not feasible in cron.
// Instead, directly generate and cache the blob here.
$today_entries = [];
$pre_stmt = $conn->prepare(
    "SELECT ce.qr_token, ce.student_id,
            CONCAT(s.first_name,' ',s.last_name) AS student_name,
            s.class AS class_name,
            s.student_id AS student_code
     FROM canteen_entitlements ce
     JOIN students s ON s.id = ce.student_id
     JOIN canteen_sessions cs ON cs.id = ce.session_id
     WHERE cs.session_date = ? AND cs.status != 'cancelled' AND ce.status = 'pending'"
);
$pre_stmt->bind_param('s', $today);
$pre_stmt->execute();
$today_entries = $pre_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$pre_stmt->close();

if (!empty($today_entries)) {
    $daily_key  = hash_hmac('sha256', 'PREFETCH|' . $today, CANTEEN_SECRET_KEY);
    $blob_json  = json_encode($today_entries, JSON_UNESCAPED_UNICODE);
    $signature  = base64_encode(hash_hmac('sha256', $blob_json, $daily_key, true));
    $cache_data = json_encode([
        'success'      => true,
        'date'         => $today,
        'signature'    => $signature,
        'daily_key'    => $daily_key,
        'entries'      => $today_entries,
        'count'        => count($today_entries),
        'generated_at' => date('H:i:s'),
    ]);
    $cache_file = sys_get_temp_dir() . '/edutrack_canteen_prefetch_' . md5($today) . '.json';
    file_put_contents($cache_file, $cache_data);
    cron_log("Task 2 done: Cached " . count($today_entries) . " entries → " . basename($cache_file));
} else {
    cron_log("Task 2 done: No entries to cache.");
}

// ── Task 3: Mark yesterday's pending entitlements as absent ─────────────────
cron_log("Task 3: Marking absent entitlements...");
$yesterday = date('Y-m-d', strtotime('-1 day'));

$absent_stmt = $conn->prepare(
    "UPDATE canteen_entitlements ce
     JOIN canteen_sessions cs ON cs.id = ce.session_id
     SET ce.status = 'absent'
     WHERE cs.session_date = ?
       AND cs.status IN ('closed','active','scheduled')
       AND ce.status = 'pending'"
);
$absent_stmt->bind_param('s', $yesterday);
$absent_stmt->execute();
$absent_count = $absent_stmt->affected_rows;
$absent_stmt->close();
cron_log("Task 3 done: {$absent_count} entitlement(s) marked absent for {$yesterday}.");

// ── Tasks 4 & 5: Monday only ─────────────────────────────────────────────────
if (date('N') == 1) { // Monday
    cron_log("Monday tasks starting...");

    // Task 4: AI weekly feeding summary
    cron_log("Task 4: Triggering weekly feeding summary...");
    $week_start = date('Y-m-d', strtotime('last monday'));
    $week_end   = date('Y-m-d', strtotime('last friday'));

    if (file_exists(__DIR__ . '/../ai/actions/send_weekly_feeding_summary.php')) {
        require_once __DIR__ . '/../ai/actions/send_weekly_feeding_summary.php';
        $result = action_send_weekly_feeding_summary([
            'week_start' => $week_start,
            'week_end'   => $week_end,
        ]);
        $sent = $result['notifications_sent'] ?? 0;
        cron_log("Task 4 done: {$sent} weekly summary SMS sent for {$week_start} to {$week_end}.");
    } else {
        cron_log("Task 4 skipped: action file not found.");
    }

    // Task 5: Flag at-risk students (3+ consecutive absent sessions)
    cron_log("Task 5: Checking at-risk students...");
    $lookback = date('Y-m-d', strtotime('-30 days'));

    $risk_stmt = $conn->prepare(
        "SELECT ce.student_id,
                CONCAT(s.first_name,' ',s.last_name) AS student_name,
                s.class,
                SUM(ce.status = 'absent') AS total_absent,
                COUNT(ce.id) AS total_sessions
         FROM canteen_entitlements ce
         JOIN canteen_sessions cs ON cs.id = ce.session_id
         JOIN students s ON s.id = ce.student_id
         WHERE cs.session_date >= ? AND cs.status != 'cancelled'
         GROUP BY ce.student_id
         HAVING total_absent >= 3
         ORDER BY total_absent DESC"
    );
    $risk_stmt->bind_param('s', $lookback);
    $risk_stmt->execute();
    $at_risk = $risk_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $risk_stmt->close();

    if (!empty($at_risk)) {
        $names = implode(', ', array_slice(array_column($at_risk, 'student_name'), 0, 5));
        cron_log("Task 5: " . count($at_risk) . " at-risk student(s): {$names}" . (count($at_risk) > 5 ? '...' : ''));
        logActivity($conn, 0, 'canteen_cron_at_risk',
            count($at_risk) . ' students with 3+ consecutive absences in last 30 days');
    } else {
        cron_log("Task 5 done: No at-risk students.");
    }
}

logActivity($conn, 0, 'canteen_cron_run', "Cron completed — {$total_created} entitlements, {$absent_count} marked absent");
$conn->close();

cron_log("=== Cron complete ===");
