<?php
/**
 * Daily Staff Schedule Cron
 * Run daily at 7:00 AM: 0 7 * * * php /path/to/cron/daily_staff_schedule.php
 */
require __DIR__ . '/../api/bootstrap.php';
require __DIR__ . '/../api/services/WhatsAppService.php';

$pdo = db();
$config = $GLOBALS['CONFIG'];

echo date('Y-m-d H:i:s') . " — Sending daily staff schedules...\n";

// Get on-duty staff with assignments
$stmt = $pdo->query("
    SELECT sp.*, u.name AS staff_name,
        (SELECT COUNT(*) FROM daily_assignments da WHERE da.staff_id = sp.id AND da.assignment_date = CURDATE()) AS task_count
    FROM staff_profiles sp
    JOIN users u ON u.id = sp.user_id
    WHERE sp.is_on_duty = 1 AND sp.whatsapp_enabled = 1 AND sp.phone IS NOT NULL
");

$staff = $stmt->fetchAll(PDO::FETCH_ASSOC);
$sent = 0;

foreach ($staff as $s) {
    // Get assignments for today
    $aStmt = $pdo->prepare("SELECT * FROM daily_assignments WHERE staff_id = ? AND assignment_date = CURDATE() ORDER BY id");
    $aStmt->execute([$s['id']]);
    $assignments = $aStmt->fetchAll(PDO::FETCH_ASSOC);

    if (count($assignments) > 0) {
        $wa = new WhatsAppService($pdo, $config, $s['property_id']);
        $wa->sendDutySchedule($s['phone'], $s['staff_name'], $assignments);
        $sent++;
        echo "  Sent schedule to: {$s['staff_name']} ({$s['task_count']} tasks)\n";
    }
}

echo "Done. Sent {$sent} schedules.\n";
