<?php
require_once __DIR__ . '/../functions.php';
requireAdmin();
$page_title = 'Pincodes';
$db = db();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pincode = trim($_POST['pincode'] ?? '');
    $city = trim($_POST['city'] ?? '');
    $state = trim($_POST['state'] ?? '');
    $codAvailable = isset($_POST['cod_available']) ? 1 : 0;
    $deliveryDays = (int)($_POST['delivery_days'] ?? 3);
    $isActive = isset($_POST['is_active']) ? 1 : 0;

    if (isset($_GET['edit'])) {
        $id = (int)$_GET['edit'];
        $db->prepare("UPDATE pincodes SET pincode=?, city=?, state=?, cod_available=?, delivery_days=?, is_active=? WHERE id=?")
            ->execute([$pincode, $city, $state, $codAvailable, $deliveryDays, $isActive, $id]);
        flash('success', 'Pincode updated!');
    } else {
        try {
            $db->prepare("INSERT INTO pincodes (pincode, city, state, cod_available, delivery_days, is_active) VALUES (?, ?, ?, ?, ?, ?)")
                ->execute([$pincode, $city, $state, $codAvailable, $deliveryDays, $isActive]);
            flash('success', 'Pincode added!');
        } catch (PDOException $e) {
            flash('error', 'Pincode already exists or invalid.');
        }
    }
    header('Location: pincodes.php');
    exit;
}

if (isset($_GET['delete'])) {
    $db->prepare("DELETE FROM pincodes WHERE id = ?")->execute([(int)$_GET['delete']]);
    flash('success', 'Pincode deleted!');
    header('Location: pincodes.php');
    exit;
}

$pincodes = $db->query("SELECT * FROM pincodes ORDER BY pincode")->fetchAll();
$editPincode = null;
if (isset($_GET['edit'])) {
    $stmt = $db->prepare("SELECT * FROM pincodes WHERE id = ?");
    $stmt->execute([(int)$_GET['edit']]);
    $editPincode = $stmt->fetch();
}

require_once __DIR__ . '/../includes/admin-header.php';
?>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <div class="lg:col-span-2">
        <div class="bg-white rounded-xl border border-gray-200 overflow-hidden">
            <table class="w-full text-sm">
                <thead><tr class="text-left bg-gray-50 text-gray-500"><th class="px-4 py-3 font-medium">Pincode</th><th class="px-4 py-3 font-medium">City</th><th class="px-4 py-3 font-medium">State</th><th class="px-4 py-3 font-medium">COD</th><th class="px-4 py-3 font-medium">Days</th><th class="px-4 py-3 font-medium">Status</th><th class="px-4 py-3 font-medium"></th></tr></thead>
                <tbody>
                    <?php foreach ($pincodes as $p): ?>
                    <tr class="border-t">
                        <td class="px-4 py-3 font-medium"><?= h($p['pincode']) ?></td>
                        <td class="px-4 py-3"><?= h($p['city'] ?: '-') ?></td>
                        <td class="px-4 py-3"><?= h($p['state'] ?: '-') ?></td>
                        <td class="px-4 py-3"><?= $p['cod_available'] ? '<span class="text-green-600"><i class="fas fa-check"></i></span>' : '<span class="text-gray-400"><i class="fas fa-times"></i></span>' ?></td>
                        <td class="px-4 py-3"><?= $p['delivery_days'] ?> days</td>
                        <td class="px-4 py-3"><?= $p['is_active'] ? '<span class="text-green-600 text-xs font-medium">Active</span>' : '<span class="text-gray-400 text-xs font-medium">Inactive</span>' ?></td>
                        <td class="px-4 py-3"><a href="pincodes.php?edit=<?= $p['id'] ?>" class="text-primary-600 hover:underline text-xs mr-2">Edit</a><a href="pincodes.php?delete=<?= $p['id'] ?>" class="text-red-500 hover:underline text-xs" onclick="return confirm('Delete?')">Delete</a></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php if (count($pincodes) === 0): ?>
            <p class="text-center text-gray-400 py-8">No pincodes added yet.</p>
            <?php endif; ?>
        </div>
    </div>
    <div>
        <form method="POST" class="bg-white rounded-xl border border-gray-200 p-6">
            <h3 class="font-semibold text-gray-800 mb-4"><?= $editPincode ? 'Edit Pincode' : 'Add Pincode' ?></h3>
            <div class="space-y-3">
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Pincode *</label><input type="text" name="pincode" id="pincode-input" value="<?= h($editPincode['pincode'] ?? '') ?>" maxlength="6" required class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm" oninput="autoFillLocation(this.value)"><span id="pincode-status" class="text-xs"></span></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">City</label><input type="text" name="city" id="city-input" value="<?= h($editPincode['city'] ?? '') ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">State</label><input type="text" name="state" id="state-input" value="<?= h($editPincode['state'] ?? '') ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Delivery Days</label><input type="number" name="delivery_days" value="<?= h($editPincode['delivery_days'] ?? '3') ?>" min="1" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"></div>
                <label class="flex items-center gap-2"><input type="checkbox" name="cod_available" <?= !isset($editPincode) || $editPincode['cod_available'] ? 'checked' : '' ?> class="rounded border-gray-300"> <span class="text-sm">COD Available</span></label>
                <label class="flex items-center gap-2"><input type="checkbox" name="is_active" <?= !isset($editPincode) || $editPincode['is_active'] ? 'checked' : '' ?> class="rounded border-gray-300"> <span class="text-sm">Active</span></label>
                <button type="submit" class="w-full bg-primary-600 text-white py-2 rounded-lg text-sm font-semibold hover:bg-primary-700"><?= $editPincode ? 'Update' : 'Add' ?></button>
                <?php if ($editPincode): ?><a href="pincodes.php" class="block text-center text-sm text-gray-500 mt-2 hover:underline">Cancel</a><?php endif; ?>
            </div>
        </form>
    </div>
</div>
<script>
let pincodeTimer;
function autoFillLocation(pincode) {
    const status = document.getElementById('pincode-status');
    status.textContent = '';
    if (pincode.length !== 6) return;
    clearTimeout(pincodeTimer);
    pincodeTimer = setTimeout(async () => {
        status.innerHTML = ' <i class="fas fa-spinner fa-spin text-gray-400"></i>';
        try {
            const r = await fetch('<?= BASE_PATH ?>/api/pincode-lookup.php?pincode=' + pincode);
            const d = await r.json();
            if (d.success) {
                document.getElementById('city-input').value = d.city;
                document.getElementById('state-input').value = d.state;
                status.innerHTML = ' <i class="fas fa-check text-green-500"></i>';
            } else {
                status.innerHTML = ' <span class="text-red-500">' + d.message + '</span>';
            }
        } catch(e) {
            status.innerHTML = ' <span class="text-red-500">Error</span>';
        }
    }, 300);
}
</script>
<?php require_once __DIR__ . '/../includes/admin-footer.php'; ?>
