<?php
/**
 * Guards Controls Management Page
 * SSCI Office Platform - Zone Controllers record guard controls with QR scanning and geolocation
 */

$auth = $GLOBALS['auth'];
$db = $GLOBALS['db'];
$pageTitle = trans('guard_controls') ?? 'Guard Controls';

// Get current user with role and zone info
$user = $db->fetch("SELECT u.id, u.role, s.zone FROM users u LEFT JOIN staff s ON u.id = s.user_id WHERE u.id = ?", [$_SESSION['user_id'] ?? 0]);

if (!$user) {
    header('Location: ?page=dashboard');
    exit();
}

// Allow controllers, managers, and admins
$isController = $user['role'] === 'controller';
$isManagerOrAdmin = in_array($user['role'], ['manager', 'admin']);

if (!$isController && !$isManagerOrAdmin) {
    header('Location: ?page=dashboard');
    exit();
}

$controllerZone = $user['zone'] ?? null;

require_once __DIR__ . '/../../layouts/header.php';

$action = $_GET['action'] ?? 'list';

// Get posts: controllers see only their zone, managers/admins see all
if ($isController) {
    $posts = $db->fetchAll(
        "SELECT id, name, zone FROM posts WHERE zone = ? AND status = 'Active' ORDER BY name",
        [$controllerZone]
    );
    $postsQuery = "WHERE p.zone = ?";
    $postsParams = [$controllerZone];
} else {
    $posts = $db->fetchAll(
        "SELECT id, name, zone FROM posts WHERE status = 'Active' ORDER BY zone, name"
    );
    $postsQuery = "";
    $postsParams = [];
}

// Get recent controls: controllers see only their controls, managers/admins see all
if ($isController) {
    $recentControls = $db->fetchAll(
        "SELECT gc.*, p.name as post_name, u.name as guard_name, s.staff_id 
         FROM guards_controls gc
         JOIN posts p ON gc.post_id = p.id
         JOIN users u ON gc.guard_id = u.id
         LEFT JOIN staff s ON u.id = s.user_id
         WHERE p.zone = ? AND gc.controller_id = ?
         ORDER BY gc.control_datetime DESC
         LIMIT 20",
        [$controllerZone, $_SESSION['user_id'] ?? 1]
    );
} else {
    $recentControls = $db->fetchAll(
        "SELECT gc.*, p.name as post_name, u.name as guard_name, s.staff_id, cu.name as controller_name
         FROM guards_controls gc
         JOIN posts p ON gc.post_id = p.id
         JOIN users u ON gc.guard_id = u.id
         LEFT JOIN staff s ON u.id = s.user_id
         LEFT JOIN users cu ON gc.controller_id = cu.id
         ORDER BY gc.control_datetime DESC
         LIMIT 20"
    );
}
?>

<div class="container mx-auto px-4 py-8 max-w-7xl">
    <!-- Page Header -->
    <div class="mb-8">
        <h1 class="text-4xl font-bold text-gray-800 mb-2">
            <i class="fas fa-check-double text-blue-600 mr-3"></i><?php echo $pageTitle; ?>
        </h1>
        <p class="text-gray-600">
            <?php if ($isController): ?>
                Record guard controls for posts in your zone 
                <span class="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-sm font-semibold ml-2">
                    Zone: <?php echo htmlspecialchars($controllerZone); ?>
                </span>
            <?php else: ?>
                View and manage guard controls across all zones and posts
                <span class="px-3 py-1 bg-green-100 text-green-700 rounded-full text-sm font-semibold ml-2">
                    <?php echo ucfirst($user['role']); ?> - Full Access
                </span>
            <?php endif; ?>
        </p>
    </div>

    <!-- Main Tabs -->
    <div class="bg-white rounded-lg shadow mb-8">
        <div class="flex border-b border-gray-200">
            <button data-tab="record" class="px-6 py-4 font-semibold text-gray-600 hover:text-gray-800 focus:outline-none tab-button" onclick="switchControlTab('record')">
                <i class="fas fa-plus-circle mr-2"></i>Record Control
            </button>
            <button data-tab="history" class="px-6 py-4 font-semibold text-blue-600 border-b-2 border-blue-600 focus:outline-none tab-button" onclick="switchControlTab('history')">
                <i class="fas fa-history mr-2"></i>Control History
            </button>
        </div>

        <!-- Record Control Tab -->
        <div id="recordTab" class="p-8 hidden">
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                <!-- QR Scanner & Geolocation Panel -->
                <div class="lg:col-span-1">
                    <div class="space-y-6">
                        <!-- Post Selection -->
                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">
                                <i class="fas fa-location-dot text-blue-600 mr-2"></i>Select Post
                            </label>
                            <select id="postSelect" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200" onchange="updateGuardList()">
                                <option value="">Choose a post...</option>
                                <?php foreach ($posts as $post): ?>
                                    <option value="<?php echo $post['id']; ?>"><?php echo htmlspecialchars($post['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <!-- Guard Selection -->
                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">
                                <i class="fas fa-user-shield text-green-600 mr-2"></i>Select Guard (Optional)
                            </label>
                            <select id="guardSelect" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-green-500 focus:ring-2 focus:ring-green-200" onchange="setGuardFromSelector()">
                                <option value="">Or scan QR code below...</option>
                            </select>
                            <p class="text-xs text-gray-600 mt-1">Select a guard from the list or scan their QR code</p>
                        </div>

                        <!-- QR Scanner Section -->
                        <div class="bg-gradient-to-br from-blue-50 to-indigo-50 rounded-lg p-6 border-2 border-blue-200">
                            <h3 class="text-lg font-bold text-gray-800 mb-4">
                                <i class="fas fa-qrcode text-blue-600 mr-2"></i>Scan Guard QR Code
                            </h3>
                            
                            <div id="qrScanner" style="width: 100%; height: 300px; background: #000; border-radius: 8px; display: flex; align-items: center; justify-content: center; color: white; position: relative;">
                                <div id="scannerMessage" class="text-center">
                                    <p class="text-lg">Ready to scan</p>
                                    <p class="text-sm opacity-75">Click to start camera</p>
                                </div>
                                <video id="qrVideo" style="width: 100%; height: 100%; display: none; border-radius: 8px; object-fit: cover;"></video>
                            </div>

                            <button type="button" id="startScannerBtn" onclick="startQRScanner()" class="w-full mt-4 bg-blue-600 text-white px-4 py-3 rounded-lg hover:bg-blue-700 transition font-semibold flex items-center justify-center">
                                <i class="fas fa-camera mr-2"></i>Start Camera Scan
                            </button>
                            <button type="button" id="stopScannerBtn" onclick="stopQRScanner()" class="w-full mt-2 bg-red-600 text-white px-4 py-3 rounded-lg hover:bg-red-700 transition font-semibold flex items-center justify-center hidden">
                                <i class="fas fa-stop-circle mr-2"></i>Stop Camera
                            </button>
                        </div>

                        <!-- Manual Guard ID Entry -->
                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">
                                <i class="fas fa-user text-blue-600 mr-2"></i>Or Enter Guard ID Manually
                            </label>
                            <input type="text" id="guardIdInput" placeholder="Guard ID or Staff Number" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200">
                        </div>

                        <!-- Geolocation Section -->
                        <div class="bg-gradient-to-br from-green-50 to-emerald-50 rounded-lg p-6 border-2 border-green-200">
                            <h3 class="text-lg font-bold text-gray-800 mb-4">
                                <i class="fas fa-location-crosshairs text-green-600 mr-2"></i>Geolocation
                            </h3>

                            <div id="geoStatus" class="text-sm text-gray-600 mb-4">
                                <p class="flex items-center">
                                    <i class="fas fa-circle-notch fa-spin text-blue-600 mr-2"></i>Waiting to capture location...
                                </p>
                            </div>

                            <div id="coordDisplay" class="hidden space-y-2">
                                <div class="bg-white p-3 rounded border border-green-200">
                                    <p class="text-xs text-gray-600">Latitude</p>
                                    <p class="font-semibold text-gray-800" id="latDisplay">--</p>
                                </div>
                                <div class="bg-white p-3 rounded border border-green-200">
                                    <p class="text-xs text-gray-600">Longitude</p>
                                    <p class="font-semibold text-gray-800" id="lngDisplay">--</p>
                                </div>
                                <div class="bg-white p-3 rounded border border-green-200">
                                    <p class="text-xs text-gray-600">Accuracy</p>
                                    <p class="font-semibold text-gray-800" id="accuracyDisplay">--</p>
                                </div>
                            </div>

                            <div class="flex gap-2">
                                <button type="button" id="getLocationBtn" onclick="getGeolocation()" class="flex-1 bg-green-600 text-white px-4 py-3 rounded-lg hover:bg-green-700 transition font-semibold flex items-center justify-center">
                                    <i class="fas fa-map-marker-alt mr-2"></i>Get Location
                                </button>
                                <button type="button" onclick="getGeolocation()" class="flex-1 bg-blue-600 text-white px-4 py-3 rounded-lg hover:bg-blue-700 transition font-semibold flex items-center justify-center" title="Refresh location data">
                                    <i class="fas fa-redo-alt mr-2"></i>Refresh
                                </button>
                            </div>
                        </div>

                        <!-- Control Timestamp -->
                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">
                                <i class="fas fa-clock text-blue-600 mr-2"></i>Control Date & Time
                            </label>
                            <input type="datetime-local" id="controlDatetime" readonly class="w-full px-4 py-3 border border-gray-300 rounded-lg bg-gray-50 text-gray-700" title="Auto-filled with current date and time">
                        </div>
                    </div>
                </div>

                <!-- Evaluation Form -->
                <div class="lg:col-span-2">
                    <form onsubmit="submitControl(event)" class="space-y-6">
                        <h3 class="text-2xl font-bold text-gray-800">
                            <i class="fas fa-clipboard-list text-blue-600 mr-2"></i>Guard Evaluation
                        </h3>

                        <!-- Evaluation Criteria (1-5 scale) - Modern Card Style -->
                        <div class="space-y-4">
                            <div class="bg-gradient-to-r from-blue-50 to-indigo-50 p-4 rounded-lg border border-blue-200">
                                <label class="block text-gray-700 font-bold mb-3">Attendance & Punctuality</label>
                                <div class="grid grid-cols-5 gap-2">
                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                        <label class="flex items-center justify-center cursor-pointer group">
                                            <input type="radio" name="attendance_punctuality" value="<?php echo $i; ?>" required class="hidden peer score-input">
                                            <span class="px-3 py-2 border-2 border-gray-300 rounded-lg text-center font-bold transition-all group-hover:border-blue-400 peer-checked:bg-blue-500 peer-checked:text-white peer-checked:border-blue-500"><?php echo $i; ?></span>
                                        </label>
                                    <?php endfor; ?>
                                </div>
                                <p class="text-xs text-gray-600 mt-2">1 = Poor, 5 = Excellent</p>
                            </div>

                            <div class="bg-gradient-to-r from-green-50 to-emerald-50 p-4 rounded-lg border border-green-200">
                                <label class="block text-gray-700 font-bold mb-3">Uniform & Presentation</label>
                                <div class="grid grid-cols-5 gap-2">
                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                        <label class="flex items-center justify-center cursor-pointer group">
                                            <input type="radio" name="uniform_presentation" value="<?php echo $i; ?>" required class="hidden peer score-input">
                                            <span class="px-3 py-2 border-2 border-gray-300 rounded-lg text-center font-bold transition-all group-hover:border-green-400 peer-checked:bg-green-500 peer-checked:text-white peer-checked:border-green-500"><?php echo $i; ?></span>
                                        </label>
                                    <?php endfor; ?>
                                </div>
                                <p class="text-xs text-gray-600 mt-2">1 = Poor, 5 = Excellent</p>
                            </div>

                            <div class="bg-gradient-to-r from-purple-50 to-pink-50 p-4 rounded-lg border border-purple-200">
                                <label class="block text-gray-700 font-bold mb-3">Patrol & Reporting Discipline</label>
                                <div class="grid grid-cols-5 gap-2">
                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                        <label class="flex items-center justify-center cursor-pointer group">
                                            <input type="radio" name="patrol_reporting_discipline" value="<?php echo $i; ?>" required class="hidden peer score-input">
                                            <span class="px-3 py-2 border-2 border-gray-300 rounded-lg text-center font-bold transition-all group-hover:border-purple-400 peer-checked:bg-purple-500 peer-checked:text-white peer-checked:border-purple-500"><?php echo $i; ?></span>
                                        </label>
                                    <?php endfor; ?>
                                </div>
                                <p class="text-xs text-gray-600 mt-2">1 = Poor, 5 = Excellent</p>
                            </div>

                            <div class="bg-gradient-to-r from-orange-50 to-red-50 p-4 rounded-lg border border-orange-200">
                                <label class="block text-gray-700 font-bold mb-3">Client Feedback</label>
                                <div class="grid grid-cols-5 gap-2">
                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                        <label class="flex items-center justify-center cursor-pointer group">
                                            <input type="radio" name="client_feedback" value="<?php echo $i; ?>" required class="hidden peer score-input">
                                            <span class="px-3 py-2 border-2 border-gray-300 rounded-lg text-center font-bold transition-all group-hover:border-orange-400 peer-checked:bg-orange-500 peer-checked:text-white peer-checked:border-orange-500"><?php echo $i; ?></span>
                                        </label>
                                    <?php endfor; ?>
                                </div>
                                <p class="text-xs text-gray-600 mt-2">1 = Poor, 5 = Excellent</p>
                            </div>

                            <div class="bg-gradient-to-r from-indigo-50 to-blue-50 p-4 rounded-lg border-2 border-indigo-300">
                                <label class="block text-gray-700 font-bold mb-3">General Evaluation</label>
                                <div class="grid grid-cols-5 gap-2">
                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                        <label class="flex items-center justify-center cursor-pointer group">
                                            <input type="radio" name="controller_general_evaluation" value="<?php echo $i; ?>" required class="hidden peer score-input">
                                            <span class="px-3 py-2 border-2 border-gray-300 rounded-lg text-center font-bold transition-all group-hover:border-indigo-400 peer-checked:bg-indigo-600 peer-checked:text-white peer-checked:border-indigo-600"><?php echo $i; ?></span>
                                        </label>
                                    <?php endfor; ?>
                                </div>
                                <p class="text-xs text-gray-600 mt-2">1 = Poor, 5 = Excellent</p>
                            </div>

                            <!-- Overall Score Display -->
                            <div class="bg-gradient-to-r from-slate-100 to-slate-50 p-4 rounded-lg border-2 border-slate-300">
                                <div class="flex items-center justify-between">
                                    <label class="text-gray-700 font-bold text-lg">Overall Score</label>
                                    <div class="text-right">
                                        <span class="text-3xl font-bold text-blue-600" id="overallScore">-</span>
                                        <span class="text-sm text-gray-600 ml-2">%</span>
                                    </div>
                                </div>
                                <div class="mt-2 h-2 bg-gray-300 rounded-full overflow-hidden">
                                    <div id="overallScoreBar" class="h-full bg-gradient-to-r from-red-500 via-yellow-500 to-green-500 transition-all" style="width: 0%"></div>
                                </div>
                            </div>
                        </div>

                        <!-- Photo Capture -->
                        <div class="border-t-2 border-gray-200 pt-6">
                            <label class="block text-gray-700 font-semibold mb-2">
                                <i class="fas fa-camera text-blue-600 mr-2"></i>Capture Photo (Optional)
                            </label>
                            <p class="text-sm text-gray-600 mb-4">Low resolution photo of the guard at the post for verification</p>

                            <div id="photoPreview" style="width: 100%; max-width: 300px; height: 200px; background: #f3f4f6; border: 2px dashed #d1d5db; border-radius: 8px; display: flex; align-items: center; justify-content: center; margin-bottom: 12px; position: relative;">
                                <div id="photoPlaceholder" class="text-center text-gray-500">
                                    <i class="fas fa-image text-4xl mb-2 opacity-50"></i>
                                    <p class="text-sm">No photo captured</p>
                                </div>
                                <canvas id="photoCanvas" style="display: none; width: 100%; height: 100%; border-radius: 6px;"></canvas>
                                <img id="photoImage" style="display: none; width: 100%; height: 100%; object-fit: cover; border-radius: 6px;">
                            </div>

                            <div class="flex gap-3">
                                <button type="button" id="capturePhotoBtn" onclick="capturePhoto()" class="flex-1 bg-blue-600 text-white px-4 py-3 rounded-lg hover:bg-blue-700 transition font-semibold flex items-center justify-center">
                                    <i class="fas fa-camera mr-2"></i>Capture Photo
                                </button>
                                <button type="button" id="clearPhotoBtn" onclick="clearPhoto()" class="flex-1 bg-red-600 text-white px-4 py-3 rounded-lg hover:bg-red-700 transition font-semibold flex items-center justify-center hidden">
                                    <i class="fas fa-trash mr-2"></i>Clear Photo
                                </button>
                            </div>

                            <video id="photoVideo" style="display: none; width: 100%; max-width: 300px; border-radius: 8px; margin-top: 12px;"></video>
                        </div>

                        <!-- Notes -->
                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">
                                <i class="fas fa-note-sticky text-blue-600 mr-2"></i>Control Notes
                            </label>
                            <textarea id="controlNotes" rows="4" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200" placeholder="Any observations or issues noted during control..."></textarea>
                        </div>

                        <!-- Submit Button -->
                        <div class="flex gap-3">
                            <button type="submit" class="flex-1 bg-green-600 text-white px-6 py-3 rounded-lg hover:bg-green-700 transition font-semibold flex items-center justify-center">
                                <i class="fas fa-check-circle mr-2"></i>Submit Control
                            </button>
                            <button type="button" onclick="resetForm()" class="flex-1 bg-gray-600 text-white px-6 py-3 rounded-lg hover:bg-gray-700 transition font-semibold">
                                <i class="fas fa-redo mr-2"></i>Reset
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- History Tab -->
        <div id="historyTab" class="p-8 ">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-2xl font-bold text-gray-800">
                    <i class="fas fa-history text-blue-600 mr-2"></i>Recent Controls
                </h2>
                <button type="button" onclick="switchControlTab('record')" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg font-semibold flex items-center gap-2 transition">
                    <i class="fas fa-plus-circle"></i>Start New Control
                </button>
            </div>

            <!-- Statistics Cards -->
            <?php 
            if (!empty($recentControls)):
                // Calculate statistics
                $totalControls = count($recentControls);
                $avgAttendance = 0;
                $avgUniform = 0;
                $avgPatrol = 0;
                $avgClient = 0;
                $avgGeneral = 0;
                
                foreach ($recentControls as $control) {
                    $avgAttendance += $control['attendance_punctuality'];
                    $avgUniform += $control['uniform_presentation'];
                    $avgPatrol += $control['patrol_reporting_discipline'];
                    $avgClient += $control['client_feedback'];
                    $avgGeneral += $control['controller_general_evaluation'];
                }
                
                $avgAttendance = round($avgAttendance / $totalControls, 1);
                $avgUniform = round($avgUniform / $totalControls, 1);
                $avgPatrol = round($avgPatrol / $totalControls, 1);
                $avgClient = round($avgClient / $totalControls, 1);
                $avgGeneral = round($avgGeneral / $totalControls, 1);
                $overallAvg = round(($avgAttendance + $avgUniform + $avgPatrol + $avgClient + $avgGeneral) / 5, 1);
            ?>
            <div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-4 mb-8">
                <div class="bg-gradient-to-br from-blue-50 to-blue-100 p-4 rounded-lg border border-blue-200 shadow">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-semibold">Total Controls</p>
                            <p class="text-3xl font-bold text-blue-600"><?php echo $totalControls; ?></p>
                        </div>
                        <i class="fas fa-chart-bar text-4xl text-blue-200"></i>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-green-50 to-green-100 p-4 rounded-lg border border-green-200 shadow">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-semibold">Avg. Attendance</p>
                            <p class="text-3xl font-bold text-green-600"><?php echo $avgAttendance; ?>/5</p>
                        </div>
                        <i class="fas fa-user-check text-4xl text-green-200"></i>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-purple-50 to-purple-100 p-4 rounded-lg border border-purple-200 shadow">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-semibold">Avg. Uniform</p>
                            <p class="text-3xl font-bold text-purple-600"><?php echo $avgUniform; ?>/5</p>
                        </div>
                        <i class="fas fa-shirt text-4xl text-purple-200"></i>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-orange-50 to-orange-100 p-4 rounded-lg border border-orange-200 shadow">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-semibold">Avg. Patrol</p>
                            <p class="text-3xl font-bold text-orange-600"><?php echo $avgPatrol; ?>/5</p>
                        </div>
                        <i class="fas fa-shield-alt text-4xl text-orange-200"></i>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-red-50 to-red-100 p-4 rounded-lg border border-red-200 shadow">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-semibold">Overall Score</p>
                            <p class="text-3xl font-bold text-red-600"><?php echo round(($overallAvg / 5) * 100); ?>%</p>
                        </div>
                        <i class="fas fa-star text-4xl text-red-200"></i>
                    </div>
                </div>
            </div>

            <!-- Chart and Report Section -->
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-8">
                <!-- Performance Trend Chart -->
                <div class="lg:col-span-2 bg-white p-6 rounded-lg border border-gray-200 shadow">
                    <h3 class="text-lg font-bold text-gray-800 mb-4">
                        <i class="fas fa-chart-line text-blue-600 mr-2"></i>Performance Trend
                    </h3>
                    <div style="position: relative; height: 300px; width: 100%;">
                        <canvas id="performanceChart"></canvas>
                    </div>
                </div>

                <!-- Report Generation -->
                <div class="bg-gradient-to-br from-indigo-50 to-purple-50 p-6 rounded-lg border border-indigo-200 shadow">
                    <h3 class="text-lg font-bold text-gray-800 mb-4">
                        <i class="fas fa-file-pdf text-purple-600 mr-2"></i>Generate Report
                    </h3>
                    <div class="space-y-3">
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-1">From Date</label>
                            <input type="date" id="reportFromDate" class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-1">To Date</label>
                            <input type="date" id="reportToDate" class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                        </div>
                        <button type="button" onclick="generateControlReport()" class="w-full bg-purple-600 hover:bg-purple-700 text-white px-4 py-3 rounded-lg font-semibold transition flex items-center justify-center gap-2">
                            <i class="fas fa-download"></i>Generate Report
                        </button>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <?php if (empty($recentControls)): ?>
                <div class="text-center py-12 text-gray-500">
                    <i class="fas fa-inbox text-4xl mb-4 opacity-50"></i>
                    <p>No controls recorded yet</p>
                </div>
            <?php else: ?>
                <div class="overflow-x-auto">
                    <table class="w-full border border-gray-300 rounded-lg overflow-hidden">
                        <thead class="bg-gray-100">
                            <tr>
                                <th class="border border-gray-300 px-4 py-3 text-left font-semibold text-gray-700">Date & Time</th>
                                <th class="border border-gray-300 px-4 py-3 text-left font-semibold text-gray-700">Post</th>
                                <th class="border border-gray-300 px-4 py-3 text-left font-semibold text-gray-700">Guard</th>
                                <?php if (!$isController): ?>
                                    <th class="border border-gray-300 px-4 py-3 text-left font-semibold text-gray-700">Controller</th>
                                <?php endif; ?>
                                <th class="border border-gray-300 px-4 py-3 text-center font-semibold text-gray-700">Attendance</th>
                                <th class="border border-gray-300 px-4 py-3 text-center font-semibold text-gray-700">Uniform</th>
                                <th class="border border-gray-300 px-4 py-3 text-center font-semibold text-gray-700">Patrol</th>
                                <th class="border border-gray-300 px-4 py-3 text-center font-semibold text-gray-700">Client</th>
                                <th class="border border-gray-300 px-4 py-3 text-center font-semibold text-gray-700">General</th>
                                <th class="border border-gray-300 px-4 py-3 text-center font-semibold text-gray-700">Status</th>
                                <th class="border border-gray-300 px-4 py-3 text-center font-semibold text-gray-700">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recentControls as $control): ?>
                                <tr class="hover:bg-blue-50 transition">
                                    <td class="border border-gray-300 px-4 py-3"><?php echo date('M d, H:i', strtotime($control['control_datetime'])); ?></td>
                                    <td class="border border-gray-300 px-4 py-3 font-semibold"><?php echo htmlspecialchars($control['post_name']); ?></td>
                                    <td class="border border-gray-300 px-4 py-3">
                                        <?php echo htmlspecialchars($control['guard_name']); ?>
                                        <span class="text-xs text-gray-600 block"><?php echo $control['staff_id'] ?? 'N/A'; ?></span>
                                    </td>
                                    <?php if (!$isController): ?>
                                        <td class="border border-gray-300 px-4 py-3 text-sm">
                                            <?php echo htmlspecialchars($control['controller_name'] ?? 'System'); ?>
                                        </td>
                                    <?php endif; ?>
                                    <td class="border border-gray-300 px-4 py-3 text-center">
                                        <span class="inline-flex items-center justify-center w-8 h-8 rounded-full font-semibold <?php echo $control['attendance_punctuality'] >= 4 ? 'bg-green-100 text-green-700' : ($control['attendance_punctuality'] >= 3 ? 'bg-yellow-100 text-yellow-700' : 'bg-red-100 text-red-700'); ?>">
                                            <?php echo $control['attendance_punctuality']; ?>
                                        </span>
                                    </td>
                                    <td class="border border-gray-300 px-4 py-3 text-center">
                                        <span class="inline-flex items-center justify-center w-8 h-8 rounded-full font-semibold <?php echo $control['uniform_presentation'] >= 4 ? 'bg-green-100 text-green-700' : ($control['uniform_presentation'] >= 3 ? 'bg-yellow-100 text-yellow-700' : 'bg-red-100 text-red-700'); ?>">
                                            <?php echo $control['uniform_presentation']; ?>
                                        </span>
                                    </td>
                                    <td class="border border-gray-300 px-4 py-3 text-center">
                                        <span class="inline-flex items-center justify-center w-8 h-8 rounded-full font-semibold <?php echo $control['patrol_reporting_discipline'] >= 4 ? 'bg-green-100 text-green-700' : ($control['patrol_reporting_discipline'] >= 3 ? 'bg-yellow-100 text-yellow-700' : 'bg-red-100 text-red-700'); ?>">
                                            <?php echo $control['patrol_reporting_discipline']; ?>
                                        </span>
                                    </td>
                                    <td class="border border-gray-300 px-4 py-3 text-center">
                                        <span class="inline-flex items-center justify-center w-8 h-8 rounded-full font-semibold <?php echo $control['client_feedback'] >= 4 ? 'bg-green-100 text-green-700' : ($control['client_feedback'] >= 3 ? 'bg-yellow-100 text-yellow-700' : 'bg-red-100 text-red-700'); ?>">
                                            <?php echo $control['client_feedback']; ?>
                                        </span>
                                    </td>
                                    <td class="border border-gray-300 px-4 py-3 text-center">
                                        <span class="inline-flex items-center justify-center w-8 h-8 rounded-full font-semibold <?php echo $control['controller_general_evaluation'] >= 4 ? 'bg-green-100 text-green-700' : ($control['controller_general_evaluation'] >= 3 ? 'bg-yellow-100 text-yellow-700' : 'bg-red-100 text-red-700'); ?>">
                                            <?php echo $control['controller_general_evaluation']; ?>
                                        </span>
                                    </td>
                                    <td class="border border-gray-300 px-4 py-3 text-center">
                                        <span class="px-3 py-1 rounded-full text-xs font-semibold <?php echo $control['status'] === 'Completed' ? 'bg-green-100 text-green-700' : 'bg-blue-100 text-blue-700'; ?>">
                                            <?php echo ucfirst(strtolower($control['status'])); ?>
                                        </span>
                                    </td>
                                    <td class="border border-gray-300 px-4 py-3 text-center space-x-2">
                                        <button type="button" onclick="editControl(<?php echo $control['id']; ?>)" class="bg-blue-500 hover:bg-blue-600 text-white px-3 py-1 rounded text-xs font-semibold transition" title="Edit control">
                                            <i class="fas fa-edit"></i> Edit
                                        </button>
                                        <button type="button" onclick="deleteControl(<?php echo $control['id']; ?>)" class="bg-red-500 hover:bg-red-600 text-white px-3 py-1 rounded text-xs font-semibold transition" title="Delete control">
                                            <i class="fas fa-trash"></i> Delete
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Pass chart data to JavaScript -->
<script>
    // Prepare chart data from recent controls
    window.performanceChartData = {
        dates: [<?php 
            if (!empty($recentControls)) {
                $dates = array_map(function($c) { 
                    return '"' . date('M d', strtotime($c['control_datetime'])) . '"'; 
                }, array_reverse($recentControls));
                echo implode(',', $dates);
            }
        ?>],
        attendance: [<?php 
            if (!empty($recentControls)) {
                $values = array_map(function($c) { return $c['attendance_punctuality']; }, array_reverse($recentControls));
                echo implode(',', $values);
            }
        ?>],
        uniform: [<?php 
            if (!empty($recentControls)) {
                $values = array_map(function($c) { return $c['uniform_presentation']; }, array_reverse($recentControls));
                echo implode(',', $values);
            }
        ?>],
        patrol: [<?php 
            if (!empty($recentControls)) {
                $values = array_map(function($c) { return $c['patrol_reporting_discipline']; }, array_reverse($recentControls));
                echo implode(',', $values);
            }
        ?>],
        client: [<?php 
            if (!empty($recentControls)) {
                $values = array_map(function($c) { return $c['client_feedback']; }, array_reverse($recentControls));
                echo implode(',', $values);
            }
        ?>],
        general: [<?php 
            if (!empty($recentControls)) {
                $values = array_map(function($c) { return $c['controller_general_evaluation']; }, array_reverse($recentControls));
                echo implode(',', $values);
            }
        ?>]
    };
</script>

<!-- Hidden file input for photo upload -->
<input type="file" id="photoInput" style="display: none;" accept="image/*" capture="environment" onchange="handlePhotoUpload(event)">

<script>
    const API_BASE_URL = '/ssci/public/api.php';
    let currentLatitude = null;
    let currentLongitude = null;
    let capturedPhotoBase64 = null;
    let photoStream = null;
    let editingControlId = null;  // Track if we're editing a control

    // Set current datetime
    const now = new Date();
    now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
    document.getElementById('controlDatetime').value = now.toISOString().slice(0, 16);

    // Calculate overall score in real-time
    function calculateOverallScore() {
        const scores = [];
        document.querySelectorAll('.score-input:checked').forEach(input => {
            scores.push(parseInt(input.value));
        });

        if (scores.length > 0) {
            const average = scores.reduce((a, b) => a + b, 0) / 5;
            const percentage = Math.round((average / 5) * 100);
            
            document.getElementById('overallScore').textContent = percentage;
            document.getElementById('overallScoreBar').style.width = percentage + '%';
            
            // Update bar color based on score
            const bar = document.getElementById('overallScoreBar');
            if (percentage >= 80) {
                bar.className = 'h-full bg-green-500 transition-all';
            } else if (percentage >= 60) {
                bar.className = 'h-full bg-yellow-500 transition-all';
            } else {
                bar.className = 'h-full bg-red-500 transition-all';
            }
        } else {
            document.getElementById('overallScore').textContent = '-';
            document.getElementById('overallScoreBar').style.width = '0%';
        }
    }

    // Load guards for selected post
    function updateGuardList() {
        const postId = document.getElementById('postSelect').value;
        const guardSelect = document.getElementById('guardSelect');
        
        if (!postId) {
            guardSelect.innerHTML = '<option value="">Or scan QR code below...</option>';
            return;
        }

        // Fetch guards for this post
        fetch(`${API_BASE_URL}?endpoint=guards/get-by-post&post_id=${postId}`)
            .then(res => res.json())
            .then(data => {
                if (data.success && data.guards && data.guards.length > 0) {
                    guardSelect.innerHTML = '<option value="">Or scan QR code below...</option>';
                    data.guards.forEach(guard => {
                        const option = document.createElement('option');
                        option.value = guard.id;
                        option.textContent = guard.name + (guard.staff_id ? ' (' + guard.staff_id + ')' : '');
                        guardSelect.appendChild(option);
                    });
                } else {
                    guardSelect.innerHTML = '<option value="">No guards assigned to this post</option>';
                }
            })
            .catch(err => {
                console.error('Error loading guards:', err);
                guardSelect.innerHTML = '<option value="">Error loading guards</option>';
            });
    }

    // Set guard ID from selector dropdown
    function setGuardFromSelector() {
        const guardSelect = document.getElementById('guardSelect');
        const guardId = guardSelect.value;
        if (guardId) {
            document.getElementById('guardIdInput').value = guardId;
        }
    }

    // Add event listeners to all score inputs
    document.addEventListener('DOMContentLoaded', function() {
        // Add score calculation listeners
        document.querySelectorAll('.score-input').forEach(input => {
            input.addEventListener('change', calculateOverallScore);
        });
        
        // Auto-load geolocation when page loads
        setTimeout(() => {
            getGeolocation();
        }, 500);
    });

    function switchControlTab(tabName) {
        // Hide all tabs using both class and inline style for reliability
        const recordTab = document.getElementById('recordTab');
        const historyTab = document.getElementById('historyTab');
        
        recordTab.classList.add('hidden');
        recordTab.style.display = 'none';
        historyTab.classList.add('hidden');
        historyTab.style.display = 'none';
        
        // Remove active state from all buttons
        document.querySelectorAll('.tab-button').forEach(el => {
            el.classList.remove('border-blue-600', 'text-blue-600', 'border-b-2');
            el.classList.add('border-transparent', 'text-gray-600');
        });

        // Show selected tab using both class and inline style for reliability
        if (tabName === 'record') {
            recordTab.classList.remove('hidden');
            recordTab.style.display = '';
        } else if (tabName === 'history') {
            historyTab.classList.remove('hidden');
            historyTab.style.display = '';
        }

        // Set active button - use data-tab attribute
        document.querySelectorAll('.tab-button').forEach(btn => {
            if (btn.getAttribute('data-tab') === tabName) {
                btn.classList.remove('text-gray-600', 'border-transparent');
                btn.classList.add('border-blue-600', 'text-blue-600', 'border-b-2');
            }
        });
    }

    async function startQRScanner() {
        try {
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');
            const video = document.getElementById('qrVideo');
            
            const stream = await navigator.mediaDevices.getUserMedia({ 
                video: { facingMode: 'environment' } 
            });
            
            photoStream = stream;
            video.srcObject = stream;
            video.style.display = 'block';
            document.getElementById('scannerMessage').style.display = 'none';
            document.getElementById('startScannerBtn').classList.add('hidden');
            document.getElementById('stopScannerBtn').classList.remove('hidden');

            // Start QR scanning loop
            async function scanQR() {
                if (video.readyState === video.HAVE_ENOUGH_DATA) {
                    canvas.width = video.videoWidth;
                    canvas.height = video.videoHeight;
                    context.drawImage(video, 0, 0, canvas.width, canvas.height);
                    const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
                    
                    // Simple QR detection - in production use qr-code library
                    // For now, we'll just show it's scanning
                }
                if (photoStream && photoStream.active) {
                    requestAnimationFrame(scanQR);
                }
            }
            scanQR();
        } catch (err) {
            showToast('error', 'Camera access denied. Please check permissions.');
            console.error(err);
        }
    }

    function stopQRScanner() {
        const video = document.getElementById('qrVideo');
        if (photoStream) {
            photoStream.getTracks().forEach(track => track.stop());
            photoStream = null;
        }
        video.style.display = 'none';
        document.getElementById('scannerMessage').style.display = 'flex';
        document.getElementById('startScannerBtn').classList.remove('hidden');
        document.getElementById('stopScannerBtn').classList.add('hidden');
    }

    function getGeolocation() {
        if (!navigator.geolocation) {
            showToast('error', 'Geolocation not supported by your browser');
            return;
        }

        document.getElementById('geoStatus').innerHTML = '<p class="flex items-center"><i class="fas fa-circle-notch fa-spin text-blue-600 mr-2"></i>Getting location...</p>';

        navigator.geolocation.getCurrentPosition(
            (position) => {
                currentLatitude = position.coords.latitude;
                currentLongitude = position.coords.longitude;
                const accuracy = Math.round(position.coords.accuracy);

                document.getElementById('latDisplay').textContent = currentLatitude.toFixed(8);
                document.getElementById('lngDisplay').textContent = currentLongitude.toFixed(8);
                document.getElementById('accuracyDisplay').textContent = accuracy + ' meters';
                document.getElementById('geoStatus').innerHTML = '<p class="text-green-600 flex items-center"><i class="fas fa-check-circle mr-2"></i>Location captured</p>';
                document.getElementById('coordDisplay').classList.remove('hidden');
                
                showToast('success', 'Location captured with ' + accuracy + 'm accuracy');
            },
            (error) => {
                document.getElementById('geoStatus').innerHTML = '<p class="text-red-600">Error: ' + error.message + '</p>';
                showToast('error', 'Failed to get location: ' + error.message);
            },
            { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 }
        );
    }

    function capturePhoto() {
        document.getElementById('photoInput').click();
    }

    function handlePhotoUpload(event) {
        const file = event.target.files[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = (e) => {
            capturedPhotoBase64 = e.target.result;
            const img = document.getElementById('photoImage');
            img.src = capturedPhotoBase64;
            img.style.display = 'block';
            document.getElementById('photoPlaceholder').style.display = 'none';
            document.getElementById('clearPhotoBtn').classList.remove('hidden');
            showToast('success', 'Photo captured');
        };
        reader.readAsDataURL(file);
    }

    function clearPhoto() {
        capturedPhotoBase64 = null;
        document.getElementById('photoImage').style.display = 'none';
        document.getElementById('photoPlaceholder').style.display = 'block';
        document.getElementById('clearPhotoBtn').classList.add('hidden');
        document.getElementById('photoInput').value = '';
    }

    function resetForm() {
        document.querySelector('form').reset();
        // Reset datetime to current time (readonly, so user can't edit)
        const now = new Date();
        now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
        document.getElementById('controlDatetime').value = now.toISOString().slice(0, 16);
        clearPhoto();
        currentLatitude = null;
        currentLongitude = null;
        editingControlId = null;
        document.getElementById('geoStatus').innerHTML = '<p class="flex items-center"><i class="fas fa-circle-notch fa-spin text-blue-600 mr-2"></i>Waiting to capture location...</p>';
    }

    function submitControl(event) {
        event.preventDefault();

        const postId = document.getElementById('postSelect').value;
        const guardId = document.getElementById('guardIdInput').value;

        if (!postId) {
            showToast('error', 'Please select a post');
            return;
        }

        if (!guardId) {
            showToast('error', 'Please scan or enter guard ID');
            return;
        }

        if (!currentLatitude || !currentLongitude) {
            showToast('warning', 'No location captured. Continuing anyway...');
        }

        const formData = new FormData(event.target);
        const data = {
            post_id: postId,
            guard_id: guardId,
            control_datetime: document.getElementById('controlDatetime').value,
            latitude: currentLatitude,
            longitude: currentLongitude,
            attendance_punctuality: parseInt(formData.get('attendance_punctuality')),
            uniform_presentation: parseInt(formData.get('uniform_presentation')),
            patrol_reporting_discipline: parseInt(formData.get('patrol_reporting_discipline')),
            client_feedback: parseInt(formData.get('client_feedback')),
            controller_general_evaluation: parseInt(formData.get('controller_general_evaluation')),
            notes: document.getElementById('controlNotes').value,
            photo_base64: capturedPhotoBase64 || 'unchanged'  // Send 'unchanged' if no new photo
        };

        // Determine if creating new or updating existing
        let endpoint = 'guards/record-control';
        let method = 'POST';
        
        if (editingControlId) {
            endpoint = 'guards/update-control';
            data.id = editingControlId;
        }

        fetch(`${API_BASE_URL}?endpoint=${endpoint}`, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        })
        .then(res => res.json())
        .then(result => {
            console.log('API Response:', result);
            if (result.success) {
                if (editingControlId) {
                    showToast('success', 'Control updated successfully!');
                } else {
                    showToast('success', 'Control recorded successfully!');
                }
                resetForm();
                editingControlId = null;
                setTimeout(() => location.reload(), 2000);
            } else {
                showToast('error', result.error || 'Failed to save control');
            }
        })
        .catch(err => {
            console.error('Error:', err);
            showToast('error', 'An error occurred: ' + err.message);
        });
    }

    function editControl(controlId) {
        // Fetch control data
        fetch(`${API_BASE_URL}?endpoint=guards/get-control&id=${controlId}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(res => res.json())
        .then(data => {
            if (data.success && data.control) {
                const control = data.control;
                
                // Set editing mode
                editingControlId = controlId;
                capturedPhotoBase64 = null;  // Don't include photo unless user changes it
                
                // Populate form with control data
                document.getElementById('postSelect').value = control.post_id;
                document.getElementById('guardIdInput').value = control.guard_id;
                
                // Set scores from stored control
                document.querySelector(`input[name="attendance_punctuality"][value="${control.attendance_punctuality}"]`).checked = true;
                document.querySelector(`input[name="uniform_presentation"][value="${control.uniform_presentation}"]`).checked = true;
                document.querySelector(`input[name="patrol_reporting_discipline"][value="${control.patrol_reporting_discipline}"]`).checked = true;
                document.querySelector(`input[name="client_feedback"][value="${control.client_feedback}"]`).checked = true;
                document.querySelector(`input[name="controller_general_evaluation"][value="${control.controller_general_evaluation}"]`).checked = true;
                
                // Set datetime - make it editable for editing mode
                const dt = new Date(control.control_datetime);
                dt.setMinutes(dt.getMinutes() - dt.getTimezoneOffset());
                document.getElementById('controlDatetime').value = dt.toISOString().slice(0, 16);
                
                // Set notes
                document.getElementById('controlNotes').value = control.notes || '';
                
                // Set location
                if (control.latitude && control.longitude) {
                    currentLatitude = parseFloat(control.latitude);
                    currentLongitude = parseFloat(control.longitude);
                    document.getElementById('latDisplay').textContent = currentLatitude.toFixed(8);
                    document.getElementById('lngDisplay').textContent = currentLongitude.toFixed(8);
                    document.getElementById('coordDisplay').classList.remove('hidden');
                    document.getElementById('geoStatus').innerHTML = '<p class="text-green-600 flex items-center"><i class="fas fa-check-circle mr-2"></i>Location loaded from record</p>';
                }
                
                // Calculate overall score
                calculateOverallScore();
                
                // Switch to record tab and scroll to form
                switchControlTab('record');
                document.querySelector('form').scrollIntoView({ behavior: 'smooth' });
                
                // Show edit mode indicator
                showToast('info', 'Editing control record #' + controlId + ' - Update scores and click Submit to save changes');
            } else {
                showToast('error', data.error || 'Failed to load control data');
            }
        })
        .catch(err => {
            console.error('Error:', err);
            showToast('error', 'An error occurred: ' + err.message);
        });
    }

    function deleteControl(controlId) {
        Swal.fire({
            title: 'Delete Control Record?',
            text: 'This will permanently delete this control record and cannot be undone.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc2626',
            cancelButtonColor: '#6b7280',
            confirmButtonText: 'Yes, delete it',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                fetch(`${API_BASE_URL}?endpoint=guards/delete-control&id=${controlId}`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        showToast('success', 'Control record deleted successfully!');
                        setTimeout(() => location.reload(), 1500);
                    } else {
                        showToast('error', data.error || 'Failed to delete control');
                    }
                })
                .catch(err => {
                    console.error('Error:', err);
                    showToast('error', 'An error occurred while deleting: ' + err.message);
                });
            }
        });
    }

    // Initialize performance chart
    let performanceChart = null;
    function initPerformanceChart() {
        // Get data from page if available
        const chartData = window.performanceChartData;
        if (!chartData || chartData.dates.length === 0) {
            return;
        }

        const ctx = document.getElementById('performanceChart');
        if (!ctx) return;

        if (performanceChart) {
            performanceChart.destroy();
        }

        performanceChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: chartData.dates,
                datasets: [
                    {
                        label: 'Attendance & Punctuality',
                        data: chartData.attendance,
                        borderColor: '#3b82f6',
                        backgroundColor: 'rgba(59, 130, 246, 0.1)',
                        tension: 0.4,
                        fill: false
                    },
                    {
                        label: 'Uniform & Presentation',
                        data: chartData.uniform,
                        borderColor: '#10b981',
                        backgroundColor: 'rgba(16, 185, 129, 0.1)',
                        tension: 0.4,
                        fill: false
                    },
                    {
                        label: 'Patrol & Discipline',
                        data: chartData.patrol,
                        borderColor: '#a855f7',
                        backgroundColor: 'rgba(168, 85, 247, 0.1)',
                        tension: 0.4,
                        fill: false
                    },
                    {
                        label: 'Client Feedback',
                        data: chartData.client,
                        borderColor: '#f59e0b',
                        backgroundColor: 'rgba(245, 158, 11, 0.1)',
                        tension: 0.4,
                        fill: false
                    },
                    {
                        label: 'General Evaluation',
                        data: chartData.general,
                        borderColor: '#ef4444',
                        backgroundColor: 'rgba(239, 68, 68, 0.1)',
                        tension: 0.4,
                        fill: false
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: true,
                        position: 'top'
                    }
                },
                scales: {
                    y: {
                        min: 0,
                        max: 5,
                        title: {
                            display: true,
                            text: 'Score'
                        }
                    }
                }
            }
        });
    }

    function generateControlReport() {
        const fromDate = document.getElementById('reportFromDate').value;
        const toDate = document.getElementById('reportToDate').value;

        if (!fromDate || !toDate) {
            showToast('error', 'Please select both start and end dates');
            return;
        }

        if (new Date(fromDate) > new Date(toDate)) {
            showToast('error', 'Start date must be before end date');
            return;
        }

        // Fetch report data
        fetch(`${API_BASE_URL}?endpoint=guards/generate-report&from=${fromDate}&to=${toDate}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                showReportModal(data.report);
            } else {
                showToast('error', data.error || 'Failed to generate report');
            }
        })
        .catch(err => {
            console.error('Error:', err);
            showToast('error', 'An error occurred: ' + err.message);
        });
    }

    function showReportModal(reportData) {
        // Create HTML for report
        const html = `
            <div class="space-y-6">
                <!-- Summary Section -->
                <div class="bg-gradient-to-r from-blue-50 to-indigo-50 p-6 rounded-lg border border-blue-200">
                    <h3 class="text-xl font-bold text-gray-800 mb-4">Report Summary</h3>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                        <div>
                            <p class="text-sm text-gray-600">Zone</p>
                            <p class="text-lg font-bold text-blue-600">${reportData.zone || 'All'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-gray-600">Posts</p>
                            <p class="text-lg font-bold text-blue-600">${reportData.postCount}</p>
                        </div>
                        <div>
                            <p class="text-sm text-gray-600">Guards</p>
                            <p class="text-lg font-bold text-blue-600">${reportData.guardCount}</p>
                        </div>
                        <div>
                            <p class="text-sm text-gray-600">Total Controls</p>
                            <p class="text-lg font-bold text-blue-600">${reportData.totalControls}</p>
                        </div>
                    </div>
                </div>

                <!-- Statistics Section -->
                <div class="bg-gradient-to-r from-green-50 to-emerald-50 p-6 rounded-lg border border-green-200">
                    <h3 class="text-xl font-bold text-gray-800 mb-4">Statistics</h3>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                        <div>
                            <p class="text-sm text-gray-600">Avg Controls/Post</p>
                            <p class="text-lg font-bold text-green-600">${reportData.avgControlsPerPost}</p>
                        </div>
                        <div>
                            <p class="text-sm text-gray-600">Avg Gap (hours)</p>
                            <p class="text-lg font-bold text-green-600">${reportData.avgGapHours}</p>
                        </div>
                        <div>
                            <p class="text-sm text-gray-600">Best Score</p>
                            <p class="text-lg font-bold text-green-600">${reportData.bestScore.toFixed(2)}</p>
                        </div>
                        <div>
                            <p class="text-sm text-gray-600">Worst Score</p>
                            <p class="text-lg font-bold text-green-600">${reportData.worstScore.toFixed(2)}</p>
                        </div>
                    </div>
                </div>

                <!-- Performance Aspects -->
                <div class="bg-gradient-to-r from-purple-50 to-pink-50 p-6 rounded-lg border border-purple-200">
                    <h3 class="text-xl font-bold text-gray-800 mb-4">Performance Analysis</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div class="bg-white p-4 rounded border border-green-300">
                            <p class="text-sm font-semibold text-gray-700">Strongest Point</p>
                            <p class="text-lg font-bold text-green-600">${reportData.strongestAspect.name}</p>
                            <p class="text-sm text-gray-600">Avg Score: ${reportData.strongestAspect.score.toFixed(2)}/5</p>
                        </div>
                        <div class="bg-white p-4 rounded border border-red-300">
                            <p class="text-sm font-semibold text-gray-700">Weakest Point</p>
                            <p class="text-lg font-bold text-red-600">${reportData.weakestAspect.name}</p>
                            <p class="text-sm text-gray-600">Avg Score: ${reportData.weakestAspect.score.toFixed(2)}/5</p>
                        </div>
                    </div>
                </div>

                <!-- Best and Worst Performers -->
                <div class="bg-white p-6 rounded-lg border border-gray-200">
                    <h3 class="text-xl font-bold text-gray-800 mb-4">Top Performers</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <h4 class="font-semibold text-green-700 mb-2">🏆 Best Performance</h4>
                            <p class="text-lg font-bold">${reportData.bestGuard.name}</p>
                            <p class="text-sm text-gray-600">Score: ${reportData.bestGuard.score.toFixed(2)}%</p>
                        </div>
                        <div>
                            <h4 class="font-semibold text-red-700 mb-2">⚠️ Needs Improvement</h4>
                            <p class="text-lg font-bold">${reportData.worstGuard.name}</p>
                            <p class="text-sm text-gray-600">Score: ${reportData.worstGuard.score.toFixed(2)}%</p>
                        </div>
                    </div>
                </div>

                <!-- Guard Performance Table -->
                <div class="bg-white p-6 rounded-lg border border-gray-200 overflow-x-auto">
                    <h3 class="text-xl font-bold text-gray-800 mb-4">Guard Performance (Sorted by Overall Score)</h3>
                    <table class="w-full text-sm">
                        <thead class="bg-gray-100">
                            <tr>
                                <th class="px-4 py-2 text-left font-semibold">Guard Name</th>
                                <th class="px-4 py-2 text-center font-semibold">Controls</th>
                                <th class="px-4 py-2 text-center font-semibold">Overall %</th>
                                <th class="px-4 py-2 text-center font-semibold">Attendance</th>
                                <th class="px-4 py-2 text-center font-semibold">Uniform</th>
                                <th class="px-4 py-2 text-center font-semibold">Patrol</th>
                                <th class="px-4 py-2 text-center font-semibold">Client</th>
                                <th class="px-4 py-2 text-center font-semibold">General</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${reportData.guardPerformance.map(guard => `
                                <tr class="border-b hover:bg-blue-50">
                                    <td class="px-4 py-2 font-semibold">${guard.name}</td>
                                    <td class="px-4 py-2 text-center">${guard.controlCount}</td>
                                    <td class="px-4 py-2 text-center font-bold text-blue-600">${guard.overallScore.toFixed(0)}%</td>
                                    <td class="px-4 py-2 text-center">${guard.attendance.toFixed(1)}</td>
                                    <td class="px-4 py-2 text-center">${guard.uniform.toFixed(1)}</td>
                                    <td class="px-4 py-2 text-center">${guard.patrol.toFixed(1)}</td>
                                    <td class="px-4 py-2 text-center">${guard.client.toFixed(1)}</td>
                                    <td class="px-4 py-2 text-center">${guard.general.toFixed(1)}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
        `;

        // Show modal with report
        Swal.fire({
            title: 'Control Report',
            html: html,
            width: '90%',
            maxHeight: '90vh',
            showConfirmButton: false,
            showDenyButton: true,
            showCancelButton: true,
            denyButtonText: 'Download PDF',
            cancelButtonText: 'Close',
            didOpen: (modal) => {
                // Get the deny button (Download PDF)
                const denyBtn = modal.querySelector('[data-swal-role="deny"]');
                if (denyBtn) {
                    denyBtn.onclick = () => {
                        downloadReportPDF(reportData);
                    };
                }
            }
        });
    }

    function downloadReportPDF(reportData) {
        const fromDate = document.getElementById('reportFromDate').value;
        const toDate = document.getElementById('reportToDate').value;
        
        // Open PDF download endpoint
        window.open(`${API_BASE_URL}?endpoint=guards/report-pdf&from=${fromDate}&to=${toDate}`, '_blank');
    }

    // Initialize chart on DOM ready
    document.addEventListener('DOMContentLoaded', function() {
        setTimeout(() => {
            initPerformanceChart();
        }, 1000);
    });
</script>

<?php require_once __DIR__ . '/../../layouts/footer.php'; ?>
