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

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

// Ensure columns exist (Auto-migration)
try { $pdo->exec("ALTER TABLE seo_landings ADD COLUMN focus_keyword TEXT"); } catch (PDOException $e) {}
try { $pdo->exec("ALTER TABLE seo_landings ADD COLUMN meta_keywords TEXT"); } catch (PDOException $e) {}

$id = (int)($_GET['id'] ?? 0);
$success = '';
$error = '';

if ($id > 0) {
    $stmt = $pdo->prepare("SELECT * FROM seo_landings WHERE id = ?");
    $stmt->execute([$id]);
    $landing = $stmt->fetch();
    
    if (!$landing) {
        redirect(url('admin/seo_hub.php'));
    }
} else {
    redirect(url('admin/seo_hub.php'));
}

// Handle Update
if (is_post()) {
    ensure_csrf();
    
    $title = sanitize_str($_POST['title'] ?? '');
    $description = sanitize_str($_POST['description'] ?? '');
    $h1 = sanitize_str($_POST['h1_title'] ?? '');
    $focusKeyword = sanitize_str($_POST['focus_keyword'] ?? '');
    $contentJson = $_POST['content_json'] ?? '';
    $status = sanitize_str($_POST['status'] ?? 'active');
    
    if (empty($title) || empty($h1)) {
        $error = 'Title and H1 are required.';
    } else {
        try {
            $stmt = $pdo->prepare("UPDATE seo_landings SET title = ?, description = ?, h1_title = ?, focus_keyword = ?, content_json = ?, status = ? WHERE id = ?");
            $stmt->execute([$title, $description, $h1, $focusKeyword, $contentJson, $status, $id]);
            $success = 'Landing page updated successfully.';
            // Refresh data
            $landing['title'] = $title;
            $landing['description'] = $description;
            $landing['h1_title'] = $h1;
            $landing['focus_keyword'] = $focusKeyword;
            $landing['content_json'] = $contentJson;
            $landing['status'] = $status;
        } catch (PDOException $e) {
            $error = 'Failed to update landing page.';
        }
    }
}

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

<style>
    .seo-editor {
        max-width: 1000px;
        margin: 0 auto;
    }
    
    .seo-score-gauge {
        background: #fff;
        border: 1px solid var(--border);
        border-radius: 16px;
        padding: 24px;
        margin-bottom: 32px;
        display: flex;
        align-items: center;
        gap: 32px;
    }
    
    .score-circle {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        border: 8px solid #f1f5f9;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28px;
        font-weight: 800;
        position: relative;
    }
    
    .score-circle svg {
        position: absolute;
        top: -8px;
        left: -8px;
        width: 100px;
        height: 100px;
        transform: rotate(-90deg);
    }
    
    .score-circle circle {
        fill: none;
        stroke-width: 8;
        stroke-linecap: round;
        transition: stroke-dashoffset 0.5s ease;
    }
    
    .score-good { color: #16a34a; }
    .score-ok { color: #d97706; }
    .score-bad { color: #dc2626; }
    
    .recommendations {
        flex: 1;
    }
    
    .rec-item {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 14px;
        margin-bottom: 4px;
    }
    
    .rec-pass { color: #16a34a; }
    .rec-fail { color: #dc2626; }
</style>

<div class="seo-editor">
    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:32px">
        <div>
            <h1 style="margin:0">Edit Landing Page</h1>
            <p class="muted">Optimize programmatic content for <code>/l/<?=e($landing['slug'])?></code></p>
        </div>
        <a href="<?=url('admin/seo_hub.php')?>" class="btn ghost">← Back to Hub</a>
    </div>


    <div class="seo-score-gauge">
        <div class="score-circle" id="seo-score-circle">
            <svg>
                <circle cx="50" cy="50" r="46" id="score-progress"></circle>
            </svg>
            <span id="score-val">0</span>
        </div>
        <div class="recommendations">
            <h4 style="margin:0 0 12px">SEO Health Score</h4>
            <div id="seo-recs"></div>
        </div>
    </div>

    <form method="post" id="seo-form">
        <?=csrf_field()?>
        <div class="card">
            <div class="form-group">
                <label class="form-label">Focus Keyword</label>
                <input type="text" name="focus_keyword" id="focus_keyword" class="form-input" value="<?=e($landing['focus_keyword'] ?? '')?>" placeholder="e.g. business registration lagos">
                <p class="form-help">The main keyword you want this page to rank for.</p>
            </div>
            
            <div class="form-group">
                <label class="form-label">SEO Title</label>
                <input type="text" name="title" id="seo_title" class="form-input" value="<?=e($landing['title'] ?? '')?>" required>
                <p class="form-help" id="title-help">Optimal: 50-60 characters.</p>
            </div>

            <div class="form-group">
                <label class="form-label">Main Heading (H1)</label>
                <input type="text" name="h1_title" id="h1_title" class="form-input" value="<?=e($landing['h1_title'] ?? '')?>" required>
            </div>

            <div class="form-group">
                <label class="form-label">Meta Description</label>
                <textarea name="description" id="meta_description" class="form-input" rows="3"><?=e($landing['description'] ?? '')?></textarea>
                <p class="form-help" id="desc-help">Optimal: 120-160 characters.</p>
            </div>

            <div class="form-group">
                <label class="form-label">Page Content (HTML/Text)</label>
                <textarea name="content_json" id="content_json" class="form-input" rows="12" placeholder="Enter the main body content for this landing page..."><?=e($landing['content_json'] ?? '')?></textarea>
                <p class="form-help">This is the main content displayed on the landing page.</p>
            </div>

            <div class="form-group">
                <label class="form-label">Status</label>
                <select name="status" class="form-input">
                    <option value="active" <?=$landing['status']==='active'?'selected':''?>>Active</option>
                    <option value="draft" <?=$landing['status']==='draft'?'selected':''?>>Draft</option>
                </select>
            </div>

            <div style="display:flex; justify-content:flex-end; gap:12px; margin-top:24px">
                <button type="submit" class="btn primary">Save Optimization</button>
            </div>
        </div>
    </form>
</div>

<script>
function calculateSeoScore() {
    const title = document.getElementById('seo_title').value;
    const h1 = document.getElementById('h1_title').value;
    const desc = document.getElementById('meta_description').value;
    const kw = document.getElementById('focus_keyword').value.toLowerCase();
    
    let score = 0;
    const checks = [];

    // Title Checks (25 pts)
    if (title.length >= 40 && title.length <= 65) {
        score += 25;
        checks.push({pass:true, text:'Title length is optimal'});
    } else {
        checks.push({pass:false, text:'Title should be 40-65 chars'});
    }

    // Keyword in Title (15 pts)
    if (kw && title.toLowerCase().includes(kw)) {
        score += 15;
        checks.push({pass:true, text:'Keyword found in title'});
    } else if (kw) {
        checks.push({pass:false, text:'Keyword missing from title'});
    }

    // H1 Checks (20 pts)
    if (h1.length > 0) {
        score += 10;
        if (kw && h1.toLowerCase().includes(kw)) {
            score += 10;
            checks.push({pass:true, text:'Keyword found in H1'});
        } else if (kw) {
            checks.push({pass:false, text:'Keyword missing from H1'});
        }
    }

    // Meta Description (20 pts)
    if (desc.length >= 100 && desc.length <= 160) {
        score += 20;
        checks.push({pass:true, text:'Meta description length is optimal'});
    } else {
        checks.push({pass:false, text:'Meta description should be 100-160 chars'});
    }

    // Keyword in Meta (20 pts)
    if (kw && desc.toLowerCase().includes(kw)) {
        score += 20;
        checks.push({pass:true, text:'Keyword found in meta description'});
    } else if (kw) {
        checks.push({pass:false, text:'Keyword missing from meta description'});
    }

    // Update UI
    const scoreVal = document.getElementById('score-val');
    const scoreCircle = document.getElementById('seo-score-circle');
    const progress = document.getElementById('score-progress');
    const recs = document.getElementById('seo-recs');
    
    scoreVal.innerText = score;
    
    // SVG Progress
    const radius = 46;
    const circumference = 2 * Math.PI * radius;
    progress.style.strokeDasharray = `${circumference} ${circumference}`;
    const offset = circumference - (score / 100) * circumference;
    progress.style.strokeDashoffset = offset;
    
    // Color
    scoreCircle.className = 'score-circle ' + (score > 80 ? 'score-good' : (score > 50 ? 'score-ok' : 'score-bad'));
    progress.style.stroke = score > 80 ? '#16a34a' : (score > 50 ? '#d97706' : '#dc2626');

    recs.innerHTML = checks.map(c => `
        <div class="rec-item ${c.pass?'rec-pass':'rec-fail'}">
            ${c.pass ? '<?=ui_icon('check',14)?>' : '<?=ui_icon('logout',14)?>'}
            ${c.text}
        </div>
    `).join('');
}

document.querySelectorAll('#seo-form input, #seo-form textarea').forEach(el => {
    el.addEventListener('input', calculateSeoScore);
});

calculateSeoScore();
</script>

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