<?php
/**
 * Guards Dashboard
 * SSCI Office Platform
 */

$auth = $GLOBALS['auth'];
$db = $GLOBALS['db'];

$user = $auth->getCurrentUser();

// Check if user is a guard
if ($user['role'] !== 'guard') {
    header('Location: ?page=dashboard');
    exit();
}

// Get guard-specific stats
// Get assigned post
$assignedPost = $db->fetch(
    "SELECT gpa.*, p.name as post_name, p.facility_type FROM guard_post_assignments gpa
     JOIN posts p ON gpa.post_id = p.id
     WHERE gpa.guard_id = ? AND gpa.status = 'Active'
     ORDER BY gpa.created_at DESC LIMIT 1",
    [$user['id']]
);

// Get total patrols this month
$totalPatrols = $db->fetch(
    "SELECT COUNT(DISTINCT p.id) as count FROM patrols p
     JOIN patrol_scans ps ON p.id = ps.post_id
     WHERE ps.guard_id = ? AND MONTH(p.patrol_date) = MONTH(NOW()) AND YEAR(p.patrol_date) = YEAR(NOW())",
    [$user['id']]
)['count'] ?? 0;

// Get controls conducted on this guard
$totalControls = $db->fetch(
    "SELECT COUNT(*) as count FROM guards_controls WHERE guard_id = ?",
    [$user['id']]
)['count'] ?? 0;

// Get unread messages
$unreadMessages = $db->fetch(
    "SELECT COUNT(*) as count FROM messages WHERE recipient_id = ? AND is_read = 0",
    [$user['id']]
)['count'] ?? 0;

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

<div class="animate__animated animate__fadeIn">
    <!-- Page Header -->
    <div class="mb-8 flex items-center justify-between">
        <div>
            <h1 class="text-4xl font-bold text-gray-800 mb-2">
                <i class="fas fa-shield-alt text-green-600 mr-3"></i>Dashboard
            </h1>
            <p class="text-gray-600">Welcome back, <?php echo e($user['name']); ?></p>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <!-- Assigned Post -->
        <div class="bg-white rounded-lg shadow p-6 border-l-4 border-blue-500 hover:shadow-lg transition">
            <div class="flex justify-between items-start">
                <div>
                    <p class="text-gray-600 text-sm font-semibold">Assigned Post</p>
                    <p class="text-2xl font-bold text-gray-800 mt-2">
                        <?php echo $assignedPost ? htmlspecialchars($assignedPost['post_name']) : 'None'; ?>
                    </p>
                </div>
                <div class="bg-blue-100 p-3 rounded-lg">
                    <i class="fas fa-map-pin text-blue-600 text-2xl"></i>
                </div>
            </div>
            <p class="text-gray-500 text-xs mt-4">
                <span class="text-blue-600"><?php echo $assignedPost ? htmlspecialchars($assignedPost['facility_type']) : 'No assignment'; ?></span>
            </p>
        </div>

        <!-- Patrols This Month -->
        <div class="bg-white rounded-lg shadow p-6 border-l-4 border-green-500 hover:shadow-lg transition">
            <div class="flex justify-between items-start">
                <div>
                    <p class="text-gray-600 text-sm font-semibold">Patrols This Month</p>
                    <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo $totalPatrols; ?></p>
                </div>
                <div class="bg-green-100 p-3 rounded-lg">
                    <i class="fas fa-walking text-green-600 text-2xl"></i>
                </div>
            </div>
            <a href="?page=guards-patrols" class="text-green-600 text-xs mt-4 font-semibold hover:text-green-700">
                View Patrols <i class="fas fa-arrow-right ml-1"></i>
            </a>
        </div>

        <!-- Controls Conducted -->
        <div class="bg-white rounded-lg shadow p-6 border-l-4 border-yellow-500 hover:shadow-lg transition">
            <div class="flex justify-between items-start">
                <div>
                    <p class="text-gray-600 text-sm font-semibold">Controls on You</p>
                    <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo $totalControls; ?></p>
                </div>
                <div class="bg-yellow-100 p-3 rounded-lg">
                    <i class="fas fa-clipboard-check text-yellow-600 text-2xl"></i>
                </div>
            </div>
            <a href="?page=guards-controls" class="text-yellow-600 text-xs mt-4 font-semibold hover:text-yellow-700">
                View Details <i class="fas fa-arrow-right ml-1"></i>
            </a>
        </div>

        <!-- Unread Messages -->
        <div class="bg-white rounded-lg shadow p-6 border-l-4 border-purple-500 hover:shadow-lg transition">
            <div class="flex justify-between items-start">
                <div>
                    <p class="text-gray-600 text-sm font-semibold">Unread Messages</p>
                    <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo $unreadMessages; ?></p>
                </div>
                <div class="bg-purple-100 p-3 rounded-lg">
                    <i class="fas fa-envelope text-purple-600 text-2xl"></i>
                </div>
            </div>
            <a href="?page=guards-messages" class="text-purple-600 text-xs mt-4 font-semibold hover:text-purple-700">
                View Messages <i class="fas fa-arrow-right ml-1"></i>
            </a>
        </div>
    </div>

    <!-- Quick Action Buttons -->
    <div class="grid grid-cols-1 lg:grid-cols-5 gap-6 mb-8">
        <!-- Start Patrol - Direct to QR Scanner -->
        <a href="?page=guards-patrols&tab=scanner" class="group block">
            <div class="bg-gradient-to-br from-green-500 to-green-600 rounded-xl shadow-lg p-8 text-center hover:shadow-2xl transition transform hover:scale-105 cursor-pointer text-white">
                <div class="inline-block bg-white/20 p-5 rounded-full mb-4 group-hover:bg-white/30 transition">
                    <i class="fas fa-qrcode text-white text-4xl"></i>
                </div>
                <h3 class="text-xl font-bold mb-2">Start Patrol</h3>
                <p class="text-green-100 text-sm">Begin QR scan patrol</p>
            </div>
        </a>

        <!-- My Post -->
        <a href="?page=guards-posts" class="group block">
            <div class="bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl shadow-lg p-8 text-center hover:shadow-2xl transition transform hover:scale-105 cursor-pointer text-white">
                <div class="inline-block bg-white/20 p-5 rounded-full mb-4 group-hover:bg-white/30 transition">
                    <i class="fas fa-building text-white text-4xl"></i>
                </div>
                <h3 class="text-xl font-bold mb-2">My Post</h3>
                <p class="text-blue-100 text-sm">View assigned details</p>
            </div>
        </a>

        <!-- My Profile -->
        <a href="?page=guards-profile" class="group block">
            <div class="bg-gradient-to-br from-indigo-500 to-indigo-600 rounded-xl shadow-lg p-8 text-center hover:shadow-2xl transition transform hover:scale-105 cursor-pointer text-white">
                <div class="inline-block bg-white/20 p-5 rounded-full mb-4 group-hover:bg-white/30 transition">
                    <i class="fas fa-user-shield text-white text-4xl"></i>
                </div>
                <h3 class="text-xl font-bold mb-2">My Profile</h3>
                <p class="text-indigo-100 text-sm">Contract & badge</p>
            </div>
        </a>

        <!-- My Salary -->
        <a href="?page=guards-payments" class="group block">
            <div class="bg-gradient-to-br from-purple-500 to-purple-600 rounded-xl shadow-lg p-8 text-center hover:shadow-2xl transition transform hover:scale-105 cursor-pointer text-white">
                <div class="inline-block bg-white/20 p-5 rounded-full mb-4 group-hover:bg-white/30 transition">
                    <i class="fas fa-money-bill-wave text-white text-4xl"></i>
                </div>
                <h3 class="text-xl font-bold mb-2">My Salary</h3>
                <p class="text-purple-100 text-sm">Payslips & history</p>
            </div>
        </a>

        <!-- Install App -->
        <button onclick="installApp()" class="group block w-full">
            <div class="bg-gradient-to-br from-orange-500 to-orange-600 rounded-xl shadow-lg p-8 text-center hover:shadow-2xl transition transform hover:scale-105 cursor-pointer text-white">
                <div class="inline-block bg-white/20 p-5 rounded-full mb-4 group-hover:bg-white/30 transition">
                    <i class="fas fa-download text-white text-4xl"></i>
                </div>
                <h3 class="text-xl font-bold mb-2">Install App</h3>
                <p class="text-orange-100 text-sm">Work offline</p>
            </div>
        </button>
    </div>

    <?php if ($assignedPost): ?>
    <!-- Post Details Card -->
    <div class="bg-white rounded-lg shadow p-8 mb-8">
        <h2 class="text-2xl font-bold text-gray-800 mb-6">
            <i class="fas fa-map-pin text-green-600 mr-2"></i>Current Assignment
        </h2>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
            <div>
                <h3 class="text-lg font-bold text-gray-800 mb-4"><?php echo htmlspecialchars($assignedPost['post_name']); ?></h3>
                <div class="space-y-3">
                    <div class="flex items-center text-gray-600">
                        <i class="fas fa-tag w-5 text-green-600"></i>
                        <span class="ml-3"><strong>Type:</strong> <?php echo htmlspecialchars($assignedPost['facility_type']); ?></span>
                    </div>
                    <div class="flex items-center text-gray-600">
                        <i class="fas fa-calendar w-5 text-blue-600"></i>
                        <span class="ml-3"><strong>Assigned:</strong> <?php echo date('M d, Y', strtotime($assignedPost['created_at'])); ?></span>
                    </div>
                    <div class="flex items-center text-gray-600">
                        <i class="fas fa-info-circle w-5 text-yellow-600"></i>
                        <span class="ml-3"><strong>Status:</strong> <span class="text-green-600 font-semibold">Active</span></span>
                    </div>
                </div>
                <a href="?page=guards-posts" class="inline-block mt-6 bg-green-600 text-white px-6 py-2 rounded-lg hover:bg-green-700 transition font-semibold">
                    View Full Details
                </a>
            </div>

            <div>
                <h3 class="text-lg font-bold text-gray-800 mb-4">Quick Statistics</h3>
                <div class="space-y-3">
                    <div class="bg-gray-50 rounded-lg p-4">
                        <p class="text-gray-600 text-sm">Patrols This Month</p>
                        <p class="text-3xl font-bold text-green-600"><?php echo $totalPatrols; ?></p>
                    </div>
                    <div class="bg-gray-50 rounded-lg p-4">
                        <p class="text-gray-600 text-sm">Total Controls</p>
                        <p class="text-3xl font-bold text-yellow-600"><?php echo $totalControls; ?></p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

</div>

<script>
    let deferredPrompt;
    
    window.addEventListener('beforeinstallprompt', (e) => {
        e.preventDefault();
        deferredPrompt = e;
    });
    
    function installApp() {
        if (deferredPrompt) {
            deferredPrompt.prompt();
            deferredPrompt.userChoice.then((choiceResult) => {
                if (choiceResult.outcome === 'accepted') {
                    Swal.fire({
                        title: 'App Installed',
                        text: 'The SSCI app has been successfully installed on your device.',
                        icon: 'success',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#10b981'
                    });
                }
                deferredPrompt = null;
            });
        } else {
            Swal.fire({
                title: 'Install Guide',
                html: '<div class="text-left"><p class="mb-3"><strong>To install this app:</strong></p><ol class="list-decimal list-inside space-y-2"><li>Click the menu button (⋮) in your browser</li><li>Select "Install app" or "Add to Home Screen"</li><li>Follow the prompts to complete installation</li></ol></div>',
                icon: 'info',
                confirmButtonText: 'Understood',
                confirmButtonColor: '#10b981'
            });
        }
    }
</script>

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