<?php
require_once __DIR__ . '/includes/admin_auth.php';
requireAdmin();
$db = getDB();

$tab = $_GET['tab'] ?? 'cities'; // cities | states

// ── STATES ──────────────────────────────────────
if ($tab === 'states') {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $id   = (int)($_POST['id'] ?? 0);
        $name = sanitize($_POST['name'] ?? '');
        $code = sanitize($_POST['code'] ?? '');
        $stat = (int)($_POST['status'] ?? 1);
        if ($name) {
            if ($id) {
                $db->prepare("UPDATE states SET name=?,code=?,status=? WHERE id=?")->execute([$name,$code,$stat,$id]);
                setAdminFlash('success','State updated.');
            } else {
                $db->prepare("INSERT INTO states (name,code,status) VALUES (?,?,?)")->execute([$name,$code,$stat]);
                setAdminFlash('success','State added.');
            }
        }
        header('Location: /admin/cities.php?tab=states'); exit;
    }
    if (isset($_GET['delete'])) {
        $db->prepare("DELETE FROM states WHERE id=?")->execute([(int)$_GET['delete']]);
        setAdminFlash('success','State deleted.'); header('Location: /admin/cities.php?tab=states'); exit;
    }
    $editItem = null;
    if (isset($_GET['edit'])) { $s=$db->prepare("SELECT * FROM states WHERE id=?");$s->execute([(int)$_GET['edit']]);$editItem=$s->fetch(); }
    $items = $db->query("SELECT s.*, (SELECT COUNT(*) FROM cities WHERE state_id=s.id) AS city_count FROM states s ORDER BY s.name")->fetchAll();

// ── CITIES ──────────────────────────────────────
} else {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $id      = (int)($_POST['id'] ?? 0);
        $name    = sanitize($_POST['name'] ?? '');
        $stateId = (int)($_POST['state_id'] ?? 0);
        $stat    = (int)($_POST['status'] ?? 1);
        if ($name && $stateId) {
            if ($id) {
                $db->prepare("UPDATE cities SET name=?,state_id=?,status=? WHERE id=?")->execute([$name,$stateId,$stat,$id]);
                setAdminFlash('success','City updated.');
            } else {
                $db->prepare("INSERT INTO cities (state_id,name,status) VALUES (?,?,?)")->execute([$stateId,$name,$stat]);
                setAdminFlash('success','City added.');
            }
        }
        header('Location: /admin/cities.php?tab=cities'); exit;
    }
    if (isset($_GET['delete'])) {
        $db->prepare("DELETE FROM cities WHERE id=?")->execute([(int)$_GET['delete']]);
        setAdminFlash('success','City deleted.'); header('Location: /admin/cities.php?tab=cities'); exit;
    }
    $editItem = null;
    if (isset($_GET['edit'])) { $s=$db->prepare("SELECT * FROM cities WHERE id=?");$s->execute([(int)$_GET['edit']]);$editItem=$s->fetch(); }
    $items  = $db->query("SELECT c.*,s.name AS state_name FROM cities c LEFT JOIN states s ON c.state_id=s.id ORDER BY s.name,c.name")->fetchAll();
    $states = $db->query("SELECT * FROM states WHERE status=1 ORDER BY name")->fetchAll();
}

adminHead('Cities & States');
adminSidebar('cities');
?>
<div class="adm-main">
<?php adminTopbar('Manage Cities & States'); ?>
<div class="adm-content">
<?php flashHtml(); ?>

<!-- Tab switcher -->
<div style="display:flex;gap:8px;margin-bottom:22px;">
    <a href="?tab=cities"  style="padding:9px 22px;border-radius:50px;font-size:.83rem;font-weight:700;text-decoration:none;border:1px solid var(--border);<?= $tab==='cities'?'background:var(--primary);color:white;border-color:var(--primary);':'background:white;color:#718096;' ?>">🏙 Cities</a>
    <a href="?tab=states"  style="padding:9px 22px;border-radius:50px;font-size:.83rem;font-weight:700;text-decoration:none;border:1px solid var(--border);<?= $tab==='states'?'background:var(--primary);color:white;border-color:var(--primary);':'background:white;color:#718096;' ?>">🗺 States</a>
</div>

<div class="row g-4">
    <!-- Form -->
    <div class="col-lg-4">
        <div class="adm-card" style="overflow:visible;">
            <div class="adm-card-head"><h6><?= $editItem ? 'Edit '.ucfirst(rtrim($tab,'s')) : 'Add New '.ucfirst(rtrim($tab,'s')) ?></h6></div>
            <div style="padding:22px;">
                <form method="POST">
                    <?php if ($editItem): ?><input type="hidden" name="id" value="<?= $editItem['id'] ?>"><?php endif; ?>

                    <?php if ($tab === 'cities'): ?>
                    <div style="margin-bottom:14px;">
                        <label class="lbl">Select State *</label>
                        <select name="state_id" class="form-ctrl" required>
                            <option value="">-- Select State --</option>
                            <?php foreach ($states as $s): ?>
                            <option value="<?= $s['id'] ?>" <?= ($editItem['state_id'] ?? 0)==$s['id']?'selected':'' ?>><?= $s['name'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php else: ?>
                    <div style="margin-bottom:14px;">
                        <label class="lbl">State Code (e.g. TS, AP)</label>
                        <input type="text" name="code" class="form-ctrl" value="<?= htmlspecialchars($editItem['code'] ?? '') ?>" maxlength="5" placeholder="e.g. TS">
                    </div>
                    <?php endif; ?>

                    <div style="margin-bottom:14px;">
                        <label class="lbl"><?= $tab==='cities'?'City':'State' ?> Name *</label>
                        <input type="text" name="name" class="form-ctrl" value="<?= htmlspecialchars($editItem['name'] ?? '') ?>" required>
                    </div>
                    <div style="margin-bottom:20px;">
                        <label class="lbl">Status</label>
                        <select name="status" class="form-ctrl">
                            <option value="1" <?= ($editItem['status'] ?? 1)==1?'selected':'' ?>>Active</option>
                            <option value="0" <?= ($editItem['status'] ?? 1)==0?'selected':'' ?>>Inactive</option>
                        </select>
                    </div>
                    <button type="submit" class="btn-gold w-100" style="width:100%;padding:11px;"><?= $editItem ? 'Update' : 'Add' ?> <?= ucfirst(rtrim($tab,'s')) ?></button>
                    <?php if ($editItem): ?>
                    <a href="/admin/cities.php?tab=<?= $tab ?>" style="display:block;text-align:center;margin-top:10px;font-size:.82rem;color:#718096;">Cancel</a>
                    <?php endif; ?>
                </form>
            </div>
        </div>
    </div>

    <!-- List -->
    <div class="col-lg-8">
        <div class="adm-card">
            <div class="adm-card-head"><h6>All <?= ucfirst($tab) ?> (<?= count($items) ?>)</h6></div>
            <div style="overflow-x:auto;">
            <table class="table tbl mb-0">
                <thead>
                    <tr>
                        <th>#</th>
                        <th><?= $tab==='cities'?'City':'State' ?> Name</th>
                        <?php if ($tab==='states'): ?><th>Code</th><?php else: ?><th>State</th><?php endif; ?>
                        <?php if ($tab==='states'): ?><th>Cities</th><?php endif; ?>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($items as $i => $item): ?>
                <tr>
                    <td style="font-size:.75rem;color:#718096;"><?= $i+1 ?></td>
                    <td style="font-weight:700;font-size:.85rem;"><?= htmlspecialchars($item['name']) ?></td>
                    <?php if ($tab==='states'): ?>
                    <td><span style="background:rgba(10,35,66,.08);color:var(--primary);padding:3px 9px;border-radius:50px;font-size:.74rem;font-weight:700;"><?= $item['code'] ?: '—' ?></span></td>
                    <td><span style="background:rgba(212,175,55,.12);color:var(--gold-dark);padding:3px 9px;border-radius:50px;font-size:.74rem;font-weight:700;"><?= $item['city_count'] ?> cities</span></td>
                    <?php else: ?>
                    <td style="font-size:.8rem;color:#718096;"><?= $item['state_name'] ?></td>
                    <?php endif; ?>
                    <td><span class="badge-pill badge-<?= $item['status']?'active':'inactive' ?>"><?= $item['status']?'Active':'Inactive' ?></span></td>
                    <td style="white-space:nowrap;">
                        <a href="?tab=<?= $tab ?>&edit=<?= $item['id'] ?>" class="btn-sm-edit">Edit</a>
                        <a href="?tab=<?= $tab ?>&delete=<?= $item['id'] ?>" class="btn-sm-del confirm-del" style="margin-left:5px;">Del</a>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($items)): ?>
                <tr><td colspan="6" style="text-align:center;padding:40px;color:#718096;">No records found.</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
            </div>
        </div>
    </div>
</div>
</div></div>
<?php adminFoot(); ?>