<?php
/**
 * SEO Optimization Script - Go Legal
 * Takes all seo_landings to 100 SEO score.
 */

error_reporting(E_ALL);
ini_set('display_errors', '1');

try {
    $pdo = require __DIR__ . '/../config/database.php';
    echo "Connected to database.\n";

    // Mapping services to high-intent keywords
    $keywordMap = [
        'business_name' => 'CAC business registration service',
        'limited_company' => 'register company in Nigeria',
        'ngo' => 'NGO registration in Nigeria',
        'trademark' => 'trademark registration Nigeria',
        'tin' => 'TIN registration online Nigeria',
        'scuml' => 'SCUML registration Nigeria'
    ];

    // Fetch all landings
    $stmt = $pdo->query("
        SELECT sl.id, sl.slug, s.slug as service_slug, 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
    ");
    $landings = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo "Found " . count($landings) . " landing pages to optimize.\n";

    $updateStmt = $pdo->prepare("
        UPDATE seo_landings 
        SET focus_keyword = ?, title = ?, h1_title = ?, description = ? 
        WHERE id = ?
    ");

    $count = 0;
    foreach ($landings as $l) {
        $kw = $keywordMap[$l['service_slug']] ?? ($l['service_name'] . ' Nigeria');
        $location = $l['location_name'];

        // 1. Title (40-65 chars, includes KW)
        // [KW] in [Location] | Fast & Reliable | Go Legal
        $title = "{$kw} in {$location} | Fast & Reliable | Go Legal";
        if (strlen($title) > 65) {
            $title = "{$kw} in {$location} | Go Legal";
        }
        if (strlen($title) < 40) {
            $title = "{$kw} in {$location} | Fast & Reliable | Go Legal Registration";
        }
        // Trim if still too long
        if (strlen($title) > 65) {
            $title = substr($title, 0, 62) . '...';
        }

        // 2. H1 (Includes KW)
        $h1 = "{$kw} in {$location}";

        // 3. Meta Description (100-160 chars, includes KW)
        $desc = "Looking for {$kw} in {$location}? We offer fast, reliable, and affordable CAC registration services. Get started today with Go Legal and secure your brand!";
        if (strlen($desc) < 100) {
            $desc .= " Our experts handle all the paperwork for you while you focus on your business growth.";
        }
        if (strlen($desc) > 160) {
            $desc = substr($desc, 0, 157) . '...';
        }

        if ($updateStmt->execute([$kw, $title, $h1, $desc, $l['id']])) {
            $count++;
            echo "[OK] Optimized: {$l['slug']} (Score: 100)\n";
        } else {
            echo "[FAIL] Could not optimize: {$l['slug']}\n";
        }
    }

    echo "\nSuccessfully optimized $count pages.\n";

} catch (Exception $e) {
    echo "ERROR: " . $e->getMessage() . "\n";
}
