<?php
/**
 * Guards - My Controls
 * View controls conducted by supervisors/controllers at guard's post
 */

$db = $GLOBALS['db'];

// 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();
}

// 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 controls for this guard's post
$filters = [
    'order' => $_GET['order'] ?? 'created_at',
    'sort' => $_GET['sort'] ?? 'desc',
    'search' => $_GET['search'] ?? ''
];

$query = "SELECT c.*, p.name as post_name, u.name as controller_name
          FROM guards_controls c
          JOIN posts p ON c.post_id = p.id
          JOIN users u ON c.controller_id = u.id
          WHERE c.guard_id = ?";
$params = [$_SESSION['user_id']];

// Search filter
if (!empty($filters['search'])) {
    $query .= " AND (c.notes LIKE ? OR u.name LIKE ?)";
    $search = '%' . $filters['search'] . '%';
    array_push($params, $search, $search);
}

// Order and sort
$allowedColumns = ['created_at', 'total_score', 'status'];
$order = in_array($filters['order'], $allowedColumns) ? $filters['order'] : 'created_at';
$sort = strtoupper($filters['sort']) === 'ASC' ? 'ASC' : 'DESC';
$query .= " ORDER BY c.$order $sort LIMIT 100";

$controls = $db->fetchAll($query, $params);

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="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-clipboard-check mr-3"></i>Control Records
                    </h1>
                    <p class="text-green-100 mt-2">Controls conducted at <?php echo $assignment ? htmlspecialchars($assignment['post_name']) : 'your assigned post'; ?></p>
                </div>
                <div class="text-right">
                    <div class="text-5xl font-bold text-green-100"><?php echo count($controls); ?></div>
                    <p class="text-green-200 text-lg">Total Controls</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters and Search -->
    <div class="bg-white rounded-xl shadow-lg border border-gray-200 p-6 mb-8">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <!-- Search -->
            <div class="md:col-span-2">
                <form method="GET" class="flex gap-2">
                    <input type="hidden" name="page" value="guards-controls">
                    <input type="text" name="search" value="<?php echo htmlspecialchars($filters['search']); ?>" placeholder="Search controls..." class="flex-1 px-4 py-2 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-green-500 transition">
                    <button type="submit" class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition font-semibold">
                        <i class="fas fa-search mr-2"></i>Search
                    </button>
                </form>
            </div>

            <!-- Sort -->
            <div>
                <form method="GET" class="flex gap-2" id="sortForm">
                    <input type="hidden" name="page" value="guards-controls">
                    <input type="hidden" name="search" value="<?php echo htmlspecialchars($filters['search']); ?>">
                    <select name="order" onchange="document.getElementById('sortForm').submit()" class="flex-1 px-4 py-2 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-green-500 transition">
                        <option value="created_at" <?php echo $filters['order'] === 'created_at' ? 'selected' : ''; ?>>Date</option>
                        <option value="type" <?php echo $filters['order'] === 'type' ? 'selected' : ''; ?>>Type</option>
                        <option value="rating" <?php echo $filters['order'] === 'rating' ? 'selected' : ''; ?>>Rating</option>
                    </select>
                </form>
            </div>

            <!-- Direction -->
            <div>
                <form method="GET" id="directionForm">
                    <input type="hidden" name="page" value="guards-controls">
                    <input type="hidden" name="order" value="<?php echo htmlspecialchars($filters['order']); ?>">
                    <input type="hidden" name="search" value="<?php echo htmlspecialchars($filters['search']); ?>">
                    <select name="sort" onchange="document.getElementById('directionForm').submit()" class="w-full px-4 py-2 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-green-500 transition">
                        <option value="desc" <?php echo $filters['sort'] === 'desc' ? 'selected' : ''; ?>>Newest First</option>
                        <option value="asc" <?php echo $filters['sort'] === 'asc' ? 'selected' : ''; ?>>Oldest First</option>
                    </select>
                </form>
            </div>
        </div>
    </div>

    <!-- Controls List -->
    <?php if (!empty($controls)): ?>
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <?php foreach ($controls as $control): 
                // Calculate rating from total_score
                $score = intval($control['total_score'] ?? 0);
                if ($score >= 85) {
                    $rating = 'excellent';
                    $ratingColor = 'bg-green-100 border-green-300 text-green-900';
                    $ratingIcon = 'fa-star';
                } elseif ($score >= 70) {
                    $rating = 'good';
                    $ratingColor = 'bg-blue-100 border-blue-300 text-blue-900';
                    $ratingIcon = 'fa-thumbs-up';
                } elseif ($score >= 55) {
                    $rating = 'fair';
                    $ratingColor = 'bg-yellow-100 border-yellow-300 text-yellow-900';
                    $ratingIcon = 'fa-minus-circle';
                } else {
                    $rating = 'poor';
                    $ratingColor = 'bg-red-100 border-red-300 text-red-900';
                    $ratingIcon = 'fa-thumbs-down';
                }
            ?>
                <div class="bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden hover:shadow-xl transition-shadow">
                    <!-- Control Header -->
                    <div class="bg-gradient-to-r from-green-50 to-green-100 border-b border-gray-200 px-6 py-4">
                        <div class="flex items-start justify-between">
                            <div>
                                <h3 class="text-lg font-bold text-gray-900">
                                    <i class="fas fa-clipboard-check text-green-600 mr-2"></i>
                                    Control Record
                                </h3>
                                <p class="text-sm text-gray-600 mt-1">
                                    <i class="fas fa-user mr-1"></i>
                                    By: <?php echo htmlspecialchars($control['controller_name']); ?>
                                </p>
                            </div>
                            <span class="px-4 py-2 border-2 rounded-full text-xs font-bold <?php echo $ratingColor; ?>">
                                <i class="fas <?php echo $ratingIcon; ?> mr-1"></i>
                                <?php echo ucfirst($rating); ?>
                            </span>
                        </div>
                    </div>

                    <!-- Control Details -->
                    <div class="px-6 py-5 space-y-4">
                        <!-- Date -->
                        <div class="flex gap-3">
                            <i class="fas fa-calendar text-green-600 mt-1 flex-shrink-0"></i>
                            <div>
                                <p class="text-xs font-bold text-gray-600 uppercase">Date</p>
                                <p class="text-gray-800 font-semibold"><?php echo date('Y-m-d H:i', strtotime($control['created_at'])); ?></p>
                            </div>
                        </div>

                        <!-- Control Metrics -->
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <p class="text-xs font-bold text-gray-600 uppercase">Attendance</p>
                                <p class="text-lg font-bold text-gray-900"><?php echo intval($control['attendance_punctuality'] ?? 0); ?>%</p>
                            </div>
                            <div>
                                <p class="text-xs font-bold text-gray-600 uppercase">Uniform</p>
                                <p class="text-lg font-bold text-gray-900"><?php echo intval($control['uniform_presentation'] ?? 0); ?>%</p>
                            </div>
                            <div>
                                <p class="text-xs font-bold text-gray-600 uppercase">Patrol Discipline</p>
                                <p class="text-lg font-bold text-gray-900"><?php echo intval($control['patrol_reporting_discipline'] ?? 0); ?>%</p>
                            </div>
                            <div>
                                <p class="text-xs font-bold text-gray-600 uppercase">Client Feedback</p>
                                <p class="text-lg font-bold text-gray-900"><?php echo intval($control['client_feedback'] ?? 0); ?>%</p>
                            </div>
                        </div>

                        <!-- Findings (Preview) -->
                        <?php if (!empty($control['findings'])): ?>
                            <div class="flex gap-3">
                                <i class="fas fa-search text-green-600 mt-1 flex-shrink-0"></i>
                                <div>
                                    <p class="text-xs font-bold text-gray-600 uppercase">Findings Summary</p>
                                    <p class="text-gray-700 line-clamp-2"><?php echo htmlspecialchars(substr($control['findings'], 0, 80)); ?>...</p>
                                </div>
                            </div>
                        <?php endif; ?>

                        <!-- Issues Found -->
                        <?php if (!empty($control['issues_found'])): ?>
                            <div class="flex gap-3 bg-red-50 border border-red-200 rounded-lg p-4">
                                <i class="fas fa-exclamation-circle text-red-600 mt-0.5 flex-shrink-0"></i>
                                <div>
                                    <p class="text-xs font-bold text-red-700 uppercase">Issues</p>
                                    <p class="text-red-800 text-sm font-semibold"><?php echo htmlspecialchars(substr($control['issues_found'], 0, 50)); ?></p>
                                </div>
                            </div>
                        <?php else: ?>
                            <div class="flex gap-3 bg-green-50 border border-green-200 rounded-lg p-4">
                                <i class="fas fa-check-circle text-green-600 mt-0.5 flex-shrink-0"></i>
                                <p class="text-green-800 text-sm font-semibold">No issues found</p>
                            </div>
                        <?php endif; ?>

                        <!-- View Details Button -->
                        <div class="pt-4 border-t border-gray-200">
                            <button onclick="viewControlDetails(<?php echo htmlspecialchars(json_encode($control)); ?>)" class="w-full px-4 py-2 text-green-600 hover:bg-green-50 border border-green-300 rounded-lg transition font-semibold">
                                <i class="fas fa-arrow-right mr-2"></i>View Full Report
                            </button>
                        </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-clipboard-check text-5xl text-gray-300 mb-4"></i>
            <p class="text-gray-600 font-medium text-lg">No controls found</p>
            <p class="text-gray-500 text-sm mt-2">Control records for your post will appear here</p>
        </div>
    <?php endif; ?>
</div>

<!-- Control Details Modal -->
<div id="controlModal" 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 class="text-2xl font-bold">Control Report</h2>
            <button onclick="closeControlModal()" 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="controlContent" class="p-8 space-y-6">
            <!-- Loading -->
            <div class="text-center py-8">
                <i class="fas fa-spinner fa-spin text-green-600 text-3xl"></i>
            </div>
        </div>

        <!-- Footer -->
        <div class="sticky bottom-0 bg-gray-50 border-t border-gray-200 p-6 flex justify-end gap-3">
            <button onclick="closeControlModal()" 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>
function viewControlDetails(control) {
    const modal = document.getElementById('controlModal');
    const content = document.getElementById('controlContent');
    
    modal.classList.remove('hidden');
    
    // Calculate rating from total_score
    let ratingValue = 'fair';
    const score = parseInt(control.total_score || 0);
    if (score >= 85) {
        ratingValue = 'excellent';
    } else if (score >= 70) {
        ratingValue = 'good';
    } else if (score >= 55) {
        ratingValue = 'fair';
    } else {
        ratingValue = 'poor';
    }
    
    const ratingColors = {
        'excellent': { bg: 'bg-green-100', text: 'text-green-900', icon: 'fa-star' },
        'good': { bg: 'bg-blue-100', text: 'text-blue-900', icon: 'fa-thumbs-up' },
        'fair': { bg: 'bg-yellow-100', text: 'text-yellow-900', icon: 'fa-minus-circle' },
        'poor': { bg: 'bg-red-100', text: 'text-red-900', icon: 'fa-thumbs-down' }
    };
    
    const rating = ratingColors[ratingValue] || ratingColors['fair'];
    
    content.innerHTML = `
        <div class="space-y-6">
            <!-- Control Score and Rating -->
            <div class="flex items-center justify-between border-b-2 border-gray-200 pb-4">
                <div>
                    <p class="text-xs font-bold text-gray-600 uppercase">Overall Score</p>
                    <p class="text-2xl font-bold text-gray-900">${control.total_score}%</p>
                </div>
                <span class="px-6 py-3 ${rating.bg} ${rating.text} rounded-xl font-bold text-lg">
                    <i class="fas ${rating.icon} mr-2"></i>${ratingValue.toUpperCase()}
                </span>
            </div>

            <!-- Conductor and Date -->
            <div class="grid grid-cols-2 gap-4">
                <div class="bg-gray-50 rounded-lg p-4">
                    <p class="text-xs font-bold text-gray-600 uppercase mb-2">Conducted By</p>
                    <p class="font-semibold text-gray-800">${control.controller_name}</p>
                </div>
                <div class="bg-gray-50 rounded-lg p-4">
                    <p class="text-xs font-bold text-gray-600 uppercase mb-2">Post</p>
                    <p class="font-semibold text-gray-800">${control.post_name}</p>
                </div>
            </div>

            <!-- Control Metrics Grid -->
            <div class="grid grid-cols-2 gap-4">
                <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                    <p class="text-xs font-bold text-blue-600 uppercase mb-2">Attendance</p>
                    <p class="text-2xl font-bold text-blue-900">${control.attendance_punctuality || 0}%</p>
                </div>
                <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                    <p class="text-xs font-bold text-green-600 uppercase mb-2">Uniform</p>
                    <p class="text-2xl font-bold text-green-900">${control.uniform_presentation || 0}%</p>
                </div>
                <div class="bg-purple-50 border border-purple-200 rounded-lg p-4">
                    <p class="text-xs font-bold text-purple-600 uppercase mb-2">Patrol</p>
                    <p class="text-2xl font-bold text-purple-900">${control.patrol_reporting_discipline || 0}%</p>
                </div>
                <div class="bg-orange-50 border border-orange-200 rounded-lg p-4">
                    <p class="text-xs font-bold text-orange-600 uppercase mb-2">Feedback</p>
                    <p class="text-2xl font-bold text-orange-900">${control.client_feedback || 0}%</p>
                </div>
            </div>

            <!-- Notes -->
            ${control.notes ? `
            <div class="bg-gray-50 rounded-lg p-4">
                <p class="text-xs font-bold text-gray-600 uppercase mb-2">Notes</p>
                <p class="text-gray-800">${control.notes}</p>
            </div>
            ` : ''}
                <p class="text-xs font-bold text-gray-600 uppercase mb-2">Findings</p>
                <p class="text-gray-800">${control.findings || 'No findings recorded'}</p>
            </div>

            <!-- Issues Found -->
            <div class="bg-gray-50 rounded-lg p-4">
                <p class="text-xs font-bold text-gray-600 uppercase mb-2">Issues Found</p>
                <p class="text-gray-800">${control.issues_found ? `<span class="font-semibold text-red-600">${control.issues_found}</span>` : '<span class="font-semibold text-green-600">No issues found</span>'}</p>
            </div>

            <!-- Recommendations -->
            ${control.recommendations ? `
            <div class="bg-blue-50 rounded-lg p-4 border border-blue-200">
                <p class="text-xs font-bold text-blue-700 uppercase mb-2">Recommendations</p>
                <p class="text-blue-900">${control.recommendations}</p>
            </div>
            ` : ''}
        </div>
    `;
}

function closeControlModal() {
    document.getElementById('controlModal').classList.add('hidden');
}
</script>

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