<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../includes/auth.php';

if (!isset($pdo)) {
    $pdo = require_once __DIR__ . '/../config/database.php';
}

require_admin();

$success = '';
$error = '';

// Handle CRUD
if (is_post()) {
    ensure_csrf();
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add') {
        $name = sanitize_str($_POST['name'] ?? '');
        $state = sanitize_str($_POST['state'] ?? '');
        $slug = slugify($name);
        
        if (empty($name)) {
            $error = 'Name is required.';
        } else {
            try {
                $stmt = $pdo->prepare("INSERT INTO locations (name, slug, state) VALUES (?,?,?)");
                $stmt->execute([$name, $slug, $state]);
                $success = 'Location added successfully.';
            } catch (PDOException $e) {
                $error = 'Failed to add location. It might already exist.';
            }
        }
    } elseif ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $pdo->prepare("DELETE FROM locations WHERE id = ?");
        $stmt->execute([$id]);
        $success = 'Location deleted successfully.';
    }
}

$locations = $pdo->query("SELECT * FROM locations ORDER BY name ASC")->fetchAll();

include __DIR__ . '/../includes/header.php';
?>

<div class="seo-hub-header" style="display:flex;justify-content:space-between;align-items:center;margin-bottom:32px">
    <div>
        <h1 style="margin:0">Target Locations</h1>
        <p class="muted"><a href="<?=url('admin/seo_hub.php')?>">SEO Hub</a> / Manage cities for programmatic landing pages.</p>
    </div>
    <button class="btn primary" onclick="document.getElementById('add-form').style.display='block'"><?=ui_icon('plus',16)?> Add City</button>
</div>

<?php if ($success): ?><div class="flash success"><?=e($success)?></div><?php endif; ?>
<?php if ($error): ?><div class="flash error"><?=e($error)?></div><?php endif; ?>

<div id="add-form" class="card" style="display:none; margin-bottom: 24px;">
    <h3 style="margin-top:0">Add New Location</h3>
    <form method="post">
        <?=csrf_field()?>
        <input type="hidden" name="action" value="add">
        <div class="grid grid-2">
            <div class="form-group">
                <label class="form-label">City Name</label>
                <input type="text" name="name" class="form-input" placeholder="e.g. Kaduna" required>
            </div>
            <div class="form-group">
                <label class="form-label">State (Optional)</label>
                <input type="text" name="state" class="form-input" placeholder="e.g. Kaduna State">
            </div>
        </div>
        <div style="display:flex; justify-content:flex-end; gap:12px; margin-top:12px">
            <button type="button" class="btn ghost" onclick="this.parentElement.parentElement.parentElement.style.display='none'">Cancel</button>
            <button type="submit" class="btn primary">Save Location</button>
        </div>
    </form>
</div>

<div class="card" style="padding:0">
    <table style="width:100%; border-collapse:collapse">
        <thead>
            <tr style="background:#f8fafc; text-align:left">
                <th style="padding:16px; border-bottom:1px solid var(--border)">City</th>
                <th style="padding:16px; border-bottom:1px solid var(--border)">Slug</th>
                <th style="padding:16px; border-bottom:1px solid var(--border)">State</th>
                <th style="padding:16px; border-bottom:1px solid var(--border)">Status</th>
                <th style="padding:16px; border-bottom:1px solid var(--border); text-align:right">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($locations as $l): ?>
                <tr>
                    <td style="padding:16px; border-bottom:1px solid var(--border); font-weight:600"><?=e($l['name'])?></td>
                    <td style="padding:16px; border-bottom:1px solid var(--border)"><code><?=e($l['slug'])?></code></td>
                    <td style="padding:16px; border-bottom:1px solid var(--border)"><?=e($l['state'] ?: '-')?></td>
                    <td style="padding:16px; border-bottom:1px solid var(--border)">
                        <span style="background:#dcfce7; color:#16a34a; padding:2px 10px; border-radius:12px; font-size:12px"><?=e($l['status'])?></span>
                    </td>
                    <td style="padding:16px; border-bottom:1px solid var(--border); text-align:right">
                        <form method="post" style="display:inline" onsubmit="return confirm('Delete this location?')">
                            <?=csrf_field()?>
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="id" value="<?=$l['id']?>">
                            <button type="submit" style="background:none; border:none; color:#ef4444; cursor:pointer" title="Delete"><?=ui_icon('trash',18)?></button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

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