<?php
/**
 * URL Helper Functions for SEO-Friendly URLs
 */

/**
 * Get the base path for the application
 * @return string
 */
function getBasePath() {
    // Return empty string for root-relative paths
    return '';
}

/**
 * Generate SEO-friendly URL for city-service page
 * @param string $citySlug
 * @param string $serviceSlug
 * @param string $format - 'city-service' or 'service-in-city'
 * @return string
 */
function getCityServiceUrl($citySlug, $serviceSlug, $format = 'city-service') {
    $basePath = getBasePath();
    
    if ($format === 'service-in-city') {
        return $basePath . '/' . $serviceSlug . '-in-' . $citySlug . '/';
    }
    
    // Default: city/service format
    return $basePath . '/' . $citySlug . '/' . $serviceSlug . '/';
}

/**
 * Generate URL for city services overview
 * @param string $citySlug
 * @return string
 */
function getCityServicesUrl($citySlug) {
    $basePath = getBasePath();
    // Preferred pretty URL: /city-services/{city}/
    return $basePath . '/city-services/' . urlencode($citySlug) . '/';
}

/**
 * Generate URL for service overview across cities
 * @param string $serviceSlug
 * @return string
 */
function getServiceCitiesUrl($serviceSlug) {
    $basePath = getBasePath();
    return $basePath . '/' . $serviceSlug . '-services/';
}

/**
 * Generate URL for individual city page
 * @param string $citySlug
 * @return string
 */
function getCityUrl($citySlug) {
    $basePath = getBasePath();
    return $basePath . '/' . $citySlug . '/';
}

/**
 * Generate breadcrumb data for SEO
 * @param string $citySlug
 * @param string $serviceSlug
 * @param string $cityName
 * @param string $serviceName
 * @return array
 */
function generateBreadcrumbs($citySlug = null, $serviceSlug = null, $cityName = null, $serviceName = null) {
    $basePath = getBasePath();
    
    $breadcrumbs = [
        [
            'name' => 'Home',
            'url' => $basePath . '/'
        ],
        [
            'name' => 'Services',
            'url' => $basePath . '/services.php'
        ]
    ];
    
    if ($citySlug && $serviceSlug) {
        $breadcrumbs[] = [
            'name' => $cityName ?: ucfirst($citySlug),
            'url' => getCityServicesUrl($citySlug)
        ];
        $breadcrumbs[] = [
            'name' => $serviceName ?: ucfirst(str_replace('-', ' ', $serviceSlug)),
            'url' => getCityServiceUrl($citySlug, $serviceSlug)
        ];
    } elseif ($citySlug) {
        $breadcrumbs[] = [
            'name' => $cityName ?: ucfirst($citySlug),
            'url' => getCityServicesUrl($citySlug)
        ];
    } elseif ($serviceSlug) {
        $breadcrumbs[] = [
            'name' => $serviceName ?: ucfirst(str_replace('-', ' ', $serviceSlug)),
            'url' => getServiceCitiesUrl($serviceSlug)
        ];
    }
    
    return $breadcrumbs;
}

/**
 * Generate canonical URL for current page
 * @param string $citySlug
 * @param string $serviceSlug
 * @return string
 */
function getCanonicalUrl($citySlug = null, $serviceSlug = null) {
    if ($citySlug && $serviceSlug) {
        return getCityServiceUrl($citySlug, $serviceSlug);
    }
    
    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    $currentPath = $_SERVER['REQUEST_URI'];
    $currentPath = strtok($currentPath, '?'); // Remove query parameters
    
    return $protocol . '://' . $host . $currentPath;
}

/**
 * Generate Open Graph URL
 * @param string $citySlug
 * @param string $serviceSlug
 * @return string
 */
function getOgUrl($citySlug = null, $serviceSlug = null) {
    return getCanonicalUrl($citySlug, $serviceSlug);
}

/**
 * Convert service name to URL-friendly slug
 * @param string $serviceName
 * @return string
 */
function serviceNameToSlug($serviceName) {
    $slug = strtolower($serviceName);
    $slug = str_replace(['&', ' and ', ' '], ['-', '-', '-'], $slug);
    $slug = preg_replace('/[^a-z0-9-]/', '', $slug);
    $slug = preg_replace('/-+/', '-', $slug);
    return trim($slug, '-');
}

/**
 * Convert city name to URL-friendly slug
 * @param string $cityName
 * @return string
 */
function cityNameToSlug($cityName) {
    $slug = strtolower($cityName);
    $slug = str_replace(' ', '-', $slug);
    $slug = preg_replace('/[^a-z0-9-]/', '', $slug);
    $slug = preg_replace('/-+/', '-', $slug);
    return trim($slug, '-');
}

/**
 * Generate sitemap URLs for all city-service combinations
 * @return array
 */
function generateSitemapUrls() {
    global $pdo;
    
    $urls = [];
    
    $stmt = $pdo->query("
        SELECT c.slug as city_slug, s.slug as service_slug, cs.updated_at
        FROM city_service cs
        JOIN cities c ON cs.city_id = c.id
        JOIN services s ON cs.service_id = s.id
        ORDER BY c.name, s.name
    ");
    
    while ($row = $stmt->fetch()) {
        $urls[] = [
            'url' => getCityServiceUrl($row['city_slug'], $row['service_slug']),
            'lastmod' => $row['updated_at'] ? date('Y-m-d', strtotime($row['updated_at'])) : date('Y-m-d'),
            'changefreq' => 'weekly',
            'priority' => '0.8'
        ];
    }
    
    return $urls;
}

/**
 * Redirect old URLs to new SEO-friendly URLs
 * @param string $citySlug
 * @param string $serviceSlug
 */
function redirectToSeoUrl($citySlug, $serviceSlug) {
    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    $newUrl = $protocol . '://' . $host . getCityServiceUrl($citySlug, $serviceSlug);
    header("Location: $newUrl", true, 301);
    exit;
}
?>