<?php

/**
 * General System Helpers
 */

/**
 * Redirect to a specific URL path cleanly
 */
function redirect($path) {
    $url = (strpos($path, 'http') === 0) ? $path : BASE_URL . '/' . ltrim($path, '/');
    
    // Frictionless Engine: If AJAX, return JSON instruction instead of hard redirect
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        header('Content-Type: application/json');
        
        $referer = $_SERVER['HTTP_REFERER'] ?? '';
        // If the redirect path is the same module base path as the referer, 
        // DO NOT send 'redirect', so the JS just reloads current window.location.href!
        $baseReferer = strtok($referer, '?');
        $baseUrl = strtok($url, '?');
        
        if($baseReferer === $baseUrl) {
            echo json_encode(['success' => true]);
            exit;
        }

        echo json_encode(['success' => true, 'redirect' => $url]);
        exit;
    }

    header("Location: $url");
    exit;
}

/**
 * Set a flash session message
 * Types: success, danger, warning, info
 */
function set_flash_message($key, $message, $type = 'success') {
    $_SESSION['flash'][$key] = [
        'message' => $message,
        'type' => $type
    ];
}

/**
 * Get and automatically display a Bootstrap dismissible flash message
 */
function display_flash_message($key) {
    if (isset($_SESSION['flash'][$key])) {
        $flash = $_SESSION['flash'][$key];
        unset($_SESSION['flash'][$key]); // delete after displaying
        
        return '
        <div class="alert alert-' . $flash['type'] . ' alert-dismissible fade show shadow-sm" role="alert">
            ' . $flash['message'] . '
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>';
    }
    return '';
}

/**
 * Dump and die (For debugging only)
 */
function dd($data) {
    echo '<pre style="background: #111; color: #0f0; padding: 15px; direction: ltr; text-align: left;">';
    print_r($data);
    echo '</pre>';
    die();
}
/**
 * Abort with a specific HTTP status code
 */
function abort($code = 404, $message = "") {
    http_response_code($code);
    if ($code == 404) {
        error_log("404 Abort: " . $message);
        $view404 = ROOT_PATH . '/app/Views/errors/404.php';
        if (file_exists($view404)) {
            require_once $view404;
        } else {
            echo "<div style='direction:rtl; text-align:center; padding:50px; font-family:sans-serif;'>";
            echo "<h1>404 - الصفحة غير موجودة</h1>";
            echo "<p>نعتذر، لم نتمكن من العثور على الصفحة المطلوبة.</p>";
            echo "<a href='" . BASE_URL . "/'>العودة للرئيسية</a>";
            echo "</div>";
        }
    } else {
        die("System Error ($code): $message");
    }
    exit;
}
