<?php
/**
 * Guards - My Patrols
 * View patrols logged by this guard with hourly grid, countdown, and reminder system
 */

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

// Verify guard access
$user = $db->fetch("SELECT id, name FROM users WHERE id = ? AND role = 'guard'", [$_SESSION['user_id'] ?? 0]);
if (!$user) {
    header('Location: ?page=dashboard');
    exit();
}

// Set user role for scanner component
$userRole = 'guard';

// Get guard's assigned post
$assignment = $db->fetch(
    "SELECT gpa.*, p.name as post_name, p.location, 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'",
    [$_SESSION['user_id']]
);

// Get all posts assigned to this guard
$assignedPosts = $db->fetchAll(
    "SELECT DISTINCT post_id FROM guard_post_assignments WHERE guard_id = ? AND status = 'Active'",
    [$_SESSION['user_id']]
);

// Extract post IDs
$postIds = array_map(fn($p) => $p['post_id'], $assignedPosts);

if (empty($postIds)) {
    $patrols = [];
    $patrols_by_date = [];
} else {
    // Get all patrols (last 30 days)
    $placeholders = implode(',', array_fill(0, count($postIds), '?'));
    $query = "SELECT p.*, pt.name as assigned_post, pt.location, pt.facility_type
              FROM patrols p
              JOIN posts pt ON p.post_id = pt.id
              WHERE p.post_id IN ($placeholders) 
              AND DATE(p.patrol_start_time) >= DATE_SUB(NOW(), INTERVAL 30 DAY)
              ORDER BY p.patrol_start_time DESC";

    $patrols = $db->fetchAll($query, $postIds);
    
    // Organize patrols by date and hour
    $patrols_by_date = [];
    foreach ($patrols as $patrol) {
        $date = date('Y-m-d', strtotime($patrol['patrol_start_time']));
        $hour = (int)date('H', strtotime($patrol['patrol_start_time']));
        
        if (!isset($patrols_by_date[$date])) {
            $patrols_by_date[$date] = [];
            for ($h = 0; $h < 24; $h++) {
                $patrols_by_date[$date][$h] = [
                    'status' => 'missed',
                    'patrol' => null,
                    'count' => 0
                ];
            }
        }
        
        $patrols_by_date[$date][$hour]['status'] = $patrol['status'] ?? 'completed';
        $patrols_by_date[$date][$hour]['patrol'] = $patrol;
        $patrols_by_date[$date][$hour]['count']++;
    }
    
    // Sort dates in reverse (newest first)
    krsort($patrols_by_date);
    $patrols_by_date = array_slice($patrols_by_date, 0, 7, true); // Show last 7 days
}

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

<div class="container mx-auto px-4 py-8 max-w-7xl">
    <!-- Header with Countdown -->
    <div class="mb-8">
        <div class="bg-gradient-to-r from-green-600 to-green-700 rounded-lg p-8 text-white shadow-lg">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-4xl font-bold">
                        <i class="fas fa-map mr-3"></i>My Patrols
                    </h1>
                    <p class="text-green-100 mt-2">Patrols logged at <?php echo $assignment ? htmlspecialchars($assignment['post_name']) : 'your assigned post'; ?></p>
                </div>
                <div class="text-right">
                    <!-- Next Patrol Countdown -->
                    <div class="bg-green-700 rounded-lg p-4 mb-4">
                        <p class="text-green-100 text-sm font-semibold">Next Patrol In</p>
                        <div id="countdown" class="text-3xl font-bold text-white font-mono">--:--:--</div>
                    </div>
                    <!-- 10 Min Warning -->
                    <div id="tenMinWarning" class="hidden bg-yellow-500 rounded-lg p-4 animate-pulse">
                        <p class="text-white text-sm font-bold">⏰ 10 Minute Reminder</p>
                        <p class="text-white text-xs mt-1">No patrol completed this hour!</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Tab Navigation -->
    <div class="bg-white rounded-xl shadow-lg border border-gray-200 mb-8">
        <div class="flex border-b border-gray-200">
            <button onclick="switchTab('history')" class="tab-btn px-6 py-3 font-semibold text-gray-600 hover:text-green-600 border-b-2 border-transparent hover:border-green-600 transition whitespace-nowrap active" data-tab="history">
                <i class="fas fa-history mr-2"></i>Patrol History
            </button>
            <button onclick="switchTab('scanner')" class="tab-btn px-6 py-3 font-semibold text-gray-600 hover:text-green-600 border-b-2 border-transparent hover:border-green-600 transition whitespace-nowrap" data-tab="scanner">
                <i class="fas fa-qrcode mr-2"></i>Start Patrol
            </button>
        </div>
    </div>

    <!-- History Tab -->
    <div id="history-tab" class="tab-content">
    <?php if (!empty($patrols_by_date)): ?>
        <div class="space-y-8">
            <?php foreach ($patrols_by_date as $date => $hours): ?>
                <div class="bg-white rounded-xl shadow-lg border border-gray-200 p-6">
                    <!-- Date Header -->
                    <h2 class="text-2xl font-bold text-gray-800 mb-6">
                        <?php echo date('l, F j, Y', strtotime($date)); ?>
                    </h2>

                    <!-- Hourly Grid (24-hour) -->
                    <div class="grid grid-cols-6 md:grid-cols-12 gap-2 mb-6">
                        <?php for ($h = 0; $h < 24; $h++):
                            $hour_data = $hours[$h];
                            $status = $hour_data['status'];
                            $patrol = $hour_data['patrol'];
                            
                            // Determine colors based on status
                            if ($status === 'completed' || $status === 'Completed') {
                                $color_class = 'bg-green-500 hover:bg-green-600';
                                $text_status = 'Complete';
                                $icon = 'fa-check';
                            } elseif ($status === 'incomplete' || $status === 'Incomplete') {
                                $color_class = 'bg-yellow-400 hover:bg-yellow-500';
                                $text_status = 'Incomplete';
                                $icon = 'fa-exclamation';
                            } else {
                                $color_class = 'bg-red-500 hover:bg-red-600';
                                $text_status = 'Missed';
                                $icon = 'fa-times';
                            }
                            
                            $hour_str = str_pad($h, 2, '0', STR_PAD_LEFT);
                        ?>
                            <div class="text-center">
                                <button onclick="viewHourDetails('<?php echo $date; ?>', <?php echo $h; ?>, event)" 
                                        class="<?php echo $color_class; ?> text-white rounded-lg p-3 cursor-pointer transition transform hover:scale-105 group relative w-full" 
                                        title="<?php echo $hour_str; ?>:00 - <?php echo $text_status; ?>">
                                    <div class="font-bold text-sm"><?php echo $hour_str; ?></div>
                                    <div class="text-xs font-semibold"><i class="fas <?php echo $icon; ?>"></i></div>
                                    
                                    <!-- Tooltip -->
                                    <div class="hidden group-hover:block absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 w-48 bg-gray-900 text-white text-xs rounded p-2 z-10 whitespace-normal">
                                        <strong><?php echo $hour_str; ?>:00</strong><br>
                                        Status: <?php echo $text_status; ?><br>
                                        <?php if ($patrol): ?>
                                            Start: <?php echo date('H:i', strtotime($patrol['patrol_start_time'])); ?><br>
                                            <?php if (!empty($patrol['patrol_end_time'])): ?>
                                                End: <?php echo date('H:i', strtotime($patrol['patrol_end_time'])); ?>
                                            <?php else: ?>
                                                <span class="text-yellow-300">Ongoing...</span>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </div>
                                </button>
                            </div>
                        <?php endfor; ?>
                    </div>

                    <!-- Legend -->
                    <div class="flex items-center gap-4 mt-4 text-sm flex-wrap border-t border-gray-200 pt-4">
                        <div class="flex items-center gap-2">
                            <div class="w-4 h-4 bg-green-500 rounded"></div>
                            <span class="text-gray-700">Completed</span>
                        </div>
                        <div class="flex items-center gap-2">
                            <div class="w-4 h-4 bg-yellow-400 rounded"></div>
                            <span class="text-gray-700">Incomplete</span>
                        </div>
                        <div class="flex items-center gap-2">
                            <div class="w-4 h-4 bg-red-500 rounded"></div>
                            <span class="text-gray-700">Missed</span>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php else: ?>
        <div class="bg-white rounded-xl shadow-lg border border-gray-200 p-12 text-center">
            <i class="fas fa-shoe-prints text-5xl text-gray-300 mb-4"></i>
            <p class="text-gray-600 font-medium text-lg">No patrols found</p>
            <p class="text-gray-500 text-sm mt-2">Start logging patrols to see them here</p>
        </div>
    <?php endif; ?>
    </div>

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

<!-- Hour Details Modal -->
<div id="hourModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-xl shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        <!-- Header -->
        <div class="sticky top-0 bg-gradient-to-r from-green-600 to-green-700 text-white p-6 flex items-center justify-between">
            <h2 id="hourModalTitle" class="text-2xl font-bold">Hour Details</h2>
            <button onclick="closeHourModal()" class="text-white hover:bg-green-800 rounded-full p-3 transition">
                <i class="fas fa-times text-2xl"></i>
            </button>
        </div>

        <!-- Content -->
        <div id="hourContent" class="p-8 space-y-6">
            <!-- Content will be populated by JavaScript -->
        </div>

        <!-- Footer -->
        <div class="sticky bottom-0 bg-gray-50 border-t border-gray-200 p-6 flex justify-end gap-3">
            <button onclick="closeHourModal()" class="px-6 py-2 text-gray-700 bg-white border-2 border-gray-300 rounded-lg hover:bg-gray-100 transition font-semibold">
                Close
            </button>
        </div>
    </div>
</div>

<script>
// Countdown Timer
function updateCountdown() {
    const now = new Date();
    const nextHour = new Date();
    nextHour.setHours(nextHour.getHours() + 1, 0, 0, 0);
    
    const diff = nextHour - now;
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const mins = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    const secs = Math.floor((diff % (1000 * 60)) / 1000);
    
    const countdownEl = document.getElementById('countdown');
    if (countdownEl) {
        countdownEl.textContent = 
            String(hours).padStart(2, '0') + ':' +
            String(mins).padStart(2, '0') + ':' +
            String(secs).padStart(2, '0');
    }
    
    // Show 10-minute warning
    const tenMinWarning = document.getElementById('tenMinWarning');
    if (tenMinWarning && mins === 10 && secs < 1) {
        tenMinWarning.classList.remove('hidden');
        // Auto-hide after 60 seconds
        setTimeout(() => tenMinWarning.classList.add('hidden'), 60000);
    }
}

// Update countdown every second
setInterval(updateCountdown, 1000);
updateCountdown();

// Modal functions
function viewHourDetails(date, hour, event) {
    event.preventDefault();
    const hourStr = String(hour).padStart(2, '0');
    document.getElementById('hourModalTitle').textContent = `${hourStr}:00 Patrol Details`;
    
    // Get patrol data for this hour
    const patrols = <?php echo json_encode($patrols); ?>;
    const hourPatrols = patrols.filter(p => {
        const pDate = p.patrol_start_time.split(' ')[0];
        const pHour = parseInt(p.patrol_start_time.split(' ')[1].split(':')[0]);
        return pDate === date && pHour === hour;
    });
    
    let content = '';
    if (hourPatrols.length === 0) {
        content = `
            <div class="text-center py-8">
                <i class="fas fa-times-circle text-6xl text-red-400 mb-4 block"></i>
                <p class="text-gray-600 font-semibold text-lg">No patrol completed in this hour</p>
                <p class="text-gray-500 text-sm mt-2">Consider adding a patrol entry for ${hourStr}:00</p>
            </div>
        `;
    } else {
        hourPatrols.forEach((patrol, idx) => {
            const startTime = new Date(patrol.patrol_start_time);
            const endTime = patrol.patrol_end_time ? new Date(patrol.patrol_end_time) : null;
            const duration = endTime ? Math.round((endTime - startTime) / 60000) : 0;
            
            content += `
                <div class="border-l-4 border-green-600 pl-4 pb-6${idx < hourPatrols.length - 1 ? ' border-b pb-6' : ''}">
                    <div class="flex items-start justify-between mb-4">
                        <h3 class="text-lg font-bold text-gray-800">Patrol ${idx + 1}</h3>
                        <span class="px-3 py-1 ${patrol.status === 'Completed' ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'} rounded-full text-xs font-bold">
                            ${patrol.status || 'Pending'}
                        </span>
                    </div>
                    
                    <div class="space-y-3">
                        <div class="bg-gray-50 rounded-lg p-3">
                            <p class="text-xs font-bold text-gray-600 uppercase mb-1">Start Time</p>
                            <p class="text-gray-800 font-semibold">${startTime.toLocaleString()}</p>
                        </div>
                        ${endTime ? `
                            <div class="bg-gray-50 rounded-lg p-3">
                                <p class="text-xs font-bold text-gray-600 uppercase mb-1">Duration</p>
                                <p class="text-gray-800 font-semibold">${Math.floor(duration / 60)}h ${duration % 60}m</p>
                            </div>
                        ` : ''}
                        ${patrol.observations ? `
                            <div class="bg-gray-50 rounded-lg p-3">
                                <p class="text-xs font-bold text-gray-600 uppercase mb-1">Observations</p>
                                <p class="text-gray-800">${patrol.observations}</p>
                            </div>
                        ` : ''}
                        ${patrol.issues_found ? `
                            <div class="bg-red-50 border border-red-200 rounded-lg p-3">
                                <p class="text-xs font-bold text-red-700 uppercase mb-1">Issues Found</p>
                                <p class="text-red-800">${patrol.issues_found}</p>
                            </div>
                        ` : ''}
                    </div>
                </div>
            `;
        });
    }
    
    document.getElementById('hourContent').innerHTML = content;
    document.getElementById('hourModal').classList.remove('hidden');
}

function closeHourModal() {
    document.getElementById('hourModal').classList.add('hidden');
}

// Close modal on escape key
document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
        closeHourModal();
    }
});

// Tab switching function
function switchTab(tabName) {
    // Hide all tabs
    const tabs = document.querySelectorAll('.tab-content');
    tabs.forEach(tab => tab.classList.add('hidden'));
    
    // Remove active state from all buttons
    const buttons = document.querySelectorAll('.tab-btn');
    buttons.forEach(btn => {
        btn.classList.remove('border-green-600');
        btn.classList.add('border-transparent');
    });
    
    // Show selected tab
    const selectedTab = document.getElementById(tabName + '-tab');
    if (selectedTab) {
        selectedTab.classList.remove('hidden');
    }
    
    // Add active state to clicked button
    event.target.closest('.tab-btn').classList.add('border-green-600');
}
</script>

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