<?php
// ============================================================================
// auth_bootstrap.php — session-safe, remember-me aware (role_id direct)
// With HARD SAFETY REDIRECT to login if remember-me cookie exists on non-login
// pages (prevents "bind_param() on bool" fatals inside remember_me.php).
// ============================================================================

/* ---- Secure cookie flags BEFORE session starts ---- */
if (session_status() !== PHP_SESSION_ACTIVE) {
    @ini_set('session.cookie_secure', '1');
    @ini_set('session.cookie_httponly', '1');
    @ini_set('session.use_only_cookies', '1');
    @ini_set('session.cookie_samesite', 'Lax');
}
if (session_status() !== PHP_SESSION_ACTIVE) { @session_start(); }

/* ---------------- Core includes ---------------- */
$cfgA = __DIR__ . '/config.php';
$cfgB = __DIR__ . '/reports-config.php'; // your newer name if used everywhere
if (file_exists($cfgA)) require_once $cfgA;
elseif (file_exists($cfgB)) require_once $cfgB;
else { http_response_code(500); echo "DB config.php not found"; exit; }

/** Pick a working mysqli link; prefer one already pointing to superadmin DB */
function _pick_db_link() {
    foreach (['conn_sa','conn_crm','conn_crmplus','conn','db','mysqli'] as $name) {
        if (isset($GLOBALS[$name]) && $GLOBALS[$name] instanceof mysqli) return $GLOBALS[$name];
    }
    return null;
}

/** Quote identifiers safely */
function qident($s){ return '`'.str_replace('`','``',$s).'`'; }
function fqtn($db,$tbl){ return qident($db).'.'.qident($tbl); }

$DB = _pick_db_link();
if (!$DB) { http_response_code(500); echo 'DB connection not available from config.php'; exit; }
@$DB->set_charset('utf8mb4');

/** Your superadmin schema & tables (fully qualified + quoted) */
if (!defined('SA_DB'))     define('SA_DB', 'broriserin_superadmin');
if (!defined('TBL_USERS')) define('TBL_USERS', fqtn(SA_DB,'users'));
if (!defined('TBL_ROLES')) define('TBL_ROLES', fqtn(SA_DB,'roles'));

/** Try to ensure this link can see the superadmin schema (priv/USE) */
@mysqli_select_db($DB, SA_DB); // harmless if lacks priv; we still use fully-qualified

/* ---------- Helpers ---------- */
if (!function_exists('h')) {
    function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
}

/* Remember-Me integration (optional file) */
$rememberFile = __DIR__ . '/remember_me.php';
if (file_exists($rememberFile)) {
    // Force the RM table to the correct schema to avoid "table not found" on other DB handles
    if (!defined('AUTH_REMEMBER_TABLE')) {
        define('AUTH_REMEMBER_TABLE', 'broriserin_broriserin.auth_remember_tokens');
    }
    require_once $rememberFile;
} else {
    if (!function_exists('sa_remember_autologin')) { function sa_remember_autologin(mysqli $db, callable $loadUserById): void {} }
    if (!function_exists('sa_remember_issue'))     { function sa_remember_issue(mysqli $db, int $user_id, int $days = 365): void {} }
    if (!function_exists('sa_remember_clear_all')) { function sa_remember_clear_all(mysqli $db, int $user_id): void {} }
}

/** Internal prepare wrapper + logging */
function _prep(mysqli $db, string $sql) {
    $stmt = $db->prepare($sql);
    if ($stmt === false) {
        error_log("[auth_bootstrap] prepare failed: {$db->error} | SQL={$sql}");
    }
    return $stmt;
}

/** Load user by id — fetch role_id directly from table */
function sa_load_user_by_id(mysqli $db, int $uid) {
    $sql = "SELECT id, email, first_name, last_name, role_id
            FROM ".TBL_USERS." WHERE id = ? LIMIT 1";
    $stmt = _prep($db, $sql);
    if (!$stmt) return null;

    if (!@$stmt->bind_param('i', $uid)) {
        error_log("[auth_bootstrap] bind_param failed sa_load_user_by_id: {$db->error}");
        @$stmt->close(); return null;
    }
    if (!$stmt->execute()) {
        error_log("[auth_bootstrap] execute failed sa_load_user_by_id: {$db->error}");
        @$stmt->close(); return null;
    }
    $res = $stmt->get_result();
    $row = $res ? ($res->fetch_assoc() ?: null) : null;
    @$stmt->close();
    return $row;
}

/* ---------- Roles ---------- */
function sa_get_role(mysqli $db, $idOrName) {
    if (is_numeric($idOrName)) {
        $sql = "SELECT * FROM ".TBL_ROLES." WHERE id = ? LIMIT 1";
        $stmt = _prep($db, $sql);
        if (!$stmt) return null;
        if (!@$stmt->bind_param('i', $idOrName)) { @$stmt->close(); return null; }
    } else {
        $sql = "SELECT * FROM ".TBL_ROLES." WHERE role_name = ? LIMIT 1";
        $stmt = _prep($db, $sql);
        if (!$stmt) return null;
        if (!@$stmt->bind_param('s', $idOrName)) { @$stmt->close(); return null; }
    }
    if (!$stmt->execute()) { @$stmt->close(); return null; }
    $res = $stmt->get_result();
    $row = $res ? $res->fetch_assoc() : null;
    @$stmt->close();
    return $row ?: null;
}

function sa_default_role_id(mysqli $db) {
    if ($r = sa_get_role($db, 'User')) return (int)$r['id'];
    return 4;
}

/** Start session payload */
function sa_start_session(array $userRow, array $roleRow = null) {
    $_SESSION['auth'] = [
        'id'         => (int)$userRow['id'],
        'name'       => trim(($userRow['first_name'] ?? '').' '.($userRow['last_name'] ?? '')),
        'email'      => $userRow['email'] ?? '',
        'role_id'    => (int)($userRow['role_id'] ?? 0),
        'role_name'  => $roleRow['role_name'] ?? '',
        'permissions'=> $roleRow && !empty($roleRow['permissions'])
                        ? (json_decode($roleRow['permissions'], true) ?: [])
                        : [],
        'logged_in'  => true,
        'time'       => time(),
    ];
}

/** Issue remember token after successful login (if checkbox) */
function sa_issue_remember_token_if_requested(mysqli $db, array $userRow): void {
    $remember = isset($_POST['remember']) && $_POST['remember'] == '1';
    if ($remember && function_exists('sa_remember_issue')) {
        sa_remember_issue($db, (int)$userRow['id'], 365);
    }
}

/* =================== HARD SAFETY REDIRECT (Hotfix) ===================
   If rm cookie exists and we are NOT on login page, redirect to login.
   This completely avoids the failing path inside remember_me.php.
   ==================================================================== */
$__uri       = $_SERVER['REQUEST_URI'] ?? '';
$__is_login  = (stripos($__uri, '/mobile/welcome/login') === 0);
/* ---------- Auto-login via remember-me cookie (only on login page) ---------- */
if ($__is_login && empty($_SESSION['auth']) && function_exists('sa_remember_autologin')) {
    try {
        sa_remember_autologin($DB, function(mysqli $db, int $uid) {
            // Load user + start session (role_id direct from table)
            $u = sa_load_user_by_id($db, $uid);
            if ($u) {
                $roleRow = sa_get_role($db, (int)($u['role_id'] ?? 0));
                sa_start_session($u, $roleRow);
            }
            return $u;
        });
    } catch (Throwable $e) {
        error_log('[auth_bootstrap] autologin throwable: '.$e->getMessage());
        // Proceed: we'll just render the login page without autologin
    }
}

/* ---------- Auto-login via remember-me cookie (only on login page) ---------- */
if (!$__is_login) {
    // Do NOT run autologin anywhere except login page (avoids crash)
} else if (empty($_SESSION['auth']) && function_exists('sa_remember_autologin')) {
    try {
        sa_remember_autologin($DB, function(mysqli $db, int $uid) {
            // Load user + start session (role_id is direct from table)
            $u = sa_load_user_by_id($db, $uid);
            if ($u) {
                $roleRow = sa_get_role($db, (int)($u['role_id'] ?? 0));
                sa_start_session($u, $roleRow);
            }
            return $u;
        });
    } catch (Throwable $e) {
        error_log('[auth_bootstrap] autologin throwable: '.$e->getMessage());
        // Continue to show login page gracefully
    }
}

/* ---------- Guards ---------- */
function sa_is_logged_in(){ return !empty($_SESSION['auth']['logged_in']); }

function sa_require_guest(){
    if (sa_is_logged_in()) { header('Location: /mobile/home_mobile.php'); exit; }
}

function sa_require_auth(){
    if (!sa_is_logged_in()) { header('Location: /mobile/welcome/login/'); exit; }
}
