<?php
/**
 * Controllers - My Posts
 * View posts in the controller's assigned 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 posts in this controller's zone
$filters = [
    'order' => $_GET['order'] ?? 'name',
    'sort' => $_GET['sort'] ?? 'asc',
    'search' => $_GET['search'] ?? ''
];

$query = "SELECT p.* FROM posts p WHERE p.zone_id = ?";
$params = [$zone ? $zone['id'] : 0];

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

// Order and sort
$allowedColumns = ['name', 'location', 'facility_type', 'surface_area'];
$order = in_array($filters['order'], $allowedColumns) ? $filters['order'] : 'name';
$sort = strtoupper($filters['sort']) === 'ASC' ? 'ASC' : 'DESC';
$query .= " ORDER BY p.$order $sort LIMIT 100";

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

// Get guard assignments for this zone
$guardsByPost = [];
foreach ($posts as $post) {
    $guards = $db->fetchAll(
        "SELECT u.id, u.name FROM guard_post_assignments gpa
         JOIN users u ON gpa.guard_id = u.id
         WHERE gpa.post_id = ? AND gpa.status = 'Active'",
        [$post['id']]
    );
    $guardsByPost[$post['id']] = $guards;
}

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-map-pin mr-3"></i>Posts in My Zone
                    </h1>
                    <p class="text-blue-100 mt-2"><?php echo $zone ? htmlspecialchars($zone['name']) : 'Zone'; ?></p>
                </div>
                <div class="text-right">
                    <div class="text-5xl font-bold text-blue-100"><?php echo count($posts); ?></div>
                    <p class="text-blue-200 text-lg">Total Posts</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-posts">
                    <input type="text" name="search" value="<?php echo htmlspecialchars($filters['search']); ?>" placeholder="Search posts..." 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-posts">
                    <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="name" <?php echo $filters['order'] === 'name' ? 'selected' : ''; ?>>Name</option>
                        <option value="location" <?php echo $filters['order'] === 'location' ? 'selected' : ''; ?>>Location</option>
                        <option value="facility_type" <?php echo $filters['order'] === 'facility_type' ? 'selected' : ''; ?>>Facility Type</option>
                    </select>
                </form>
            </div>

            <!-- Direction -->
            <div>
                <form method="GET" id="directionForm">
                    <input type="hidden" name="page" value="controllers-posts">
                    <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="asc" <?php echo $filters['sort'] === 'asc' ? 'selected' : ''; ?>>A-Z</option>
                        <option value="desc" <?php echo $filters['sort'] === 'desc' ? 'selected' : ''; ?>>Z-A</option>
                    </select>
                </form>
            </div>
        </div>
    </div>

    <!-- Posts Grid -->
    <?php if (!empty($posts)): ?>
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <?php foreach ($posts as $post): ?>
                <div class="bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden hover:shadow-xl transition-shadow">
                    <!-- Post Header -->
                    <div class="bg-gradient-to-r from-blue-50 to-blue-100 border-b border-gray-200 px-6 py-4">
                        <h3 class="text-2xl font-bold text-gray-900">
                            <i class="fas fa-map-pin text-blue-600 mr-2"></i>
                            <?php echo htmlspecialchars($post['name']); ?>
                        </h3>
                        <p class="text-sm text-gray-600 mt-1">
                            <i class="fas fa-map text-blue-500 mr-1"></i>
                            <?php echo htmlspecialchars($post['location']); ?>
                        </p>
                    </div>

                    <!-- Post Details -->
                    <div class="px-6 py-5 space-y-4">
                        <!-- Facility Type -->
                        <div class="flex gap-3">
                            <i class="fas fa-building text-blue-600 mt-1 flex-shrink-0"></i>
                            <div>
                                <p class="text-xs font-bold text-gray-600 uppercase">Facility Type</p>
                                <p class="text-gray-800 font-semibold"><?php echo htmlspecialchars($post['facility_type']); ?></p>
                            </div>
                        </div>

                        <!-- Assigned Guards -->
                        <div class="flex gap-3">
                            <i class="fas fa-user-shield text-blue-600 mt-1 flex-shrink-0"></i>
                            <div class="w-full">
                                <p class="text-xs font-bold text-gray-600 uppercase mb-2">Assigned Guards</p>
                                <?php if (!empty($guardsByPost[$post['id']])): ?>
                                    <div class="space-y-1">
                                        <?php foreach ($guardsByPost[$post['id']] as $guard): ?>
                                            <span class="inline-block px-3 py-1 bg-blue-100 text-blue-900 rounded-full text-sm font-semibold mr-2">
                                                <?php echo htmlspecialchars($guard['name']); ?>
                                            </span>
                                        <?php endforeach; ?>
                                    </div>
                                <?php else: ?>
                                    <p class="text-sm text-gray-500 italic">No guards assigned</p>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Surface Area -->
                        <?php if (!empty($post['surface_area'])): ?>
                            <div class="flex gap-3">
                                <i class="fas fa-expand text-blue-600 mt-1 flex-shrink-0"></i>
                                <div>
                                    <p class="text-xs font-bold text-gray-600 uppercase">Surface Area</p>
                                    <p class="text-gray-800 font-semibold"><?php echo htmlspecialchars($post['surface_area']); ?> m²</p>
                                </div>
                            </div>
                        <?php endif; ?>

                        <!-- Assigned Hours -->
                        <?php if (!empty($post['assigned_hours'])): ?>
                            <div class="flex gap-3">
                                <i class="fas fa-clock text-blue-600 mt-1 flex-shrink-0"></i>
                                <div>
                                    <p class="text-xs font-bold text-gray-600 uppercase">Assigned Hours</p>
                                    <p class="text-gray-800 font-semibold"><?php echo htmlspecialchars($post['assigned_hours']); ?> hours/week</p>
                                </div>
                            </div>
                        <?php endif; ?>

                        <!-- Action Button -->
                        <div class="pt-4 border-t border-gray-200">
                            <button onclick="viewPostDetails(<?php echo htmlspecialchars(json_encode($post)); ?>)" 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-eye mr-2"></i>View Full Details
                            </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-map-pin text-5xl text-gray-300 mb-4"></i>
            <p class="text-gray-600 font-medium text-lg">No posts found in your zone</p>
            <p class="text-gray-500 text-sm mt-2">Posts will appear here once they are assigned to your zone</p>
        </div>
    <?php endif; ?>
</div>

<!-- Post Details Modal -->
<div id="postModal" 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 id="postModalTitle" class="text-2xl font-bold">Post Details</h2>
            <button onclick="closePostModal()" 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="postContent" 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="closePostModal()" 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 viewPostDetails(post) {
    const modal = document.getElementById('postModal');
    const content = document.getElementById('postContent');
    
    modal.classList.remove('hidden');
    document.getElementById('postModalTitle').textContent = post.name;
    
    content.innerHTML = `
        <div class="space-y-6">
            <!-- Location -->
            <div class="border-l-4 border-blue-600 pl-4">
                <p class="text-xs font-bold text-gray-600 uppercase">Location</p>
                <p class="text-2xl font-bold text-gray-900 mt-1">${post.location}</p>
            </div>

            <!-- Details Grid -->
            <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">Facility Type</p>
                    <p class="text-gray-800 font-semibold">${post.facility_type || 'N/A'}</p>
                </div>
                <div class="bg-gray-50 rounded-lg p-4">
                    <p class="text-xs font-bold text-gray-600 uppercase mb-2">Surface Area</p>
                    <p class="text-gray-800 font-semibold">${post.surface_area ? post.surface_area + ' m²' : 'N/A'}</p>
                </div>
                <div class="bg-gray-50 rounded-lg p-4">
                    <p class="text-xs font-bold text-gray-600 uppercase mb-2">Assigned Hours</p>
                    <p class="text-gray-800 font-semibold">${post.assigned_hours ? post.assigned_hours + ' hours/week' : 'N/A'}</p>
                </div>
                <div class="bg-gray-50 rounded-lg p-4">
                    <p class="text-xs font-bold text-gray-600 uppercase mb-2">Owner</p>
                    <p class="text-gray-800 font-semibold">${post.owner_name ? post.owner_name : 'N/A'}</p>
                </div>
            </div>

            <!-- Owner Contact -->
            ${post.owner_phone ? `
            <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">Owner Contact</p>
                <p class="text-blue-900 font-semibold">${post.owner_phone}</p>
                ${post.owner_address ? `<p class="text-blue-800 text-sm mt-2">${post.owner_address}</p>` : ''}
            </div>
            ` : ''}

            <!-- Description -->
            ${post.description ? `
            <div class="bg-gray-50 rounded-lg p-4">
                <p class="text-xs font-bold text-gray-600 uppercase mb-2">Description</p>
                <p class="text-gray-800">${post.description}</p>
            </div>
            ` : ''}
        </div>
    `;
}

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

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