<?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 Bulk Generation
if (is_post() && isset($_POST['action']) && $_POST['action'] === 'generate') {
    ensure_csrf();
    $serviceIds = $_POST['services'] ?? [];
    $locationIds = $_POST['locations'] ?? [];
    
    if (empty($serviceIds) || empty($locationIds)) {
        $error = 'Please select at least one service and one location.';
    } else {
        $count = 0;
        foreach ($serviceIds as $sid) {
            foreach ($locationIds as $lid) {
                // Fetch service and location details
                $s = $pdo->prepare("SELECT service_name, slug FROM services WHERE id = ?");
                $s->execute([$sid]);
                $service = $s->fetch();
                
                $l = $pdo->prepare("SELECT name, slug FROM locations WHERE id = ?");
                $l->execute([$lid]);
                $location = $l->fetch();
                
                if ($service && $location) {
                    $slug = $service['slug'] . '-in-' . $location['slug'];
                    $title = $service['service_name'] . ' in ' . $location['name'] . ' | Fast & Reliable | Go Legal';
                    $description = 'Register your ' . str_replace(' Registration', '', $service['service_name']) . ' in ' . $location['name'] . ' with ease. We handle CAC filing, TIN, and more. Get started today!';
                    $h1 = $service['service_name'] . ' in ' . $location['name'];
                    
                    try {
                        $stmt = $pdo->prepare("INSERT OR IGNORE INTO seo_landings (service_id, location_id, slug, title, description, h1_title) VALUES (?,?,?,?,?,?)");
                        if ($stmt->execute([$sid, $lid, $slug, $title, $description, $h1])) {
                            $count++;
                        }
                    } catch (PDOException $e) {
                        // Likely already exists
                    }
                }
            }
        }
        $success = "Successfully generated $count new landing pages.";
    }
}

// Handle Delete
if (isset($_GET['delete'])) {
    if (!verify_csrf($_GET['csrf_token'] ?? null)) {
        http_response_code(400);
        exit;
    }
    $id = (int)$_GET['delete'];
    $pdo->prepare("DELETE FROM seo_landings WHERE id = ?")->execute([$id]);
    $success = "Landing page deleted.";
}

// Fetch Services & Locations for selection
$services = $pdo->query("SELECT id, service_name FROM services WHERE status='active' ORDER BY service_name ASC")->fetchAll();
$locations = $pdo->query("SELECT id, name FROM locations WHERE status='active' ORDER BY name ASC")->fetchAll();

// Fetch existing landings
$landings = $pdo->query("
    SELECT sl.*, s.service_name, l.name as location_name 
    FROM seo_landings sl
    JOIN services s ON sl.service_id = s.id
    JOIN locations l ON sl.location_id = l.id
    ORDER BY sl.created_at DESC
")->fetchAll();

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

<style>
    .seo-hub-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 32px;
    }
    
    .seo-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 24px;
        margin-bottom: 40px;
    }
    
    .stats-card {
        background: rgba(255, 255, 255, 0.05);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.1);
        border-radius: 16px;
        padding: 24px;
        color: #fff;
    }
    
    .stats-value {
        font-size: 36px;
        font-weight: 800;
        margin-bottom: 4px;
        background: linear-gradient(135deg, #10b981 0%, #3b82f6 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    
    .stats-label {
        color: var(--muted);
        font-size: 14px;
        font-weight: 500;
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }
    
    .selection-box {
        max-height: 200px;
        overflow-y: auto;
        border: 1px solid var(--border);
        border-radius: 8px;
        padding: 12px;
        background: #fff;
    }
    
    .selection-item {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 8px;
    }
    
    .selection-item label {
        margin: 0;
        cursor: pointer;
    }
    
    .table-container {
        background: #fff;
        border-radius: 12px;
        border: 1px solid var(--border);
        overflow: hidden;
    }
    
    table {
        width: 100%;
        border-collapse: collapse;
    }
    
    th {
        text-align: left;
        background: #f8fafc;
        padding: 16px;
        font-size: 13px;
        font-weight: 600;
        color: var(--muted);
        border-bottom: 1px solid var(--border);
    }
    
    td {
        padding: 16px;
        border-bottom: 1px solid var(--border);
        font-size: 14px;
    }
    
    .status-pill {
        display: inline-flex;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
    }
    
    .status-active { background: #dcfce7; color: #16a34a; }
</style>

<div class="seo-hub-header">
    <div>
        <h1 style="margin:0">SEO Hub</h1>
        <p class="muted">Manage your programmatic SEO engine and rank higher in search results.</p>
    </div>
    <div style="display:flex;gap:12px">
        <a href="<?=url('admin/seo_locations.php')?>" class="btn ghost"><?=ui_icon('locations',16)?> Locations</a>
        <button class="btn primary" onclick="document.getElementById('generator').scrollIntoView({behavior:'smooth'})"><?=ui_icon('plus',16)?> New Landing</button>
    </div>
</div>


<div class="seo-grid">
    <div class="stats-card">
        <div class="stats-value"><?=count($landings)?></div>
        <div class="stats-label">Active Landings</div>
    </div>
    <div class="stats-card">
        <div class="stats-value"><?=count($locations)?></div>
        <div class="stats-label">Target Locations</div>
    </div>
</div>

<div id="generator" class="card" style="margin-bottom: 40px;">
    <h3 style="margin-top:0">Bulk Landing Generator</h3>
    <p class="muted">Select services and locations to generate programmatic landing pages.</p>
    
    <form method="post">
        <?=csrf_field()?>
        <input type="hidden" name="action" value="generate">
        
        <div class="grid grid-2" style="margin-bottom: 24px;">
            <div>
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px">
                    <label class="form-label" style="margin:0">Select Services</label>
                    <button type="button" class="btn link" style="padding:0; font-size:12px" onclick="toggleChecks('services[]', true)">Select All</button>
                </div>
                <div class="selection-box">
                    <?php foreach ($services as $s): ?>
                        <div class="selection-item">
                            <input type="checkbox" name="services[]" value="<?=$s['id']?>" id="svc-<?=$s['id']?>">
                            <label for="svc-<?=$s['id']?>"><?=e($s['service_name'])?></label>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <div>
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px">
                    <label class="form-label" style="margin:0">Select Locations</label>
                    <button type="button" class="btn link" style="padding:0; font-size:12px" onclick="toggleChecks('locations[]', true)">Select All</button>
                </div>
                <div class="selection-box">
                    <?php foreach ($locations as $l): ?>
                        <div class="selection-item">
                            <input type="checkbox" name="locations[]" value="<?=$l['id']?>" id="loc-<?=$l['id']?>">
                            <label for="loc-<?=$l['id']?>"><?=e($l['name'])?></label>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        
        <div style="display:flex; justify-content:flex-end">
            <button type="submit" class="btn primary"><?=ui_icon('processing',18)?> Generate Landing Pages</button>
        </div>
    </form>
</div>

<div class="card" style="padding:0">
    <div style="padding:20px; border-bottom:1px solid var(--border)">
        <h3 style="margin:0">Existing Landing Pages</h3>
    </div>
    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th>Landing Page</th>
                    <th>Service</th>
                    <th>Location</th>
                    <th>Slug</th>
                    <th>Status</th>
                    <th>Created</th>
                    <th style="text-align:right">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($landings)): ?>
                    <tr>
                        <td colspan="7" style="text-align:center; padding:40px" class="muted">No landing pages generated yet.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($landings as $l): ?>
                        <tr>
                            <td>
                                <div style="font-weight:600; color:var(--text)"><?=e($l['title'])?></div>
                                <div class="muted" style="font-size:12px"><?=e(substr($l['description'],0,60))?>...</div>
                            </td>
                            <td><?=e($l['service_name'])?></td>
                            <td><?=e($l['location_name'])?></td>
                            <td><code>/l/<?=e($l['slug'])?></code></td>
                            <td><span class="status-pill status-active"><?=e($l['status'])?></span></td>
                            <td><?=date('M j, Y', strtotime($l['created_at']))?></td>
                            <td style="text-align:right">
                                <div style="display:flex; gap:8px; justify-content:flex-end">
                                    <a href="<?=url('admin/seo_edit.php?id='.$l['id'])?>" class="btn secondary sm" title="Edit Optimization"><?=ui_icon('settings',14)?></a>
                                    <a href="<?=url('l/'.$l['slug'])?>" target="_blank" class="btn secondary sm" title="View Landing"><?=ui_icon('eye',14)?></a>
                                    <a href="?delete=<?=$l['id']?>&csrf_token=<?=csrf_token()?>" class="btn danger sm" onclick="return confirm('Are you sure?')" title="Delete"><?=ui_icon('trash',14)?></a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
function toggleChecks(name, val) {
    document.querySelectorAll(`input[name="${name}"]`).forEach(i => i.checked = val);
}
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
