<?php

function tempahanSessionCandidates(): array
{
    $storageDirectory = __DIR__ . DIRECTORY_SEPARATOR . 'storage';

    return [
        $storageDirectory . DIRECTORY_SEPARATOR . 'runtime_sessions',
        $storageDirectory . DIRECTORY_SEPARATOR . 'sessions',
        rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR)
            . DIRECTORY_SEPARATOR
            . 'tempahan_sessions_' . substr(sha1(__DIR__), 0, 12),
    ];
}

function tempahanDirectoryIsWritable(string $directory): bool
{
    if (!is_dir($directory) && !@mkdir($directory, 0770, true) && !is_dir($directory)) {
        return false;
    }

    @chmod($directory, 0770);
    $probeFile = $directory . DIRECTORY_SEPARATOR . '.write_test_' . uniqid('', true);

    if (@file_put_contents($probeFile, 'ok', LOCK_EX) === false) {
        return false;
    }

    @unlink($probeFile);
    return true;
}

function tempahanStartSession(): bool
{
    if (session_status() === PHP_SESSION_ACTIVE) {
        return true;
    }

    foreach (tempahanSessionCandidates() as $directory) {
        if (!tempahanDirectoryIsWritable($directory)) {
            error_log('Sistem Tempahan: Direktori session tidak boleh ditulis: ' . $directory);
            continue;
        }

        session_save_path($directory);

        if (@session_start()) {
            return true;
        }

        $lastError = error_get_last();
        $message = $lastError['message'] ?? 'Sebab tidak diketahui';
        error_log('Sistem Tempahan: session_start gagal pada ' . $directory . '. ' . $message);
    }

    return false;
}

if (session_status() === PHP_SESSION_NONE) {
    session_name('TEMPahanSESSID');

    ini_set('session.use_strict_mode', '1');
    ini_set('session.use_only_cookies', '1');

    $isHttps = (!empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off')
        || (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])
            && strtolower((string) $_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https');

    $cookiePath = '/';
    $documentRoot = isset($_SERVER['DOCUMENT_ROOT']) ? realpath((string) $_SERVER['DOCUMENT_ROOT']) : false;
    $applicationRoot = realpath(__DIR__);

    if ($documentRoot !== false && $applicationRoot !== false) {
        $normalizedDocumentRoot = str_replace('\\', '/', $documentRoot);
        $normalizedApplicationRoot = str_replace('\\', '/', $applicationRoot);

        if (stripos($normalizedApplicationRoot, $normalizedDocumentRoot) === 0) {
            $relativePath = substr($normalizedApplicationRoot, strlen($normalizedDocumentRoot));
            $cookiePath = '/' . trim((string) $relativePath, '/') . '/';
            $cookiePath = $cookiePath === '//' ? '/' : $cookiePath;
        }
    }

    session_set_cookie_params([
        'lifetime' => 0,
        'path' => $cookiePath,
        'secure' => $isHttps,
        'httponly' => true,
        'samesite' => 'Lax',
    ]);

    foreach (tempahanSessionCandidates() as $sessionDirectory) {
        if (tempahanDirectoryIsWritable($sessionDirectory)) {
            session_save_path($sessionDirectory);
            break;
        }
    }
}
