<?php
/**
 * Patrols Management Page
 * SSCI Office Platform - Security Guard Patrol Tracking System
 */

// Bootstrap is already loaded from public/index.php
$auth = $GLOBALS['auth'];
$db = $GLOBALS['db'];

if (!$auth->canAccessPage('patrols')) {
    header('Location: index.php');
    exit();
}

$pageTitle = trans('patrols') . ' - ' . config('app.name');
$userRole = $_SESSION['role'] ?? null;
?>

<!DOCTYPE html>
<html lang="<?php echo current_language(); ?>" dir="<?php echo text_direction(); ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($pageTitle); ?></title>
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=PT+Sans+Narrow:wght@400;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        * {
            font-family: 'PT Sans Narrow', sans-serif;
        }
        .score-badge {
            font-size: 1.5rem;
            font-weight: bold;
            padding: 0.5rem 1rem;
            border-radius: 0.5rem;
        }
        .score-completed { background: #10b981; color: white; }
        .score-incomplete { background: #f59e0b; color: white; }
        .score-missed { background: #ef4444; color: white; }
        .patrol-card {
            transition: all 0.3s ease;
        }
        .patrol-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body class="bg-gray-50">
    <?php require SSCI_VIEWS . '/layouts/header.php'; ?>
    
    <div class="p-4 md:p-8">
        <!-- Page Header -->
        <div class="mb-6">
            <h1 class="text-3xl font-bold text-gray-800 mb-2">
                <i class="fas fa-route text-blue-600 mr-2"></i><?php echo trans('patrols'); ?>
            </h1>
            <p class="text-gray-600">
                <?php echo trans('manage_and_track_guard_patrols'); ?>
            </p>
        </div>

        <!-- Tabs -->
        <div class="mb-6 flex space-x-2 border-b border-gray-200 overflow-x-auto">
            <button onclick="switchTab('overview')" class="tab-btn active px-4 py-2 font-semibold text-blue-600 border-b-2 border-blue-600 whitespace-nowrap">
                <i class="fas fa-chart-bar mr-2"></i><?php echo trans('overview'); ?>
            </button>
            <button onclick="switchTab('scanner')" class="tab-btn px-4 py-2 font-semibold text-gray-600 hover:text-blue-600 whitespace-nowrap">
                <i class="fas fa-qrcode mr-2"></i><?php echo trans('scan_qr_code'); ?>
            </button>
            <button onclick="switchTab('dashboard')" class="tab-btn px-4 py-2 font-semibold text-gray-600 hover:text-blue-600 whitespace-nowrap">
                <i class="fas fa-gauge mr-2"></i><?php echo trans('dashboard'); ?>
            </button>
            <?php if ($userRole === 'admin' || $userRole === 'manager'): ?>
            <button onclick="switchTab('settings')" class="tab-btn px-4 py-2 font-semibold text-gray-600 hover:text-blue-600 whitespace-nowrap">
                <i class="fas fa-cog mr-2"></i><?php echo trans('settings'); ?>
            </button>
            <?php endif; ?>
        </div>

        <!-- Overview Tab -->
        <div id="overview-tab" class="tab-content">
            <!-- Posts with Patrol Status -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
                <?php
                $posts = $db->fetchAll("SELECT * FROM posts WHERE active = 1 ORDER BY name ASC");
                if (empty($posts)):
                ?>
                    <div class="col-span-full bg-blue-50 border border-blue-200 rounded-lg p-6 text-center">
                        <i class="fas fa-info-circle text-blue-600 text-2xl mb-2"></i>
                        <p class="text-gray-700"><?php echo trans('no_posts_available'); ?></p>
                    </div>
                <?php else:
                    foreach ($posts as $post):
                        // Get current patrol status
                        $currentHour = date('Y-m-d H');
                        $patrol = $db->fetch(
                            "SELECT * FROM patrols WHERE post_id = ? AND patrol_hour = ? LIMIT 1",
                            [$post['id'], $currentHour]
                        );
                        
                        $score = $patrol['score'] ?? 0;
                        $status = $patrol['status'] ?? 'Missed';
                        $completion = $patrol['completion_percentage'] ?? 0;
                        
                        $statusClass = $status === 'Completed' ? 'score-completed' : 
                                      ($status === 'Incomplete' ? 'score-incomplete' : 'score-missed');
                ?>
                    <div class="patrol-card bg-white rounded-lg shadow p-6 border-l-4" 
                         style="border-left-color: <?php echo $status === 'Completed' ? '#10b981' : ($status === 'Incomplete' ? '#f59e0b' : '#ef4444'); ?>">
                        <div class="flex justify-between items-start mb-4">
                            <div>
                                <h3 class="text-lg font-bold text-gray-800"><?php echo htmlspecialchars($post['name']); ?></h3>
                                <p class="text-sm text-gray-500"><?php echo htmlspecialchars($post['location'] ?? 'N/A'); ?></p>
                            </div>
                            <span class="px-3 py-1 rounded-full text-xs font-semibold <?php echo $statusClass; ?>">
                                <?php echo $status; ?>
                            </span>
                        </div>

                        <!-- Score Progress -->
                        <div class="mb-4">
                            <div class="flex justify-between mb-2">
                                <span class="text-sm font-semibold text-gray-700"><?php echo trans('patrol_score'); ?></span>
                                <span class="text-sm font-bold text-blue-600"><?php echo $score; ?>/8</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2.5">
                                <div class="bg-blue-600 h-2.5 rounded-full transition-all duration-300" 
                                     style="width: <?php echo min($completion, 100); ?>%"></div>
                            </div>
                            <p class="text-xs text-gray-600 mt-1"><?php echo round($completion); ?>% <?php echo trans('complete'); ?></p>
                        </div>

                        <!-- Stats -->
                        <div class="grid grid-cols-2 gap-2 mb-4 text-sm">
                            <div class="bg-gray-50 p-2 rounded">
                                <p class="text-gray-600"><?php echo trans('patrol_points'); ?></p>
                                <p class="font-bold text-gray-800">4</p>
                            </div>
                            <div class="bg-gray-50 p-2 rounded">
                                <p class="text-gray-600"><?php echo trans('scans'); ?></p>
                                <p class="font-bold text-gray-800"><?php echo $patrol['total_scans'] ?? 0; ?></p>
                            </div>
                        </div>

                        <!-- Actions -->
                        <div class="flex gap-2">
                            <a href="?page=patrols&post_id=<?php echo $post['id']; ?>" class="flex-1 px-3 py-2 bg-blue-600 text-white rounded text-center text-sm font-semibold hover:bg-blue-700 transition">
                                <i class="fas fa-eye mr-1"></i><?php echo trans('view_details'); ?>
                            </a>
                            <a href="?page=admin/patrols/manage-points&post_id=<?php echo $post['id']; ?>" class="flex-1 px-3 py-2 bg-green-600 text-white rounded text-center text-sm font-semibold hover:bg-green-700 transition">
                                <i class="fas fa-location-dot mr-1"></i><?php echo trans('manage_points'); ?>
                            </a>
                            <?php if ($userRole === 'admin' || $userRole === 'manager'): ?>
                                <button onclick="editPatrolSettings(<?php echo $post['id']; ?>)" class="px-3 py-2 bg-gray-600 text-white rounded text-sm font-semibold hover:bg-gray-700 transition">
                                    <i class="fas fa-cog"></i>
                                </button>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; endif; ?>
            </div>
        </div>

        <!-- Scanner Tab -->
        <div id="scanner-tab" class="tab-content hidden">
            <?php require SSCI_VIEWS . '/components/patrol-scanner.php'; ?>
        </div>

        <!-- Dashboard Tab -->
        <div id="dashboard-tab" class="tab-content hidden">
            <?php require SSCI_VIEWS . '/components/patrol-dashboard.php'; ?>
        </div>

        <!-- Settings Tab (Admin/Manager only) -->
        <?php if ($userRole === 'admin' || $userRole === 'manager'): ?>
        <div id="settings-tab" class="tab-content hidden">
            <div class="bg-white rounded-lg shadow p-8 max-w-2xl">
                <h2 class="text-2xl font-bold text-gray-800 mb-6">
                    <i class="fas fa-cog text-blue-600 mr-2"></i><?php echo trans('patrol_settings'); ?>
                </h2>

                <div class="space-y-6">
                    <!-- Reminder Time -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            <?php echo trans('reminder_time'); ?>
                        </label>
                        <div class="flex items-center">
                            <input type="number" id="reminderMinutes" min="1" max="59" value="50" 
                                   class="px-4 py-2 border border-gray-300 rounded-lg w-24 focus:outline-none focus:ring-2 focus:ring-blue-600">
                            <span class="ml-2 text-gray-700"><?php echo trans('minutes_before_hour_end'); ?></span>
                        </div>
                        <p class="text-sm text-gray-600 mt-2">
                            <?php echo trans('reminders_sent_at_minute'); ?> <span id="reminderDisplay">50</span> <?php echo trans('of_each_hour'); ?>
                        </p>
                    </div>

                    <!-- Save Button -->
                    <div class="pt-6 border-t border-gray-200">
                        <button onclick="savePatrolSettings()" class="px-6 py-3 bg-blue-600 text-white rounded-lg font-semibold hover:bg-blue-700 transition">
                            <i class="fas fa-save mr-2"></i><?php echo trans('save_settings'); ?>
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <?php require SSCI_VIEWS . '/layouts/footer.php'; ?>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        function switchTab(tabName) {
            // Hide all tabs
            document.querySelectorAll('.tab-content').forEach(tab => tab.classList.add('hidden'));
            document.querySelectorAll('.tab-btn').forEach(btn => {
                btn.classList.remove('active', 'text-blue-600', 'border-b-2', 'border-blue-600');
                btn.classList.add('text-gray-600');
            });

            // Show selected tab
            document.getElementById(tabName + '-tab').classList.remove('hidden');
            event.target.closest('.tab-btn').classList.add('active', 'text-blue-600', 'border-b-2', 'border-blue-600');
            event.target.closest('.tab-btn').classList.remove('text-gray-600');
        }

        document.getElementById('reminderMinutes').addEventListener('change', function() {
            document.getElementById('reminderDisplay').textContent = this.value;
        });

        function editPatrolSettings(postId) {
            Swal.fire({
                title: '<?php echo trans('patrol_settings'); ?>',
                html: `<div class="text-left">
                    <p class="text-gray-700 mb-4"><?php echo trans('managing_patrol_for'); ?> Post ID: ${postId}</p>
                    <button onclick="location.href='?page=patrols&post_id=${postId}'" class="px-4 py-2 bg-blue-600 text-white rounded">
                        <?php echo trans('manage_points'); ?>
                    </button>
                </div>`,
                showConfirmButton: false,
                showCancelButton: true
            });
        }

        function savePatrolSettings() {
            Swal.fire({
                title: '<?php echo trans('saving'); ?>...',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            setTimeout(() => {
                Swal.fire({
                    title: '<?php echo trans('success'); ?>!',
                    text: '<?php echo trans('patrol_settings_saved'); ?>',
                    icon: 'success',
                    confirmButtonText: '<?php echo trans('ok'); ?>'
                });
            }, 1000);
        }

        // Auto-refresh patrol status every 30 seconds
        // setInterval(() => {
        //     location.reload();
        // }, 30000);
    </script>
</body>
</html>
