<?php
// seo-router.php - Central Router for Programmatic SEO Location Landing Pages

// 1. Retrieve the route parameter
$route = isset($_GET['route']) ? trim($_GET['route']) : '';

if (empty($route)) {
    header("HTTP/1.1 404 Not Found");
    include('404.php');
    exit;
}

// 2. Define Country Maps
$countries_map = [
    'pakistan' => ['name' => 'Pakistan', 'country' => 'Pakistan', 'population' => '240M+'],
    'usa' => ['name' => 'USA', 'country' => 'USA', 'population' => '330M+'],
    'uk' => ['name' => 'United Kingdom', 'country' => 'United Kingdom', 'population' => '67M+'],
    'united-kingdom' => ['name' => 'United Kingdom', 'country' => 'United Kingdom', 'population' => '67M+'],
    'canada' => ['name' => 'Canada', 'country' => 'Canada', 'population' => '38M+'],
    'australia' => ['name' => 'Australia', 'country' => 'Australia', 'population' => '26M+'],
    'uae' => ['name' => 'UAE', 'country' => 'UAE', 'population' => '10M+']
];

// 3. Scan cached cities
$cities_map = [];
$city_files = glob(__DIR__ . '/cache/cities/*.json');
if (is_array($city_files)) {
    foreach ($city_files as $file) {
        $slug = basename($file, '.json');
        $data = json_decode(file_get_contents($file), true);
        if ($data) {
            $cities_map[$slug] = [
                'name' => isset($data['name']) ? $data['name'] : (isset($data['city_name']) ? $data['city_name'] : ''),
                'country' => isset($data['country']) ? $data['country'] : '',
                'population' => isset($data['population']) ? $data['population'] : ''
            ];
        }
    }
}

// Combine locations and sort by length descending to match longest slugs first
$locations_map = array_merge($countries_map, $cities_map);
uksort($locations_map, function($a, $b) {
    return strlen($b) - strlen($a);
});

// 4. Match location and prefix keyword
$found_location_slug = null;
$found_location = null;
$found_keyword = null;

foreach ($locations_map as $loc_slug => $loc_info) {
    // Check if route ends with "-in-$loc_slug"
    $suffix_in = "-in-" . $loc_slug;
    if (substr($route, -strlen($suffix_in)) === $suffix_in) {
        $found_location_slug = $loc_slug;
        $found_location = $loc_info;
        $found_keyword = substr($route, 0, -strlen($suffix_in));
        break;
    }
    // Check if route ends with "-$loc_slug"
    $suffix_dash = "-" . $loc_slug;
    if (substr($route, -strlen($suffix_dash)) === $suffix_dash) {
        $found_location_slug = $loc_slug;
        $found_location = $loc_info;
        $found_keyword = substr($route, 0, -strlen($suffix_dash));
        break;
    }
}

// If no valid location or keyword prefix matches, load 404
if (!$found_location_slug || !$found_keyword) {
    header("HTTP/1.1 404 Not Found");
    include('404.php');
    exit;
}

// 5. Define PSEO Keywords mapping to physical template files
$keyword_templates = [
    // Web Development
    'web-development-agency' => ['file' => 'web-development.php', 'name' => 'Web Development'],
    'top-web-development-company' => ['file' => 'web-development.php', 'name' => 'Web Development'],
    'best-web-development-agency' => ['file' => 'web-development.php', 'name' => 'Web Development'],
    'top-web-development-agency' => ['file' => 'web-development.php', 'name' => 'Web Development'],
    'best-web-development-company' => ['file' => 'web-development.php', 'name' => 'Web Development'],
    'affordable-web-development-agency' => ['file' => 'web-development.php', 'name' => 'Web Development'],
    
    // App Development
    'flutter-app-developer' => ['file' => 'app-development.php', 'name' => 'Flutter App Development'],
    'react-native-app-developer' => ['file' => 'app-development.php', 'name' => 'React Native App Development'],
    'number-1-flutter-developer' => ['file' => 'app-development.php', 'name' => 'Flutter App Development'],
    'app-development-agency' => ['file' => 'app-development.php', 'name' => 'App Development'],
    'mobile-app-development' => ['file' => 'app-development.php', 'name' => 'Mobile App Development'],
    
    // AI Automation
    'ai-automation-agency' => ['file' => 'ai-automation.php', 'name' => 'AI Automation'],
    'best-ai-automation-agency' => ['file' => 'ai-automation.php', 'name' => 'AI Automation'],
    
    // SaaS Development
    'saas-development-company' => ['file' => 'saas-development.php', 'name' => 'SaaS Development'],
    'top-saas-development-company' => ['file' => 'saas-development.php', 'name' => 'SaaS Development'],
    
    // UI/UX Design
    'ui-ux-design-agency' => ['file' => 'ui-ux-design.php', 'name' => 'UI/UX Design'],
    'top-ui-ux-design' => ['file' => 'ui-ux-design.php', 'name' => 'UI/UX Design'],
    
    // Graphic Design
    'graphic-design-agency' => ['file' => 'graphic-design.php', 'name' => 'Graphic Design'],
    
    // Digital Marketing
    'digital-marketing-agency' => ['file' => 'digital-marketing.php', 'name' => 'Digital Marketing'],
    'best-digital-marketing-agency' => ['file' => 'digital-marketing.php', 'name' => 'Digital Marketing'],
    'number-1-digital-marketing-agency' => ['file' => 'digital-marketing.php', 'name' => 'Digital Marketing'],
    
    // Domain & Hosting
    'domain-hosting-services' => ['file' => 'domain-hosting.php', 'name' => 'Domain & Hosting'],
    
    // General Software Agency / Software House
    'best-software-agency' => ['file' => 'service.php', 'name' => 'Software Agency Services'],
    'number-1-software-house' => ['file' => 'service.php', 'name' => 'Software House Services'],
    'best-software-development-company' => ['file' => 'service.php', 'name' => 'Software Development Services'],
    'top-software-house' => ['file' => 'service.php', 'name' => 'Software House Services']
];

if (!isset($keyword_templates[$found_keyword])) {
    header("HTTP/1.1 404 Not Found");
    include('404.php');
    exit;
}

$mapped_template = $keyword_templates[$found_keyword];
$template_file = $mapped_template['file'];
$service_name = $mapped_template['name'];
$location_name = $found_location['name'];
$location_country = $found_location['country'];
$location_population = $found_location['population'];

// 6. Set variables for the dynamic templates to load
$is_pseo = true;
$pseo_location_slug = $found_location_slug;
$pseo_location_name = $location_name;
$pseo_location_country = $location_country;
$pseo_keyword = $found_keyword;

// Localized optimization copy (Roman-Urdu context for Pakistan)
$is_pakistan = (strtolower($location_country) === 'pakistan' || strtolower($found_location_slug) === 'pakistan');

if ($is_pakistan) {
    $page_title = "Best {$service_name} Agency in {$location_name} | Prime Vertex Sphere";
    $page_description = "Prime Vertex Sphere (Vertex Sphere) is the premier {$service_name} agency in {$location_name}, Pakistan. We build customized, high-performance web apps, mobile solutions, and AI automation.";
} else {
    $page_title = "Premium {$service_name} in {$location_name}, {$location_country} | Prime Vertex Sphere";
    $page_description = "Get expert {$service_name} in {$location_name}, {$location_country}. Prime Vertex Sphere delivers high-converting websites, mobile apps, and custom digital systems.";
}

// Generate the heading format
$pseo_heading = $service_name . " <span class='d-block' style='font-size: 28px; color: #a70006; margin-top: 10px;'>in " . $location_name . "</span>";

// Generate LocalBusiness + Service Schema Graph for pSEO pages
$schema_markup = '{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "LocalBusiness",
      "@id": "https://primevertexsphere.com/' . htmlspecialchars($route) . '#localbusiness",
      "name": "Prime Vertex Sphere - ' . htmlspecialchars($service_name) . ' in ' . htmlspecialchars($location_name) . '",
      "image": "https://primevertexsphere.com/assets/images/logo.png",
      "url": "https://primevertexsphere.com/' . htmlspecialchars($route) . '",
      "telephone": "+923188428922",
      "email": "info@primevertexsphere.com",
      "address": {
        "@type": "PostalAddress",
        "addressLocality": "' . htmlspecialchars($location_name) . '",
        "addressCountry": "' . htmlspecialchars($location_country) . '"
      },
      "openingHoursSpecification": {
        "@type": "OpeningHoursSpecification",
        "dayOfWeek": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"],
        "opens": "09:00",
        "closes": "18:00"
      }
    },
    {
      "@type": "Service",
      "name": "' . htmlspecialchars($service_name) . ' in ' . htmlspecialchars($location_name) . '",
      "provider": {
        "@type": "Organization",
        "@id": "https://primevertexsphere.com/#organization",
        "name": "Prime Vertex Sphere",
        "url": "https://primevertexsphere.com"
      },
      "areaServed": {
        "@type": "City",
        "name": "' . htmlspecialchars($location_name) . '"
      },
      "description": "' . htmlspecialchars($page_description) . '"
    }
  ]
}';

// Route internally by including the physical template file
if (file_exists($template_file)) {
    include($template_file);
} else {
    header("HTTP/1.1 404 Not Found");
    include('404.php');
    exit;
}
?>
