<?php
// app/Core/init.php - Bootstrap File

// Start secure session
if (session_status() === PHP_SESSION_NONE) {
    session_start([
        'cookie_httponly' => true,
        'cookie_secure' => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on',
        'cookie_samesite' => 'Strict',
        'use_strict_mode' => true,
        'cookie_lifetime' => 0,
        'gc_maxlifetime' => 1800
    ]);
}

// Define base paths
define('ROOT_PATH', dirname(dirname(__DIR__)));
define('APP_PATH', ROOT_PATH . '/app');
define('CONFIG_PATH', ROOT_PATH . '/config');
define('STORAGE_PATH', ROOT_PATH . '/storage');
define('PUBLIC_PATH', ROOT_PATH . '/public');
define('UPLOAD_PATH', PUBLIC_PATH . '/uploads');

// Load configuration
require_once CONFIG_PATH . '/config.php';

// Load core classes
require_once APP_PATH . '/Core/Database.php';
require_once APP_PATH . '/Core/Auth.php';
require_once APP_PATH . '/Core/Security.php';
require_once APP_PATH . '/Core/Mailer.php';
require_once APP_PATH . '/Core/Upload.php';

// Load helper files
require_once APP_PATH . '/Helpers/general.php';
require_once APP_PATH . '/Helpers/validation.php';
require_once APP_PATH . '/Helpers/format.php';
require_once APP_PATH . '/Helpers/file.php';

// Autoload models, services, and payment classes
spl_autoload_register(function ($class) {
    $paths = [
        APP_PATH . '/Models/' . $class . '.php',
        APP_PATH . '/Services/' . $class . '.php',
        APP_PATH . '/Payment/' . $class . '.php',
    ];
    
    foreach ($paths as $path) {
        if (file_exists($path)) {
            require_once $path;
            return;
        }
    }
});

// Error reporting based on environment
if (defined('APP_DEBUG') && APP_DEBUG) {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
} else {
    error_reporting(0);
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', STORAGE_PATH . '/logs/error.log');
}

// Set default timezone
date_default_timezone_set('Africa/Lagos');

// Security headers
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');

// Session regeneration for security (every 5 minutes)
if (!isset($_SESSION['last_regeneration'])) {
    session_regenerate_id(true);
    $_SESSION['last_regeneration'] = time();
} elseif (time() - $_SESSION['last_regeneration'] > 300) {
    session_regenerate_id(true);
    $_SESSION['last_regeneration'] = time();
}

// Initialize database connection
try {
    $db = Database::getInstance();
} catch (Exception $e) {
    if (defined('APP_DEBUG') && APP_DEBUG) {
        die("Database Connection Error: " . $e->getMessage());
    } else {
        error_log("Database Connection Error: " . $e->getMessage());
        die("Sorry, we're experiencing technical difficulties. Please try again later.");
    }
}

// Set character encoding
if (function_exists('mb_internal_encoding')) {
    mb_internal_encoding('UTF-8');
}
if (function_exists('mb_http_output')) {
    mb_http_output('UTF-8');
}


// escape 'esc'
if (!function_exists('esc')) {
    function esc($string = null, $context = 'html') {
        // Grab the variable that the template expects if nothing is passed
        if ($string === null) {
            // Change this line to match YOUR variable name
            global $data;            // ← Kirby
            // global $view;         // ← Slim
            // global $page;         // ← custom
            $string = $data ?? $view ?? $page ?? '';
        }

        $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5;
        return match($context) {
            'attr' => htmlspecialchars($string, $flags, 'UTF-8'),
            'js'   => addslashes($string),
            'url'  => rawurlencode($string),
            default=> htmlspecialchars($string, $flags, 'UTF-8'),
        };
    }
}


// Start secure session
if (session_status() === PHP_SESSION_NONE) {
    session_start([
        'cookie_httponly' => true,
        'cookie_secure' => isset($_SERVER['HTTPS']),
        'cookie_samesite' => 'Strict',
        'use_strict_mode' => true
    ]);
}

// Load configuration
require_once __DIR__ . '/../../config/config.php';

// Load core classes
require_once __DIR__ . '/Database.php';
require_once __DIR__ . '/Auth.php';
require_once __DIR__ . '/Security.php';
require_once __DIR__ . '/Mailer.php';
require_once __DIR__ . '/Upload.php';

// Load helper functions
require_once __DIR__ . '/../Helpers/general.php';

// Autoload models, services, and payment classes
spl_autoload_register(function ($class) {
    $paths = [
        __DIR__ . '/../Models/' . $class . '.php',
        __DIR__ . '/../Services/' . $class . '.php',
        __DIR__ . '/../Payment/' . $class . '.php',
    ];
    
    foreach ($paths as $path) {
        if (file_exists($path)) {
            require_once $path;
            return;
        }
    }
});

// Error reporting based on environment
if (defined('APP_DEBUG') && APP_DEBUG) {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
} else {
    error_reporting(0);
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../../storage/logs/php-error.log');
}

// Security headers
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header('X-XSS-Protection: 1; mode=block');

// Session regeneration for security
if (!isset($_SESSION['last_regeneration'])) {
    session_regenerate_id(true);
    $_SESSION['last_regeneration'] = time();
} elseif (time() - $_SESSION['last_regeneration'] > 300) {
    session_regenerate_id(true);
    $_SESSION['last_regeneration'] = time();
}



// ================
// Function to get current user
function getCurrentUser() {
    return Auth::user();
}

// Function to sanitize output
function e($string) {
    return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
}

// Function to format currency
function formatCurrency($amount) {
    return '₦' . number_format($amount, 2);
}

// Function to format date
function formatDate($date, $format = 'M d, Y') {
    return date($format, strtotime($date));
}

// Function to format datetime
function formatDateTime($datetime, $format = 'M d, Y H:i') {
    return date($format, strtotime($datetime));
}

// Function to generate star rating display
function displayStars($rating) {
    $output = '';
    for ($i = 1; $i <= 5; $i++) {
        if ($i <= $rating) {
            $output .= '<i class="fas fa-star text-warning"></i>';
        } elseif ($i - 0.5 <= $rating) {
            $output .= '<i class="fas fa-star-half-alt text-warning"></i>';
        } else {
            $output .= '<i class="far fa-star text-muted"></i>';
        }
    }
    return $output;
}

// Function to truncate text
function truncateText($text, $length = 100) {
    return strlen($text) > $length ? substr($text, 0, $length) . '...' : $text;
}

// Function to get user role
function getUserRole() {
    return Auth::user()['user_type'] ?? 'guest';
}

// Function to require authentication
function requireAuth() {
    if (!isLoggedIn()) {
        redirect('/auth/login.php');
    }
}

// Function to require customer role
function requireCustomer() {
    requireAuth();
    if (getUserRole() !== 'customer') {
        redirect('/');
    }

}

// Check session timeout
Auth::checkTimeout();