<?php
/**
 * TechStackBase – System Bootstrap
 * Shared by Admin UI + API
 */

declare(strict_types=1);

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (!defined('PRODUCT_ID')) {
    define('PRODUCT_ID', 1);
}

require_once __DIR__ . '/response.php';  
require_once __DIR__ . '/auth.php';

/* ==========================================================
   ERROR HANDLING
   ========================================================== */

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
ini_set('log_errors', '1');
error_reporting(E_ALL);

/* ==========================================================
   SESSION COOKIE
   ========================================================== */

if (!defined('API_MODE')) {

    ini_set('session.cookie_domain', '.jb26.co.za');
    ini_set('session.cookie_path', '/');
    ini_set('session.cookie_secure', '1');   // if HTTPS
    ini_set('session.cookie_httponly', '1');
    ini_set('session.cookie_samesite', 'None');

    /* ==========================================================
       SESSION CONFIGURATION (CRITICAL)
       ========================================================== */

    session_set_cookie_params([
        'lifetime' => 0,
        'path'     => '/',
        'domain'   => '',
        'secure'   => true,
        'httponly' => true,
        'samesite' => 'Lax',
    ]);

    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
}

/* ==========================================================
   CSRF
   ========================================================== */

 
require_once __DIR__ . '/csrf.php';

/* ==========================================================
   LOAD DATABASE (SINGLE SOURCE)
   ========================================================== */

require_once __DIR__ . '/../config/database.php';

/* ==========================================================
   AUDIT + LEGAL
   ========================================================== */

require_once __DIR__ . '/audit.php';
require_once __DIR__ . '/legal_hold.php';

/* ==========================================================
   PUBLIC AUTH ENDPOINT CHECK (SKIP LIFECYCLE ONLY)
   ========================================================== */

$publicAuthEndpoints = [
    'login.php',
    'register.php',
    'verify_email.php',
    'resend_verification.php',
    'reset_password.php',
];

$currentScript = $_SERVER['SCRIPT_NAME'] ?? '';

foreach ($publicAuthEndpoints as $endpoint) {
    if (str_ends_with($currentScript, '/auth/' . $endpoint)) {
        // Skip lifecycle enforcement, NOT bootstrap
        return;
    }
}

/* ==========================================================
   AUTHENTICATED USER VALIDATION (AUTHORITATIVE)
   ========================================================== */

if (isset($_SESSION['user_id'])) {

    $stmt = $pdo->prepare("
        SELECT id, email_verified, status, role_key, company_id
        FROM users
        WHERE id = ?
        LIMIT 1
    ");
    $stmt->execute([$_SESSION['user_id']]);
    $authUser = $stmt->fetch(PDO::FETCH_ASSOC);

    $status = strtolower(trim((string)$authUser['status']));

    if (
        !$authUser ||
        (int)$authUser['email_verified'] !== 1 ||
        $status !== 'active'
    ) {

        // Kill access immediately
        session_destroy();
        json_response([
            'error' => 'Account not active or not verified'
        ], 401);
    }

    // Optional: hydrate minimal trusted session data
    $_SESSION['role_key']   = $authUser['role_key'];
    $_SESSION['company_id'] = $authUser['company_id'];
    
    if (isset($_SESSION['user_id'])) {
    if (!defined('API_MODE')) {
        verify_csrf();
    }
    }
}
    