<?php
// db.php - Fixed Session Handling

// 1. START SESSION PROPERLY (Settings must come BEFORE start)
if (session_status() === PHP_SESSION_NONE) {
    // Session cookie security settings (must be before session_start)
    ini_set('session.cookie_httponly', 1);
    ini_set('session.use_only_cookies', 1);
    ini_set('session.cookie_samesite', 'Lax'); // Use 'Lax' instead of 'Strict' to allow cross-site navigation
    
    // Set secure cookie if HTTPS
    if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
        ini_set('session.cookie_secure', 1);
    }
    
    // Disable session timeout - sessions will persist indefinitely (100 years)
    ini_set('session.gc_maxlifetime', 3153600000); // 100 years - effectively no timeout
    ini_set('session.cookie_lifetime', 3153600000); // Cookie expires in 100 years
    
    // Set cookie parameters with all options
    $cookieParams = [
        'lifetime' => 3153600000,
        'path' => '/',
        'domain' => '',
        'secure' => (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on'),
        'httponly' => true,
        'samesite' => 'Lax'
    ];
    session_set_cookie_params($cookieParams);
    
    session_name('FONFIX_SYSTEM_ID');
    session_start();
}

// 2. Security Headers
header("X-Frame-Options: DENY");
header("X-XSS-Protection: 1; mode=block");
header("X-Content-Type-Options: nosniff");

// 3. Database Connection
// Load config if available, otherwise use defaults
$configFile = __DIR__ . '/config.php';
if (file_exists($configFile)) {
    $config = require $configFile;
    $host = $config['database']['host'];
    $db = $config['database']['dbname'];
    $user = $config['database']['username'];
    $pass = $config['database']['password'];
    $charset = $config['database']['charset'];
} else {
    // Fallback to defaults (backward compatibility)
    $host = 'localhost';
    $db   = 'spartanm_systemdb';
    $user = 'spartanm_systemdb';
    $pass = '.CA}RN-yF8yUd.WK';
    $charset = 'utf8mb4';
}

$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass, $options);
} catch (\PDOException $e) {
    // Silent error to prevent leaking details to user
    error_log($e->getMessage());
    die("System Error: Database Connection Failed.");
}

// 4. CSRF Token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>