<?php
/**
 * Simple partial include helper.
 * Usage: part('hero') will include inc/hero.php
 */
function part(string $name): void {
    $path = __DIR__ . '/' . trim($name) . '.php';
    if (file_exists($path)) {
        include $path;
    } else {
        throw new Exception('Partial file not found: ' . $path);
    }
}

/**
 * Language detection via URL prefix. Returns array with keys: lang, prefix, switchToAr, switchToEn
 */
function detect_lang(): array {
    $reqPathRaw = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
    // Strip base directory (e.g., '/altoukhi') from the request path before language detection
    $docRoot = $_SERVER['DOCUMENT_ROOT'] ?? '';
    $docRoot = rtrim(str_replace('\\', '/', $docRoot), '/');
    $projectRoot = rtrim(str_replace('\\', '/', dirname(__DIR__)), '/');
    $basePrefix = '';
    if ($docRoot && strpos($projectRoot, $docRoot) === 0) {
        $basePrefix = substr($projectRoot, strlen($docRoot));
        $basePrefix = str_replace('\\', '/', $basePrefix);
        $basePrefix = rtrim($basePrefix, '/');
    } else {
        $scriptName = $_SERVER['SCRIPT_NAME'] ?? '/';
        $basePrefix = rtrim(str_replace('\\', '/', dirname($scriptName)), '/');
    }
    if ($basePrefix !== '' && $basePrefix !== '/' && strpos($reqPathRaw, $basePrefix . '/') === 0) {
        $reqPathRaw = substr($reqPathRaw, strlen($basePrefix));
        if ($reqPathRaw === '') { $reqPathRaw = '/'; }
    }
    $segments = array_values(array_filter(explode('/', $reqPathRaw), fn($s) => $s !== ''));

    // Default language is English at root. Explicit prefixes: /ar, /en
    $first = isset($segments[0]) ? strtolower($segments[0]) : '';
    if ($first === 'ar') {
        $lang = 'ar';
        $prefix = '/ar';
        array_shift($segments);
    } elseif ($first === 'en') {
        $lang = 'en';
        $prefix = '/en';
        array_shift($segments);
    } else {
        $lang = 'en';
        $prefix = '';
    }

    $pathSansLang = '/' . implode('/', $segments);
    if ($pathSansLang === '//') { $pathSansLang = '/'; }

    // Build switch URLs
    $switchToEn = $pathSansLang === '/' ? '/' : $pathSansLang; // default EN has no prefix
    $switchToAr = '/ar' . ($pathSansLang === '/' ? '' : $pathSansLang);

    return [ 'lang' => $lang, 'prefix' => $prefix, 'switchToAr' => $switchToAr, 'switchToEn' => $switchToEn ];
}

/**
 * Load translations JSON once per request.
 */
function load_translations(): array {
    static $cache = null;
    if ($cache !== null) return $cache;
    $file = dirname(__DIR__) . '/assets/i18n/lang.json';
    if (!file_exists($file)) return $cache = [];
    $json = file_get_contents($file);
    $data = json_decode($json, true) ?: [];
    return $cache = $data;
}

/**
 * Translate helper: t('group.key', 'fallback') uses current detected language.
 */
function t(string $key, ?string $fallback = null): string {
    static $lang = null, $map = null;
    if ($lang === null) {
        $i18n = detect_lang();
        $lang = $i18n['lang'];
        $map = load_translations();
    }
    $parts = explode('.', $key);
    $node = $map[$lang] ?? [];
    foreach ($parts as $p) {
        if (!is_array($node) || !array_key_exists($p, $node)) {
            return $fallback ?? $key;
        }
        $node = $node[$p];
    }
    return is_string($node) ? $node : ($fallback ?? $key);
}

/**
 * Debug mode helper
 */
function alt_is_debug_mode(): bool {
    return isset($_GET['debug']) && $_GET['debug'] === '1';
}


/**
 * Compute base prefix (e.g., '/altoukhi') based on server environment.
 * Strips language suffixes like '/ar' or '/en' if present at the end.
 */
function compute_base_prefix(): string {
    $docRoot = $_SERVER['DOCUMENT_ROOT'] ?? '';
    $docRoot = rtrim(str_replace('\\', '/', $docRoot), '/');
    $projectRoot = rtrim(str_replace('\\', '/', dirname(__DIR__)), '/');
    if ($docRoot && strpos($projectRoot, $docRoot) === 0) {
        $base = substr($projectRoot, strlen($docRoot));
        $base = str_replace('\\', '/', $base);
        $base = rtrim($base, '/');
    } else {
        $scriptName = $_SERVER['SCRIPT_NAME'] ?? '/';
        $base = rtrim(str_replace('\\', '/', dirname($scriptName)), '/');
    }
    if ($base !== '' && $base !== '/' && preg_match('#/(ar|en)$#i', $base)) {
        $base = preg_replace('#/(ar|en)$#i', '', $base);
    }
    if ($base === '/' || $base === '.' || $base === '') {
        $base = '';
    }
    return $base;
}

/**
 * Start global prefix rewrite once per request. Prepends base prefix to href/src/action that start with '/'.
 */
function start_global_prefix_rewrite(): void {
    if (defined('ALT_GLOBAL_PREFIX_REWRITE')) return;
    $basePrefix = compute_base_prefix();
    define('ALT_GLOBAL_PREFIX_REWRITE', true);
    ob_start(function($html) use ($basePrefix) {
        $pattern = '/\b(href|src|action)="(\/[^"]*)"/i';
        $html = preg_replace_callback($pattern, function($m) use ($basePrefix){
            $url = $m[2];
            if (strpos($url, '//') === 0) return $m[0];
            if ($basePrefix !== '' && strpos($url, $basePrefix . '/') === 0) return $m[0];
            return $m[1] . '="' . $basePrefix . $url . '"';
        }, $html);
        if ($basePrefix !== '') {
            $double = $basePrefix . $basePrefix . '/';
            $single = $basePrefix . '/';
            $html = str_replace('="' . $double, '="' . $single, $html);
        }
        return $html;
    });
}

/**
 * Get the correct URL path with base prefix for AJAX requests
 */
function get_ajax_url(string $endpoint): string {
    $basePrefix = compute_base_prefix();
    return $basePrefix . '/' . ltrim($endpoint, '/');
}

/**
 * Check if a page exists dynamically and redirect to 404 if not
 */
function check_page_exists(string $requestedPage): void {
    if (alt_is_debug_mode()) {
        return; // Skip redirects/headers in debug mode
    }
    // Get language info
    $i18n = detect_lang();
    $lang = $i18n['lang'];
    $prefix = $i18n['prefix'];
    
    $cleanPage = ltrim($requestedPage, '/');
    if (empty($cleanPage)) {
        return; // Allow empty/root requests
    }
    
    if (!str_ends_with($cleanPage, '.php')) {
        $cleanPage .= '.php';
    }
    
    // Get project root directory
    $projectRoot = dirname(__DIR__);
    
    // Check different possible file locations
    $possiblePaths = [];
    
    // For language-specific requests (ar/something.php)
    if ($lang === 'ar') {
        $possiblePaths[] = $projectRoot . '/ar/' . $cleanPage;
        $possiblePaths[] = $projectRoot . '/' . $cleanPage; // Fallback to main file
    } else {
        $possiblePaths[] = $projectRoot . '/' . $cleanPage;
    }
    
    // Check if any of the possible paths exist
    $fileExists = false;
    foreach ($possiblePaths as $path) {
        if (file_exists($path) && is_file($path)) {
            $fileExists = true;
            break;
        }
    }
    
    if (!$fileExists) {
        if (strpos($cleanPage, '404.php') !== false) {
            return;
        }
        
        // Redirect to 404 page with proper language
        $basePrefix = compute_base_prefix();
        $redirectUrl = $basePrefix . $prefix . '/404.php';
        
        header("HTTP/1.0 404 Not Found");
        header("Location: " . $redirectUrl);
        exit();
    }
}

/**
 * Auto-redirect to 404 for non-existent pages
 */
function auto_404_redirect(): void {
    if (alt_is_debug_mode()) {
        return; // Skip auto-redirect in debug mode
    }
    $requestUri = $_SERVER['REQUEST_URI'] ?? '/';
    $parsedUri = parse_url($requestUri, PHP_URL_PATH);
    $basePrefix = compute_base_prefix();
    // Always allow site base path (e.g., "/altoukhi" and "/altoukhi/")
    if ($parsedUri === '/' || $parsedUri === $basePrefix || $parsedUri === rtrim($basePrefix, '/') . '/') {
        return;
    }
    
    // Get the file being requested
    $scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
    $requestedFile = basename($parsedUri);
    
    // Treat language roots as valid (with and without base prefix)
    if (
        $parsedUri === '/ar' || $parsedUri === '/ar/' ||
        $parsedUri === '/en' || $parsedUri === '/en/' ||
        ($basePrefix !== '' && (
            $parsedUri === $basePrefix . '/ar' || $parsedUri === $basePrefix . '/ar/' ||
            $parsedUri === $basePrefix . '/en' || $parsedUri === $basePrefix . '/en/'
        ))
    ) {
        return;
    }

    // Skip if it's an asset, API call, or already 404
    if (
        strpos($parsedUri, '/assets/') !== false ||
        strpos($parsedUri, '/api/') !== false ||
        strpos($parsedUri, '404.php') !== false ||
        empty($requestedFile) ||
        $requestedFile === 'index.php'
    ) {
        return;
    }
    
    // Check if the actual PHP file exists
    $currentDir = dirname($_SERVER['SCRIPT_FILENAME']);
    $requestedFilePath = $currentDir . '/' . $requestedFile;
    
    if (!file_exists($requestedFilePath)) {
        check_page_exists($requestedFile);
    }
}


