<?php
/**
 * Manage Patrol Points
 * Create, edit, and delete QR code patrol points
 */

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

if (!$auth->canAccessPage('patrols') || !$auth->hasPermission('manage_patrols')) {
    header('Location: ?page=dashboard');
    exit();
}

$post_id = $_GET['post_id'] ?? null;
if (!$post_id) {
    header('Location: ?page=patrols');
    exit();
}

// Get post info
$post = $db->fetch("SELECT * FROM posts WHERE id = ?", [$post_id]);
if (!$post) {
    header('Location: ?page=patrols');
    exit();
}

// Get patrol points for this post
$patrol_points = $db->fetchAll(
    "SELECT * FROM patrol_points WHERE post_id = ? ORDER BY point_name ASC",
    [$post_id]
);

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

<div class="container mx-auto px-4 py-8 max-w-6xl">
    <!-- Header -->
    <div class="mb-8">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-4xl font-bold text-gray-800">
                    <i class="fas fa-location-dot text-blue-600 mr-3"></i><?php echo Language::get('manage_patrol_points'); ?>
                </h1>
                <p class="text-gray-600 mt-2">
                    <?php echo htmlspecialchars($post['name']); ?>
                    <span class="text-sm text-gray-500 ml-2">(<?php echo htmlspecialchars($post['location']); ?>)</span>
                </p>
            </div>
            <div class="flex gap-2">
                <a href="?page=patrols" 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>
                <button onclick="showAddPointModal()" class="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-semibold">
                    <i class="fas fa-plus mr-2"></i><?php echo Language::get('add_patrol_point'); ?>
                </button>
            </div>
        </div>
    </div>

    <!-- Points Grid -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <?php if (!empty($patrol_points)): ?>
            <?php foreach ($patrol_points as $point): ?>
                <div class="bg-white rounded-lg shadow border border-gray-200 p-6 hover:shadow-lg transition">
                    <!-- Point Number Badge -->
                    <div class="flex items-start justify-between mb-4">
                        <div class="bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm font-semibold">
                            <?php echo Language::get('point_status'); ?> <?php echo $point['id']; ?>
                        </div>
                        <div class="flex gap-1">
                            <button onclick="editPatrolPoint(<?php echo $point['id']; ?>)" class="text-gray-600 hover:text-blue-600 p-2">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button onclick="confirmDeletePoint(<?php echo $point['id']; ?>, '<?php echo htmlspecialchars($point['point_name']); ?>')" class="text-gray-600 hover:text-red-600 p-2">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>

                    <!-- Point Name -->
                    <h3 class="text-lg font-bold text-gray-800 mb-3">
                        <?php echo htmlspecialchars($point['point_name']); ?>
                    </h3>

                    <!-- Location Description -->
                    <?php if ($point['location_description']): ?>
                    <p class="text-sm text-gray-600 mb-3">
                        <i class="fas fa-map-pin mr-2 text-gray-500"></i>
                        <?php echo htmlspecialchars($point['location_description']); ?>
                    </p>
                    <?php endif; ?>

                    <!-- QR Code Display -->
                    <div class="bg-gray-50 p-4 rounded-lg mb-3 text-center">
                        <?php if ($point['qr_code']): ?>
                            <img src="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=<?php echo urlencode($point['qr_code']); ?>" 
                                 alt="QR Code" class="w-32 h-32 mx-auto">
                            <p class="text-xs text-gray-600 mt-2 break-all font-mono"><?php echo htmlspecialchars(substr($point['qr_code'], 0, 20)); ?>...</p>
                        <?php else: ?>
                            <p class="text-gray-500 italic">No QR code</p>
                        <?php endif; ?>
                    </div>

                    <!-- Coordinates (if available) -->
                    <?php if ($point['latitude'] && $point['longitude']): ?>
                    <div class="text-xs text-gray-600 mb-3 p-2 bg-gray-50 rounded">
                        <strong>Coordinates:</strong><br>
                        <?php echo round($point['latitude'], 6); ?>, <?php echo round($point['longitude'], 6); ?>
                    </div>
                    <?php endif; ?>

                    <!-- Status Indicator -->
                    <div class="flex items-center justify-between text-sm">
                        <span class="text-gray-600">Status:</span>
                        <span class="<?php echo $point['is_active'] ? 'text-green-600 font-semibold' : 'text-red-600 font-semibold'; ?>">
                            <i class="fas fa-<?php echo $point['is_active'] ? 'check-circle' : 'times-circle'; ?> mr-1"></i>
                            <?php echo $point['is_active'] ? 'Active' : 'Inactive'; ?>
                        </span>
                    </div>

                    <!-- Actions -->
                    <div class="mt-4 pt-4 border-t border-gray-200 flex gap-2">
                        <button onclick="downloadQRCode('<?php echo htmlspecialchars($point['qr_code']); ?>', '<?php echo htmlspecialchars($point['point_name']); ?>')" 
                                class="flex-1 px-3 py-2 bg-blue-100 text-blue-700 rounded text-sm font-semibold hover:bg-blue-200 transition">
                            <i class="fas fa-download mr-1"></i><?php echo Language::get('download'); ?>
                        </button>
                        <button onclick="togglePointStatus(<?php echo $point['id']; ?>, <?php echo $point['is_active'] ? 1 : 0; ?>)" 
                                class="flex-1 px-3 py-2 bg-gray-100 text-gray-700 rounded text-sm font-semibold hover:bg-gray-200 transition">
                            <i class="fas fa-<?php echo $point['is_active'] ? 'pause' : 'play'; ?> mr-1"></i>
                            <?php echo $point['is_active'] ? Language::get('deactivate') : Language::get('activate'); ?>
                        </button>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <!-- Empty State -->
            <div class="col-span-full 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 Language::get('no_posts_available'); ?></p>
                <p class="text-gray-400 text-sm mt-2">Add patrol points to get started</p>
                <button onclick="showAddPointModal()" class="mt-6 px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-semibold">
                    <i class="fas fa-plus mr-2"></i><?php echo Language::get('add_patrol_point'); ?>
                </button>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Add/Edit Point Modal -->
<div id="pointModal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center z-50">
    <div class="bg-white rounded-lg shadow-lg p-8 max-w-md w-full mx-4">
        <h2 class="text-2xl font-bold text-gray-800 mb-6" id="modalTitle">Add Patrol Point</h2>
        
        <form id="pointForm" class="space-y-4">
            <input type="hidden" id="point_id" value="">
            <input type="hidden" name="post_id" value="<?php echo $post_id; ?>">
            
            <!-- Point Name -->
            <div>
                <label class="block text-sm font-semibold text-gray-700 mb-2">Point Name *</label>
                <input type="text" name="point_name" id="point_name" required 
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                       placeholder="e.g., Front Gate, Main Building">
            </div>

            <!-- Location Description -->
            <div>
                <label class="block text-sm font-semibold text-gray-700 mb-2">Location Description</label>
                <textarea name="location_description" id="location_description" rows="2"
                          class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                          placeholder="Detailed location info for guards..."></textarea>
            </div>

            <!-- QR Code -->
            <div>
                <label class="block text-sm font-semibold text-gray-700 mb-2">QR Code Data *</label>
                <div class="flex gap-2">
                    <input type="text" name="qr_code" id="qr_code" required 
                           class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                           placeholder="Unique QR code value">
                    <button type="button" onclick="generateQRCode()" class="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 font-semibold">
                        <i class="fas fa-magic"></i>
                    </button>
                </div>
            </div>

            <!-- Latitude/Longitude -->
            <div class="grid grid-cols-2 gap-2">
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Latitude</label>
                    <input type="number" name="latitude" id="latitude" step="0.000001"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                           placeholder="0.000000">
                </div>
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Longitude</label>
                    <input type="number" name="longitude" id="longitude" step="0.000001"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                           placeholder="0.000000">
                </div>
            </div>

            <!-- Active Status -->
            <div>
                <label class="flex items-center gap-2">
                    <input type="checkbox" name="is_active" id="is_active" checked
                           class="w-5 h-5 text-blue-600 rounded focus:outline-none">
                    <span class="text-sm font-semibold text-gray-700">Active</span>
                </label>
            </div>

            <!-- Actions -->
            <div class="flex gap-2 pt-6 border-t border-gray-200">
                <button type="button" onclick="closeModal()" class="flex-1 px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 font-semibold">
                    Cancel
                </button>
                <button type="submit" class="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-semibold">
                    Save Point
                </button>
            </div>
        </form>
    </div>
</div>

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

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
const POST_ID = <?php echo $post_id; ?>;

function showAddPointModal() {
    document.getElementById('point_id').value = '';
    document.getElementById('pointForm').reset();
    document.getElementById('modalTitle').textContent = 'Add Patrol Point';
    document.getElementById('pointModal').classList.remove('hidden');
}

function closeModal() {
    document.getElementById('pointModal').classList.add('hidden');
}

function editPatrolPoint(pointId) {
    // Fetch point data and populate modal with detailed error handling
    fetch(`?page=api&endpoint=patrol/points/list&id=${pointId}`)
        .then(r => {
            if (!r.ok) throw new Error(`HTTP ${r.status}`);
            return r.json();
        })
        .then(data => {
            if (data.success && data.data) {
                const point = data.data;
                document.getElementById('point_id').value = point.id;
                document.getElementById('point_name').value = point.point_name || '';
                document.getElementById('location_description').value = point.location_description || '';
                document.getElementById('qr_code').value = point.qr_code || '';
                document.getElementById('latitude').value = point.latitude || '';
                document.getElementById('longitude').value = point.longitude || '';
                document.getElementById('is_active').checked = point.is_active == 1;
                document.getElementById('modalTitle').textContent = 'Edit Patrol Point';
                document.getElementById('pointModal').classList.remove('hidden');
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Load Failed',
                    text: data.error || 'Could not load point details',
                    confirmButtonColor: '#3b82f6'
                });
            }
        })
        .catch(err => {
            console.error('Edit point error:', err);
            Swal.fire({
                icon: 'error',
                title: 'Connection Error',
                text: 'Failed to load point: ' + err.message,
                confirmButtonColor: '#3b82f6'
            });
        });
}

function confirmDeletePoint(pointId, pointName) {
    Swal.fire({
        icon: 'warning',
        title: 'Delete Patrol Point?',
        html: `<p>Are you sure you want to delete <strong>${pointName}</strong>?</p><p class="text-sm text-gray-600 mt-2">This action cannot be undone.</p>`,
        confirmButtonText: 'Delete',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#6b7280',
        showCancelButton: true
    }).then(result => {
        if (result.isConfirmed) {
            deletePatrolPoint(pointId);
        }
    });
}

function deletePatrolPoint(pointId) {
    Swal.fire({
        title: 'Deleting...',
        allowOutsideClick: false,
        allowEscapeKey: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });

    fetch(`?page=api&endpoint=patrol/points/delete`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: pointId })
    })
    .then(r => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json();
    })
    .then(data => {
        if (data.success) {
            Swal.fire({
                icon: 'success',
                title: 'Deleted!',
                text: 'Patrol point has been deleted',
                confirmButtonColor: '#3b82f6',
                timer: 1500,
                timerProgressBar: true,
                didClose: () => location.reload()
            });
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Delete Failed',
                text: data.error || 'Failed to delete point',
                confirmButtonColor: '#3b82f6'
            });
        }
    })
    .catch(err => {
        console.error('Delete error:', err);
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Failed to delete point: ' + err.message,
            confirmButtonColor: '#3b82f6'
        });
    });
}

function togglePointStatus(pointId, currentStatus) {
    const newStatus = currentStatus ? 0 : 1;
    const action = newStatus ? 'Activating' : 'Deactivating';
    
    Swal.fire({
        title: action + '...',
        allowOutsideClick: false,
        allowEscapeKey: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });

    fetch(`?page=api&endpoint=patrol/points/update`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: pointId, is_active: newStatus })
    })
    .then(r => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json();
    })
    .then(data => {
        if (data.success) {
            Swal.fire({
                icon: 'success',
                title: 'Updated!',
                text: 'Point status has been updated',
                confirmButtonColor: '#3b82f6',
                timer: 1000,
                timerProgressBar: true,
                didClose: () => location.reload()
            });
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Update Failed',
                text: data.error || 'Failed to update status',
                confirmButtonColor: '#3b82f6'
            });
        }
    })
    .catch(err => {
        console.error('Status update error:', err);
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Failed to update status: ' + err.message,
            confirmButtonColor: '#3b82f6'
        });
    });
}

function generateQRCode() {
    const uniqueId = 'PATROL_' + POST_ID + '_' + Date.now();
    document.getElementById('qr_code').value = uniqueId;
    
    Swal.fire({
        icon: 'success',
        title: 'QR Code Generated!',
        text: 'Auto-generated unique QR code: ' + uniqueId,
        confirmButtonColor: '#10b981',
        timer: 2000,
        timerProgressBar: true
    });
}

function downloadQRCode(qrData, pointName) {
    const url = `https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodeURIComponent(qrData)}`;
    const a = document.createElement('a');
    a.href = url;
    a.download = `QR_${pointName.replace(/\s+/g, '_')}.png`;
    a.click();
}

document.getElementById('pointForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const pointId = document.getElementById('point_id').value;
    const pointName = document.getElementById('point_name').value;
    const endpoint = pointId ? 'patrol/points/update' : 'patrol/points/create';
    
    const formData = {
        post_id: POST_ID,
        point_name: pointName,
        location_description: document.getElementById('location_description').value,
        qr_code: document.getElementById('qr_code').value,
        latitude: document.getElementById('latitude').value || null,
        longitude: document.getElementById('longitude').value || null,
        is_active: document.getElementById('is_active').checked ? 1 : 0
    };
    
    if (pointId) {
        formData.id = pointId;
    }
    
    // Show saving indicator
    Swal.fire({
        title: 'Saving...',
        allowOutsideClick: false,
        allowEscapeKey: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    try {
        const response = await fetch(`?page=api&endpoint=${endpoint}`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(formData)
        });
        
        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        
        const data = await response.json();
        
        if (data.success) {
            closeModal();
            Swal.fire({
                icon: 'success',
                title: 'Saved!',
                text: `Patrol point "${pointName}" has been ${pointId ? 'updated' : 'created'}`,
                confirmButtonColor: '#10b981',
                timer: 1500,
                timerProgressBar: true,
                didClose: () => location.reload()
            });
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Save Failed',
                text: data.error || 'Failed to save point',
                confirmButtonColor: '#3b82f6'
            });
        }
    } catch (error) {
        console.error('Save error:', error);
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Error saving point: ' + error.message,
            confirmButtonColor: '#3b82f6'
        });
    }
});

// Close modal on escape key
document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && !document.getElementById('pointModal').classList.contains('hidden')) {
        closeModal();
    }
});
</script>
