<?php
/**
 * Guard to Post Assignment Page
 * SSCI Office Platform - Assign guards to security posts by zone or individually
 */

$auth = $GLOBALS['auth'];
$db = $GLOBALS['db'];
$pageTitle = trans('assign_guards_to_posts') ?? 'Assign Guards to Posts';

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

// Get all zones for filtering
$zones = ['Buea', 'Limbe', 'Douala', 'Tiko', 'Yaounde', 'Bamenda', 'Kumba'];

// Get filter parameters
$selectedZone = $_GET['zone'] ?? '';
$selectedPost = $_GET['post'] ?? '';

// Get posts (optionally filtered by zone)
$postsQuery = "SELECT id, name, zone FROM posts WHERE status = 'Active'";
$postsParams = [];
if ($selectedZone) {
    $postsQuery .= " AND zone = ?";
    $postsParams[] = $selectedZone;
}
$postsQuery .= " ORDER BY zone, name";
$posts = $db->fetchAll($postsQuery, $postsParams);

// Get guards (optionally filtered by zone)
$guardsQuery = "SELECT u.id, u.name, u.email, u.phone, s.staff_id, s.zone 
                FROM users u 
                LEFT JOIN staff s ON u.id = s.user_id 
                WHERE u.role = 'guard'";
$guardsParams = [];
if ($selectedZone) {
    $guardsQuery .= " AND (s.zone = ? OR s.zone IS NULL)";
    $guardsParams[] = $selectedZone;
}
$guardsQuery .= " ORDER BY u.name";
$guards = $db->fetchAll($guardsQuery, $guardsParams);

// Get current assignments for the selected post
$currentAssignments = [];
if ($selectedPost) {
    $currentAssignments = $db->fetchAll(
        "SELECT gpa.*, u.name, s.staff_id, s.zone 
         FROM guard_post_assignments gpa
         JOIN users u ON gpa.guard_id = u.id
         LEFT JOIN staff s ON u.id = s.user_id
         WHERE gpa.post_id = ? AND gpa.status = 'Active'
         ORDER BY u.name",
        [$selectedPost]
    );
}
?>

<div class="container mx-auto px-4 py-8 max-w-6xl">
    <!-- Page Header -->
    <div class="mb-8">
        <h1 class="text-4xl font-bold text-gray-800 mb-2">
            <i class="fas fa-user-check text-blue-600 mr-3"></i><?php echo $pageTitle; ?>
        </h1>
        <p class="text-gray-600">Assign security guards to posts and manage their deployments by zone</p>
    </div>

    <!-- Filter Section -->
    <div class="bg-white rounded-lg shadow p-6 mb-8">
        <h2 class="text-xl font-bold text-gray-800 mb-4">
            <i class="fas fa-filter text-blue-600 mr-2"></i>Filter & Select
        </h2>
        
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
            <!-- Zone Filter -->
            <div>
                <label class="block text-gray-700 font-semibold mb-2">Zone</label>
                <select id="zoneFilter" onchange="filterByZone()" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200">
                    <option value="">All Zones</option>
                    <?php foreach ($zones as $zone): ?>
                        <option value="<?php echo $zone; ?>" <?php echo ($selectedZone === $zone) ? 'selected' : ''; ?>><?php echo $zone; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- Post Selection -->
            <div>
                <label class="block text-gray-700 font-semibold mb-2">Select Post</label>
                <select id="postSelect" onchange="selectPost()" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200">
                    <option value="">Choose a post...</option>
                    <?php foreach ($posts as $post): ?>
                        <option value="<?php echo $post['id']; ?>" data-zone="<?php echo htmlspecialchars($post['zone']); ?>" 
                                <?php echo ($selectedPost == $post['id']) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($post['name']); ?> (<?php echo htmlspecialchars($post['zone']); ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- Action Button -->
            <div class="flex items-end">
                <button type="button" onclick="openAssignModal()" class="w-full bg-green-600 text-white px-4 py-3 rounded-lg hover:bg-green-700 transition font-semibold flex items-center justify-center">
                    <i class="fas fa-plus mr-2"></i>Assign Guard
                </button>
            </div>
        </div>
    </div>

    <!-- Main Content Grid -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- Available Guards Column -->
        <div class="lg:col-span-1">
            <div class="bg-white rounded-lg shadow p-6 sticky top-8">
                <h2 class="text-xl font-bold text-gray-800 mb-4">
                    <i class="fas fa-users text-blue-600 mr-2"></i>Available Guards
                </h2>

                <div class="space-y-2 max-h-96 overflow-y-auto">
                    <?php if (empty($guards)): ?>
                        <p class="text-gray-500 text-center py-8">No guards available</p>
                    <?php else: ?>
                        <?php foreach ($guards as $guard): ?>
                            <div class="border border-gray-200 rounded-lg p-3 hover:bg-blue-50 cursor-pointer transition" 
                                 onclick="selectGuard(<?php echo $guard['id']; ?>, '<?php echo htmlspecialchars($guard['name']); ?>')">
                                <div class="font-semibold text-gray-800"><?php echo htmlspecialchars($guard['name']); ?></div>
                                <div class="text-xs text-gray-500">
                                    <?php echo $guard['staff_id'] ?? 'N/A'; ?> 
                                    <?php if ($guard['zone']): ?>
                                        • <?php echo $guard['zone']; ?>
                                    <?php endif; ?>
                                </div>
                                <div class="text-xs text-gray-600"><?php echo htmlspecialchars($guard['email']); ?></div>
                                <?php if ($guard['phone']): ?>
                                    <div class="text-xs text-gray-600"><?php echo htmlspecialchars($guard['phone']); ?></div>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Current Assignments Column -->
        <div class="lg:col-span-2">
            <div class="bg-white rounded-lg shadow p-6">
                <h2 class="text-xl font-bold text-gray-800 mb-4">
                    <i class="fas fa-list text-blue-600 mr-2"></i>
                    <?php 
                    if ($selectedPost) {
                        $selectedPostData = array_filter($posts, fn($p) => $p['id'] == $selectedPost);
                        $selectedPostData = array_shift($selectedPostData);
                        echo 'Assigned Guards - ' . htmlspecialchars($selectedPostData['name'] ?? 'Unknown Post');
                    } else {
                        echo 'Select a post to view assignments';
                    }
                    ?>
                </h2>

                <?php if (!$selectedPost): ?>
                    <div class="text-center py-12 text-gray-500">
                        <i class="fas fa-inbox text-4xl mb-4 opacity-50"></i>
                        <p>Select a post from the filter above to view and manage guard assignments</p>
                    </div>
                <?php elseif (empty($currentAssignments)): ?>
                    <div class="text-center py-12 text-gray-500">
                        <i class="fas fa-user-check text-4xl mb-4 opacity-50"></i>
                        <p>No guards currently assigned to this post</p>
                        <button type="button" onclick="openAssignModal()" class="mt-4 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition">
                            Assign First Guard
                        </button>
                    </div>
                <?php else: ?>
                    <div class="space-y-4">
                        <?php foreach ($currentAssignments as $assignment): ?>
                            <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition">
                                <div class="flex justify-between items-start mb-2">
                                    <div>
                                        <h3 class="font-semibold text-gray-800"><?php echo htmlspecialchars($assignment['name']); ?></h3>
                                        <p class="text-sm text-gray-600">
                                            ID: <?php echo $assignment['staff_id'] ?? 'N/A'; ?>
                                            <?php if ($assignment['zone']): ?>
                                                | Zone: <?php echo $assignment['zone']; ?>
                                            <?php endif; ?>
                                        </p>
                                    </div>
                                    <button type="button" onclick="removeAssignment(<?php echo $assignment['id']; ?>)" class="text-red-600 hover:text-red-800 transition">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>

                                <div class="grid grid-cols-2 gap-4 text-sm">
                                    <div>
                                        <p class="text-gray-600">Assigned Date</p>
                                        <p class="font-semibold text-gray-800"><?php echo date('M d, Y', strtotime($assignment['assignment_start_date'])); ?></p>
                                    </div>
                                    <div>
                                        <p class="text-gray-600">Status</p>
                                        <span class="px-2 py-1 bg-green-100 text-green-700 rounded text-xs font-semibold">
                                            <?php echo ucfirst(strtolower($assignment['status'])); ?>
                                        </span>
                                    </div>
                                </div>

                                <?php if (!empty($assignment['notes'])): ?>
                                    <div class="mt-3 pt-3 border-t border-gray-200">
                                        <p class="text-gray-700 text-sm"><?php echo htmlspecialchars($assignment['notes']); ?></p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Assign Guard Modal -->
<div id="assignModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
    <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4 max-h-screen overflow-y-auto">
        <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-xl font-bold">
                <i class="fas fa-user-plus mr-2"></i>Assign Guard to Post
            </h2>
            <button type="button" onclick="closeAssignModal()" class="text-white hover:text-gray-200 transition">
                <i class="fas fa-times text-2xl"></i>
            </button>
        </div>

        <form onsubmit="submitAssignment(event)" class="p-6 space-y-4">
            <input type="hidden" id="postIdInput" value="">
            <input type="hidden" id="guardIdInput" value="">

            <!-- Guard Selection -->
            <div>
                <label class="block text-gray-700 font-semibold mb-2">Guard *</label>
                <input type="text" id="guardNameDisplay" readonly class="w-full px-4 py-3 border border-gray-300 rounded-lg bg-gray-100" placeholder="Click below to select">
                
                <div id="guardList" class="mt-3 border border-gray-300 rounded-lg max-h-64 overflow-y-auto">
                    <?php foreach ($guards as $guard): ?>
                        <div class="px-4 py-2 hover:bg-blue-50 cursor-pointer border-b border-gray-200 last:border-b-0 flex justify-between items-center"
                             onclick="selectGuardFromModal(<?php echo $guard['id']; ?>, '<?php echo htmlspecialchars(addslashes($guard['name'])); ?>')">
                            <div>
                                <div class="font-semibold text-gray-800"><?php echo htmlspecialchars($guard['name']); ?></div>
                                <div class="text-xs text-gray-600"><?php echo $guard['staff_id'] ?? 'N/A'; ?></div>
                            </div>
                            <i class="fas fa-check-circle text-blue-600 opacity-0 checkmark"></i>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Assignment Start Date -->
            <div>
                <label class="block text-gray-700 font-semibold mb-2">Assignment Start Date *</label>
                <input type="date" id="assignmentStartDate" required class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500">
            </div>

            <!-- Assignment End Date (Optional) -->
            <div>
                <label class="block text-gray-700 font-semibold mb-2">Assignment End Date (Optional)</label>
                <input type="date" id="assignmentEndDate" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500">
            </div>

            <!-- Notes -->
            <div>
                <label class="block text-gray-700 font-semibold mb-2">Notes</label>
                <textarea id="assignmentNotes" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" rows="3" placeholder="Any special notes or instructions..."></textarea>
            </div>

            <!-- Buttons -->
            <div class="flex gap-3 pt-4">
                <button type="button" onclick="closeAssignModal()" class="flex-1 px-4 py-3 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition font-semibold">
                    Cancel
                </button>
                <button type="submit" class="flex-1 px-4 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition font-semibold">
                    Assign Guard
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    // API Base URL for API calls
    const API_BASE_URL = '/ssci/public/api.php';

    // Set today's date as default for assignment start date
    document.getElementById('assignmentStartDate').valueAsDate = new Date();

    function filterByZone() {
        const zone = document.getElementById('zoneFilter').value;
        window.location.href = `?page=guards&action=assign&zone=${zone}`;
    }

    function selectPost() {
        const postId = document.getElementById('postSelect').value;
        if (postId) {
            window.location.href = `?page=guards&action=assign&zone=<?php echo $selectedZone; ?>&post=${postId}`;
        }
    }

    function selectGuard(guardId, guardName) {
        document.getElementById('guardIdInput').value = guardId;
        document.getElementById('guardNameDisplay').value = guardName;
        openAssignModal();
    }

    function selectGuardFromModal(guardId, guardName) {
        document.getElementById('guardIdInput').value = guardId;
        document.getElementById('guardNameDisplay').value = guardName;
        
        // Update checkmarks
        document.querySelectorAll('#guardList > div').forEach(el => {
            el.querySelector('.checkmark').classList.add('opacity-0');
        });
        event.target.closest('div').querySelector('.checkmark')?.classList.remove('opacity-0');
    }

    function openAssignModal() {
        const postId = document.getElementById('postSelect').value;
        if (!postId) {
            showToast('warning', 'Please select a post first');
            return;
        }
        document.getElementById('postIdInput').value = postId;
        document.getElementById('assignModal').classList.remove('hidden');
    }

    function closeAssignModal() {
        document.getElementById('assignModal').classList.add('hidden');
        document.getElementById('guardIdInput').value = '';
        document.getElementById('guardNameDisplay').value = '';
        document.getElementById('assignmentNotes').value = '';
    }

    function submitAssignment(event) {
        event.preventDefault();

        const postId = document.getElementById('postIdInput').value;
        const guardId = document.getElementById('guardIdInput').value;
        const startDate = document.getElementById('assignmentStartDate').value;
        const endDate = document.getElementById('assignmentEndDate').value;
        const notes = document.getElementById('assignmentNotes').value;

        if (!postId || !guardId || !startDate) {
            showToast('error', 'Please fill in all required fields');
            return;
        }

        const data = {
            post_id: postId,
            guard_id: guardId,
            assignment_start_date: startDate,
            assignment_end_date: endDate || null,
            notes: notes
        };

        fetch(`${API_BASE_URL}?endpoint=guards/assign-to-post`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                showToast('success', 'Guard assigned successfully!');
                closeAssignModal();
                // Reload page to see updated assignments
                setTimeout(() => location.reload(), 1000);
            } else {
                showToast('error', data.error || 'Failed to assign guard');
            }
        })
        .catch(err => {
            console.error('Error:', err);
            showToast('error', 'An error occurred. Please try again.');
        });
    }

    function removeAssignment(assignmentId) {
        if (!confirm('Are you sure you want to remove this assignment?')) {
            return;
        }

        fetch(`${API_BASE_URL}?endpoint=guards/remove-assignment&id=${assignmentId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({})
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                showToast('success', 'Assignment removed successfully');
                setTimeout(() => location.reload(), 1000);
            } else {
                showToast('error', data.error || 'Failed to remove assignment');
            }
        })
        .catch(err => {
            console.error('Error:', err);
            showToast('error', 'An error occurred. Please try again.');
        });
    }
</script>

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