<?php
session_start();
require_once '../includes/config.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'controller') {
    header("Location: ../auth/login.php");
    exit;
}

$controller_id = $_SESSION['user_id'];
$username = $_SESSION['username'] ?? 'Controller';
$today = date('Y-m-d');

try {
    // Fetch attendance with officer name and site (if available)
    $stmt = $pdo->prepare("
        SELECT a.*, u.username, s.site_name
        FROM attendance a
        JOIN users u ON a.officer_id = u.id
        LEFT JOIN sites s ON u.site_id = s.id
        WHERE a.date = :today
        ORDER BY a.time_in DESC
    ");
    $stmt->execute([':today' => $today]);
    $records = $stmt->fetchAll();

    // Controller Attendance Today
    $stmt = $pdo->prepare("SELECT * FROM controller_attendance WHERE controller_id = :controller_id AND date = :today");
    $stmt->execute([':controller_id' => $controller_id, ':today' => $today]);
    $myAttendance = $stmt->fetch();

    // Metrics
    $totalToday = $pdo->query("SELECT COUNT(*) FROM attendance WHERE date = CURDATE()")->fetchColumn();
    $totalOfficers = $pdo->query("SELECT COUNT(*) FROM users WHERE role = 'officer'")->fetchColumn();
    $alerts = $pdo->query("SELECT COUNT(*) FROM attendance WHERE TIMESTAMPDIFF(HOUR, time_in, time_out) > 12 AND date = CURDATE()")->fetchColumn();
    $myMonthCount = $pdo->prepare("SELECT COUNT(*) FROM controller_attendance WHERE controller_id = ? AND date >= CURDATE() - INTERVAL 30 DAY");
    $myMonthCount->execute([$controller_id]);
    $monthlyTotal = $myMonthCount->fetchColumn();

    // Controller Weekly Trend
    $trendStmt = $pdo->prepare("SELECT date, time_in FROM controller_attendance WHERE controller_id = ? AND date >= CURDATE() - INTERVAL 7 DAY ORDER BY date ASC");
    $trendStmt->execute([$controller_id]);
    $trend = $trendStmt->fetchAll();
    $trendLabels = json_encode(array_column($trend, 'date'));
    $trendCounts = json_encode(array_map(fn($r) => $r['time_in'] ? 1 : 0, $trend));

    // Weekly Attendance Summary (Last 7 Days)
    $weekStmt = $pdo->prepare("
        SELECT date, time_in, time_out 
        FROM controller_attendance 
        WHERE controller_id = :controller_id 
        AND date >= CURDATE() - INTERVAL 7 DAY 
        ORDER BY date DESC
    ");
    $weekStmt->execute([':controller_id' => $controller_id]);
    $weekData = $weekStmt->fetchAll();

    // Officer Alerts (Attendance > 12 hrs)
    $alertStmt = $pdo->prepare("
        SELECT a.*, u.username 
        FROM attendance a 
        JOIN users u ON a.officer_id = u.id 
        WHERE DATE(a.date) = :today  
        AND a.time_in IS NOT NULL 
        AND a.time_out IS NOT NULL
    ");
    $alertStmt->execute([':today' => $today]);
    $officerAlerts = $alertStmt->fetchAll();

} catch (PDOException $e) {
    die("Database error: " . htmlspecialchars($e->getMessage()));
}
?>
