"""PHP Generator for LandingForge."""


class PHPGenerator:
    """Generates PHP files for language detection and redirects."""

    def __init__(self, config: dict):
        self.config = config
        self.languages = config.get("languages", {})

    def generate_index_php(self) -> str:
        supported = self.languages.get("supported", [])
        default_lang = self.languages.get("default", "en")
        codes = [l["code"] for l in supported]
        codes_php = "array('" + "', '".join(codes) + "')"
        return f"""<?php
/**
 * LandingForge — index.php
 * Language detection and redirect handler
 */
require_once __DIR__ . '/includes/detect-language.php';

$supported = {codes_php};
$default   = '{default_lang}';

// 1. Check language cookie
$lang = isset($_COOKIE['lf_lang']) ? trim($_COOKIE['lf_lang']) : '';

// 2. Check query parameter
if (empty($lang) && isset($_GET['lang'])) {{
    $lang = trim($_GET['lang']);
}}

// 3. Fall back to Accept-Language header detection
if (empty($lang)) {{
    $lang = detectLanguage($supported, $default);
}}

// Validate against supported list
if (!in_array($lang, $supported, true)) {{
    $lang = $default;
}}

// Set language cookie for future visits (1 year, SameSite=Lax)
setcookie('lf_lang', $lang, [
    'expires'  => time() + 365 * 86400,
    'path'     => '/',
    'samesite' => 'Lax',
]);

// Redirect to language subdirectory or serve default
if ($lang !== $default) {{
    $target = '/lang/' . rawurlencode($lang) . '/';
    header('Location: ' . $target, true, 302);
    exit;
}}

// Serve the default language index
readfile(__DIR__ . '/index.html');
"""

    def generate_language_detection_php(self) -> str:
        return r"""<?php
/**
 * LandingForge — includes/detect-language.php
 * Reusable language detection from Accept-Language header.
 */

/**
 * Parse the Accept-Language header and return the best-matching
 * language code from the supported list.
 *
 * @param  string[] $supported  List of supported language codes (e.g. ['en','es','fr'])
 * @param  string   $default    Default language code to return on no match
 * @return string               The matched language code
 */
function detectLanguage(array $supported, string $default): string {
    $header = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '';
    if (empty($header)) {
        return $default;
    }

    // Parse header: "en-US,en;q=0.9,es;q=0.8"
    $langs = [];
    foreach (explode(',', $header) as $part) {
        $part = trim($part);
        if (preg_match('/^([a-zA-Z]{1,8}(?:-[a-zA-Z0-9]{1,8})*)(?:;q=([0-9.]+))?$/', $part, $m)) {
            $code    = strtolower(substr($m[1], 0, 2));
            $quality = isset($m[2]) ? (float)$m[2] : 1.0;
            // Keep the highest quality for each code
            if (!isset($langs[$code]) || $langs[$code] < $quality) {
                $langs[$code] = $quality;
            }
        }
    }

    // Sort by quality descending
    arsort($langs);

    foreach (array_keys($langs) as $code) {
        if (in_array($code, $supported, true)) {
            return $code;
        }
    }

    return $default;
}
"""

    def generate_redirect_php(self) -> str:
        return r"""<?php
/**
 * LandingForge — includes/redirect.php
 * Simple redirect map handler with 301 redirects and 404 fallback.
 */

// Redirect map: old path => new path
$redirects = [
    '/home'    => '/',
    '/index'   => '/',
    '/blog/'   => '/blog.html',
    '/about/'  => '/about.html',
    '/privacy' => '/privacy.html',
    '/terms'   => '/terms.html',
    '/cookies' => '/cookies.html',
];

$requestUri = strtok($_SERVER['REQUEST_URI'] ?? '/', '?');
$requestUri = '/' . ltrim(rtrim($requestUri, '/'), '/');

if (isset($redirects[$requestUri])) {
    $destination = $redirects[$requestUri];
    header('Location: ' . $destination, true, 301);
    exit;
}

// 404 fallback
http_response_code(404);
$notFound = __DIR__ . '/../404.html';
if (file_exists($notFound)) {
    readfile($notFound);
} else {
    echo '<!DOCTYPE html><html><head><title>404 Not Found</title></head>'
       . '<body><h1>404 — Page Not Found</h1><p><a href="/">Return Home</a></p></body></html>';
}
"""
