<?php
/**
 * Delivery Management - Admin Page
 */

$page_title = 'Delivery Services';
require_once 'includes/header.php';

$message = '';
$error = '';

try {
    $pdo = getDBConnection();

    // Handle form submissions
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['save_service'])) {
            $id = $_POST['id'] ?? null;
            $service_name = $_POST['service_name'];
            $description = $_POST['description'];
            $amount = $_POST['amount'];
            $is_active = isset($_POST['is_active']) ? 1 : 0;

            if ($id) {
                $stmt = $pdo->prepare("UPDATE delivery_services SET service_name = ?, description = ?, amount = ?, is_active = ? WHERE id = ?");
                $stmt->execute([$service_name, $description, $amount, $is_active, $id]);
                $message = 'Delivery service updated successfully!';
            } else {
                $stmt = $pdo->prepare("INSERT INTO delivery_services (service_name, description, amount, is_active) VALUES (?, ?, ?, ?)");
                $stmt->execute([$service_name, $description, $amount, $is_active]);
                $message = 'Delivery service added successfully!';
            }
        } elseif (isset($_POST['delete_service'])) {
            $id = $_POST['id'];
            $stmt = $pdo->prepare("DELETE FROM delivery_services WHERE id = ?");
            $stmt->execute([$id]);
            $message = 'Delivery service deleted successfully!';
        } elseif (isset($_POST['toggle_status'])) {
            $id = $_POST['id'];
            $status = $_POST['status'];
            $stmt = $pdo->prepare("UPDATE delivery_services SET is_active = ? WHERE id = ?");
            $stmt->execute([$status, $id]);
            $message = 'Service status updated!';
        }
    }

    // Get all services
    $stmt = $pdo->query("SELECT * FROM delivery_services ORDER BY created_at DESC");
    $services = $stmt->fetchAll();

} catch (Exception $e) {
    $error = "Database error: " . $e->getMessage();
}
?>

<div class="flex h-screen overflow-hidden">
    <?php include 'includes/sidebar.php'; ?>

    <div class="flex-1 flex flex-col overflow-hidden">
        <header class="sticky top-0 z-30 flex items-center bg-white/80 dark:bg-background-dark/80 backdrop-blur-md p-4 justify-between border-b border-slate-200 dark:border-slate-800 lg:px-8">
            <h2 class="text-slate-900 dark:text-white text-clamp-lg font-bold">Delivery Services</h2>
            <button onclick="openModal()" class="bg-primary text-white px-4 py-2 rounded-xl font-bold text-sm shadow-lg shadow-primary/20 flex items-center gap-2">
                <span class="material-symbols-outlined text-sm">add</span>
                Add New Service
            </button>
        </header>

        <main class="flex-1 overflow-y-auto p-4 lg:p-8 pb-24 admin-content">
            <?php if ($message): ?>
                <div class="bg-emerald-100 dark:bg-emerald-900/30 border border-emerald-400 text-emerald-700 dark:text-emerald-300 px-4 py-3 rounded-xl mb-6">
                    <?= htmlspecialchars($message) ?>
                </div>
            <?php endif; ?>

            <?php if ($error): ?>
                <div class="bg-red-100 dark:bg-red-900/30 border border-red-400 text-red-700 dark:text-red-300 px-4 py-3 rounded-xl mb-6">
                    <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>

            <div class="bg-white dark:bg-surface-dark rounded-2xl border border-slate-200 dark:border-slate-800 overflow-hidden shadow-sm">
                <div class="overflow-x-auto">
                    <table class="w-full text-left border-collapse">
                        <thead>
                            <tr class="bg-slate-50 dark:bg-slate-900/50">
                                <th class="px-6 py-4 text-xs font-bold text-slate-500 uppercase">Service/Place</th>
                                <th class="px-6 py-4 text-xs font-bold text-slate-500 uppercase">Description</th>
                                <th class="px-6 py-4 text-xs font-bold text-slate-500 uppercase">Amount</th>
                                <th class="px-6 py-4 text-xs font-bold text-slate-500 uppercase">Status</th>
                                <th class="px-6 py-4 text-xs font-bold text-slate-500 uppercase text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100 dark:divide-slate-800">
                            <?php if (empty($services)): ?>
                                <tr>
                                    <td colspan="5" class="px-6 py-12 text-center text-slate-500">No delivery services found. Click "Add New Service" to get started.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($services as $s): ?>
                                    <tr class="hover:bg-slate-50 dark:hover:bg-slate-900/30 transition-colors">
                                        <td class="px-6 py-4">
                                            <p class="font-bold text-slate-900 dark:text-white"><?= htmlspecialchars($s['service_name']) ?></p>
                                        </td>
                                        <td class="px-6 py-4">
                                            <p class="text-sm text-slate-500 dark:text-slate-400 line-clamp-1"><?= htmlspecialchars($s['description']) ?></p>
                                        </td>
                                        <td class="px-6 py-4">
                                            <p class="font-bold text-primary">₱<?= number_format($s['amount'], 2) ?></p>
                                        </td>
                                        <td class="px-6 py-4">
                                            <form method="POST" class="inline">
                                                <input type="hidden" name="toggle_status" value="1">
                                                <input type="hidden" name="id" value="<?= $s['id'] ?>">
                                                <input type="hidden" name="status" value="<?= $s['is_active'] ? 0 : 1 ?>">
                                                <button type="submit" class="px-3 py-1 rounded-full text-[10px] font-bold uppercase transition-colors <?= $s['is_active'] ? 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200' : 'bg-slate-100 text-slate-700 hover:bg-slate-200' ?>">
                                                    <?= $s['is_active'] ? 'Active' : 'Inactive' ?>
                                                </button>
                                            </form>
                                        </td>
                                        <td class="px-6 py-4 text-right">
                                            <div class="flex items-center justify-end gap-2">
                                                <button onclick='editService(<?= json_encode($s) ?>)' class="p-2 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/30 rounded-lg transition-colors">
                                                    <span class="material-symbols-outlined text-lg">edit</span>
                                                </button>
                                                <form method="POST" class="inline" onsubmit="return confirm('Are you sure you want to delete this service?')">
                                                    <input type="hidden" name="delete_service" value="1">
                                                    <input type="hidden" name="id" value="<?= $s['id'] ?>">
                                                    <button type="submit" class="p-2 text-rose-600 hover:bg-rose-50 dark:hover:bg-rose-900/30 rounded-lg transition-colors">
                                                        <span class="material-symbols-outlined text-lg">delete</span>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- Modal -->
<div id="serviceModal" class="fixed inset-0 z-[100] hidden overflow-y-auto">
    <div class="flex min-h-screen items-center justify-center p-4">
        <div class="fixed inset-0 bg-slate-900/50 backdrop-blur-sm" onclick="closeModal()"></div>
        <div class="relative w-full max-w-lg rounded-2xl bg-white dark:bg-surface-dark shadow-2xl border border-slate-200 dark:border-slate-800">
            <div class="flex items-center justify-between border-b border-slate-100 dark:border-slate-800 p-4">
                <h3 id="modalTitle" class="text-lg font-bold">Add Delivery Service</h3>
                <button onclick="closeModal()" class="flex size-8 items-center justify-center rounded-full hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>
            <form method="POST" class="p-6 space-y-4">
                <input type="hidden" name="save_service" value="1">
                <input type="hidden" name="id" id="service_id">

                <div>
                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Service Name / Place</label>
                    <input type="text" name="service_name" id="service_name" required class="w-full px-4 py-2 bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-xl focus:ring-primary focus:border-primary" placeholder="e.g. Airport Transfer, City Delivery">
                </div>

                <div>
                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Description / Info</label>
                    <textarea name="description" id="description" rows="3" class="w-full px-4 py-2 bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-xl focus:ring-primary focus:border-primary" placeholder="Details about this delivery service..."></textarea>
                </div>

                <div>
                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Amount (₱)</label>
                    <input type="number" name="amount" id="amount" step="0.01" required class="w-full px-4 py-2 bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-xl focus:ring-primary focus:border-primary" placeholder="0.00">
                </div>

                <div class="flex items-center gap-2">
                    <input type="checkbox" name="is_active" id="is_active" checked class="w-4 h-4 text-primary bg-slate-50 border-slate-200 rounded focus:ring-primary">
                    <label for="is_active" class="text-sm font-medium text-slate-700 dark:text-slate-300">Active and available for booking</label>
                </div>

                <div class="flex justify-end gap-3 mt-6">
                    <button type="button" onclick="closeModal()" class="px-6 py-2 bg-slate-100 dark:bg-slate-800 rounded-lg font-bold text-sm">Cancel</button>
                    <button type="submit" class="px-6 py-2 bg-primary text-white rounded-lg font-bold text-sm shadow-lg shadow-primary/20">Save Service</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function openModal() {
    document.getElementById('serviceModal').classList.remove('hidden');
    document.getElementById('modalTitle').textContent = 'Add Delivery Service';
    document.getElementById('service_id').value = '';
    document.getElementById('service_name').value = '';
    document.getElementById('description').value = '';
    document.getElementById('amount').value = '';
    document.getElementById('is_active').checked = true;
}

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

function editService(service) {
    document.getElementById('serviceModal').classList.remove('hidden');
    document.getElementById('modalTitle').textContent = 'Edit Delivery Service';
    document.getElementById('service_id').value = service.id;
    document.getElementById('service_name').value = service.service_name;
    document.getElementById('description').value = service.description;
    document.getElementById('amount').value = service.amount;
    document.getElementById('is_active').checked = service.is_active == 1;
}
</script>

<?php include 'includes/footer.php'; ?>
