<?php
/**
 * Controllers - My Controls
 * View controls added by this controller in their zone
 */

$db = $GLOBALS['db'];

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

// Get controller's zone
$zone = $db->fetch("SELECT * FROM zones WHERE assigned_to = ?", [$_SESSION['user_id']]);

// Get controls added by this controller in their zone
$filters = [
    'order' => $_GET['order'] ?? 'created_at',
    'sort' => $_GET['sort'] ?? 'desc',
    'search' => $_GET['search'] ?? ''
];

$query = "SELECT c.*, p.name as post_name, p.location
          FROM controls c
          JOIN posts p ON c.post_id = p.id
          WHERE p.zone_id = ? AND c.conducted_by = ?";
$params = [$zone ? $zone['id'] : 0, $_SESSION['user_id']];

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

// Order and sort
$allowedColumns = ['created_at', 'type', 'rating'];
$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-blue-600 to-blue-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>My Control Records
                    </h1>
                    <p class="text-blue-100 mt-2">Controls added in <?php echo $zone ? htmlspecialchars($zone['name']) : 'your zone'; ?></p>
                </div>
                <div class="text-right">
                    <div class="text-5xl font-bold text-blue-100"><?php echo count($controls); ?></div>
                    <p class="text-blue-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="controllers-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-blue-500 transition">
                    <button type="submit" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-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="controllers-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-blue-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="controllers-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-blue-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): 
                // Determine color scheme for rating
                $ratingColor = match($control['rating']) {
                    'excellent' => 'bg-green-100 border-green-300 text-green-900',
                    'good' => 'bg-blue-100 border-blue-300 text-blue-900',
                    'fair' => 'bg-yellow-100 border-yellow-300 text-yellow-900',
                    'poor' => 'bg-red-100 border-red-300 text-red-900',
                    default => 'bg-gray-100 border-gray-300 text-gray-900'
                };
                
                $ratingIcon = match($control['rating']) {
                    'excellent' => 'fa-star',
                    'good' => 'fa-thumbs-up',
                    'fair' => 'fa-minus-circle',
                    'poor' => 'fa-thumbs-down',
                    default => 'fa-question-circle'
                };
            ?>
                <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-blue-50 to-blue-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-blue-600 mr-2"></i>
                                    <?php echo htmlspecialchars($control['type']); ?> Control
                                </h3>
                                <p class="text-sm text-gray-600 mt-1">
                                    <i class="fas fa-map-pin mr-1"></i>
                                    Post: <?php echo htmlspecialchars($control['post_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($control['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-blue-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 Type -->
                        <div class="flex gap-3">
                            <i class="fas fa-list text-blue-600 mt-1 flex-shrink-0"></i>
                            <div>
                                <p class="text-xs font-bold text-gray-600 uppercase">Type</p>
                                <p class="text-gray-800 font-semibold"><?php echo htmlspecialchars($control['type']); ?></p>
                            </div>
                        </div>

                        <!-- Findings (Preview) -->
                        <?php if (!empty($control['findings'])): ?>
                            <div class="flex gap-3">
                                <i class="fas fa-search text-blue-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-blue-600 hover:bg-blue-50 border border-blue-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">Controls added in your zone 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-blue-600 to-blue-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-blue-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-blue-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');
    
    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[control.rating] || ratingColors['fair'];
    
    content.innerHTML = `
        <div class="space-y-6">
            <!-- Control Type 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">Control Type</p>
                    <p class="text-2xl font-bold text-gray-900">${control.type}</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>${control.rating.toUpperCase()}
                </span>
            </div>

            <!-- Post 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">Post</p>
                    <p class="font-semibold text-gray-800">${control.post_name}</p>
                </div>
                <div class="bg-gray-50 rounded-lg p-4">
                    <p class="text-xs font-bold text-gray-600 uppercase mb-2">Date</p>
                    <p class="font-semibold text-gray-800">${new Date(control.created_at).toLocaleString()}</p>
                </div>
            </div>

            <!-- Findings -->
            <div class="bg-gray-50 rounded-lg p-4">
                <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'; ?>
