<?php
/**
 * Client - My Patrols (Read-Only)
 * View patrol performance for their own posts with hourly grid visualization
 * Uses new patrol system with hourly tracking, QR codes, and scoring
 */

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

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

// Get client's posts
$posts = $db->fetchAll(
    "SELECT id, name, location, active FROM posts WHERE owner_id = ? AND active = 1 ORDER BY name ASC",
    [$_SESSION['user_id']]
);

// Get date range for filter (last 30 days)
$end_date = date('Y-m-d');
$start_date = date('Y-m-d', strtotime('-30 days'));

// Build patrol data by post
$patrol_data = [];

if (!empty($posts)) {
    $post_ids = array_column($posts, 'id');
    
    // Get all patrols for these posts in the date range
    $placeholders = implode(',', array_fill(0, count($post_ids), '?'));
    $patrols = $db->fetchAll(
        "SELECT p.*, 
                COUNT(ps.id) as scan_count
         FROM patrols p
         LEFT JOIN patrol_scans ps ON p.post_id = ps.post_id 
            AND DATE(ps.scan_timestamp) = p.patrol_date
            AND DATE_FORMAT(ps.scan_timestamp, '%Y-%m-%d %H:00:00') = p.patrol_start_time
         WHERE p.post_id IN ($placeholders)
         AND DATE(p.patrol_date) >= ?
         AND DATE(p.patrol_date) <= ?
         GROUP BY p.id
         ORDER BY p.created_at DESC",
        array_merge($post_ids, [$start_date, $end_date])
    );
    
    // Organize by post and date then hour
    foreach ($posts as $post) {
        $patrol_data[$post['id']] = [
            'name' => $post['name'],
            'location' => $post['location'],
            'dates' => []
        ];
    }
    
    foreach ($patrols as $patrol) {
        $post_id = $patrol['post_id'];
        $date = $patrol['patrol_date'];
        $hour = (int)date('H', strtotime($patrol['patrol_start_time']));
        
        if (!isset($patrol_data[$post_id]['dates'][$date])) {
            $patrol_data[$post_id]['dates'][$date] = array_fill(0, 24, [
                'status' => 'Missed',
                'score' => 0,
                'completion' => 0,
                'scans' => 0,
                'patrol_id' => null,
                'details' => null
            ]);
        }
        
        $patrol_data[$post_id]['dates'][$date][$hour] = [
            'status' => $patrol['status'],
            'score' => $patrol['score'],
            'completion' => $patrol['completion_percentage'],
            'scans' => $patrol['scan_count'],
            'patrol_id' => $patrol['id'],
            'details' => $patrol
        ];
    }
}

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

<div class="container mx-auto px-4 py-8 max-w-7xl">
    <!-- Header -->
    <div class="mb-8">
        <div class="flex items-center justify-between">
            <h1 class="text-4xl font-bold text-gray-800">
                <i class="fas fa-route text-blue-600 mr-3"></i><?php echo Language::get('my_patrols'); ?>
            </h1>
            <a href="?page=clients/dashboard" class="px-6 py-3 bg-gray-600 text-white rounded-lg hover:bg-gray-700 font-semibold">
                <i class="fas fa-arrow-left mr-2"></i><?php echo Language::get('back'); ?>
            </a>
        </div>
        <p class="text-gray-600 mt-2">
            <?php echo Language::get('manage_and_track_guard_patrols'); ?> - Last 30 days
        </p>
    </div>

    <!-- Patrol Performance by Post -->
    <?php if (!empty($patrol_data) && !empty($posts)): ?>
        <div class="space-y-8">
            <?php foreach ($posts as $post): 
                $post_id = $post['id'];
                $post_info = $patrol_data[$post_id];
                $dates = $post_info['dates'];
            ?>
                <div class="bg-white rounded-lg shadow border border-gray-200 overflow-hidden">
                    <!-- Post Header -->
                    <div class="bg-gradient-to-r from-blue-600 to-blue-700 p-4 text-white">
                        <div class="flex items-center justify-between">
                            <div>
                                <h2 class="text-xl font-bold"><?php echo htmlspecialchars($post['name']); ?></h2>
                                <p class="text-blue-100 text-sm mt-1">
                                    <i class="fas fa-map-marker-alt mr-2"></i><?php echo htmlspecialchars($post['location']); ?>
                                </p>
                            </div>
                            <span class="bg-blue-800 px-3 py-1 rounded-full text-sm font-semibold">
                                <?php echo Language::get('patrols'); ?>
                            </span>
                        </div>
                    </div>

                    <!-- Post Content -->
                    <div class="p-6">
                        <?php if (empty($dates)): ?>
                            <div class="text-center py-8">
                                <i class="fas fa-inbox text-4xl text-gray-300 mb-3"></i>
                                <p class="text-gray-500">No patrol records for this post yet</p>
                            </div>
                        <?php else: ?>
                            <?php 
                                // Sort dates in descending order (most recent first)
                                krsort($dates);
                                $display_dates = array_slice($dates, 0, 7, true); // Show last 7 days
                            ?>
                            
                            <?php foreach ($display_dates as $date => $hours): ?>
                                <div class="mb-8">
                                    <h3 class="text-lg font-semibold text-gray-800 mb-3">
                                        <?php echo date('l, F j, Y', strtotime($date)); ?>
                                    </h3>

                                    <!-- Hourly Grid (24-hour) -->
                                    <div class="grid grid-cols-6 md:grid-cols-12 gap-2">
                                        <?php for ($h = 0; $h < 24; $h++): 
                                            $hour_data = $hours[$h];
                                            $status = $hour_data['status'];
                                            $score = $hour_data['score'];
                                            $completion = $hour_data['completion'];
                                            $scans = $hour_data['scans'];
                                            
                                            // Determine colors based on status
                                            if ($status === 'completed' || $status === 'Completed') {
                                                $color_class = 'bg-green-500 hover:bg-green-600';
                                                $text_status = 'Complete';
                                            } elseif ($status === 'incomplete' || $status === 'Incomplete') {
                                                $color_class = 'bg-yellow-400 hover:bg-yellow-500';
                                                $text_status = 'Incomplete';
                                            } else {
                                                $color_class = 'bg-red-500 hover:bg-red-600';
                                                $text_status = 'Missed';
                                            }
                                            
                                            $hour_str = str_pad($h, 2, '0', STR_PAD_LEFT);
                                        ?>
                                            <div class="text-center">
                                                <div class="<?php echo $color_class; ?> text-white rounded-lg p-3 cursor-pointer transition transform hover:scale-105 group relative" 
                                                     title="<?php echo $hour_str; ?>:00 - <?php echo $text_status; ?> (Score: <?php echo $score; ?>/8)">
                                                    <div class="font-bold text-sm"><?php echo $hour_str; ?></div>
                                                    <div class="text-xs font-semibold"><?php echo $score; ?>/8</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>
                                                        Score: <?php echo $score; ?>/8<br>
                                                        Completion: <?php echo $completion; ?>%<br>
                                                        Scans: <?php echo $scans; ?>/8
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endfor; ?>
                                    </div>

                                    <!-- Legend -->
                                    <div class="flex items-center gap-4 mt-4 text-sm flex-wrap">
                                        <div class="flex items-center gap-2">
                                            <div class="w-4 h-4 bg-green-500 rounded"></div>
                                            <span class="text-gray-700"><?php echo Language::get('patrol_completed'); ?> (8/8)</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"><?php echo Language::get('patrol_incomplete'); ?> (4-7/8)</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"><?php echo Language::get('patrol_missed'); ?> (0-3/8)</span>
                                        </div>
                                    </div>

                                    <!-- Daily Stats -->
                                    <?php 
                                        $daily_score = 0;
                                        $max_daily_score = 192; // 24 hours * 8 points max
                                        $completed_hours = 0;
                                        
                                        foreach ($hours as $h_data) {
                                            $daily_score += $h_data['score'];
                                            if ($h_data['status'] === 'completed' || $h_data['status'] === 'Completed') {
                                                $completed_hours++;
                                            }
                                        }
                                        $daily_completion_percent = ($daily_score / $max_daily_score) * 100;
                                        $completion_percent = round($daily_completion_percent, 1);
                                    ?>
                                    <div class="mt-4 p-4 bg-gray-50 rounded-lg border border-gray-200">
                                        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-3">
                                            <div>
                                                <span class="text-xs font-semibold text-gray-600 uppercase"><?php echo Language::get('patrol_score'); ?></span>
                                                <p class="text-2xl font-bold text-gray-800"><?php echo $daily_score; ?><span class="text-sm text-gray-600">/<?php echo $max_daily_score; ?></span></p>
                                            </div>
                                            <div>
                                                <span class="text-xs font-semibold text-gray-600 uppercase"><?php echo Language::get('completion_percentage'); ?></span>
                                                <p class="text-2xl font-bold text-gray-800"><?php echo $completion_percent; ?><span class="text-sm text-gray-600">%</span></p>
                                            </div>
                                            <div>
                                                <span class="text-xs font-semibold text-gray-600 uppercase"><?php echo Language::get('patrol_completed'); ?></span>
                                                <p class="text-2xl font-bold text-green-600"><?php echo $completed_hours; ?><span class="text-sm text-gray-600">/24</span></p>
                                            </div>
                                            <div>
                                                <span class="text-xs font-semibold text-gray-600 uppercase"><?php echo Language::get('patrol_missed'); ?></span>
                                                <p class="text-2xl font-bold text-red-600"><?php echo (24 - $completed_hours); ?><span class="text-sm text-gray-600">/24</span></p>
                                            </div>
                                        </div>
                                        <div class="w-full bg-gray-200 rounded-full h-2.5 overflow-hidden">
                                            <div class="h-full transition-all <?php 
                                                echo $completion_percent >= 80 ? 'bg-green-500' : ($completion_percent >= 50 ? 'bg-yellow-500' : 'bg-red-500');
                                            ?>" style="width: <?php echo $completion_percent; ?>%"></div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php else: ?>
        <div class="bg-white rounded-lg shadow border border-gray-200 p-12 text-center">
            <i class="fas fa-inbox text-5xl text-gray-300 mb-4"></i>
            <p class="text-gray-500 text-lg"><?php echo $auth->lang('no_posts_available'); ?></p>
            <p class="text-gray-400 text-sm mt-2">Contact your administrator to add posts to your account</p>
        </div>
    <?php endif; ?>
</div>

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