<?php
// logout.php  (place under /mobile/welcome/login/logout.php or similar)
if (session_status() === PHP_SESSION_NONE) { session_start(); }

/* Bring DB + Remember-Me helpers */
$CFG_TRY = [
    __DIR__ . '/../../config.php',   // /mobile/welcome/login/../../config.php -> /mobile/config.php
    __DIR__ . '/../../../config.php' // fallback one more level if structure differs
];
foreach ($CFG_TRY as $p) { if (file_exists($p)) { require_once $p; break; } }

$RM_TRY = [
    __DIR__ . '/../../remember_me.php',
    __DIR__ . '/../../../remember_me.php'
];
foreach ($RM_TRY as $p) { if (file_exists($p)) { require_once $p; break; } }

/* Helper must match auth_bootstrap.php */
if (!function_exists('_pick_db_link')) {
    function _pick_db_link() {
        foreach (['conn_crm', 'conn_crmplus', 'conn', 'db', 'mysqli'] as $name) {
            if (isset($GLOBALS[$name]) && $GLOBALS[$name] instanceof mysqli) {
                return $GLOBALS[$name];
            }
        }
        return null;
    }
}

$DB  = _pick_db_link();
$uid = (int)($_SESSION['auth']['id'] ?? 0);

/* Clear all remember tokens for this user (DB + cookie) */
if ($DB && $uid && function_exists('sa_remember_clear_all')) {
    sa_remember_clear_all($DB, $uid);
} else {
    // If remember_me.php not present, at least try to clear cookie 'rm'
    if (isset($_COOKIE['rm'])) {
        $params = session_get_cookie_params();
        setcookie('rm', '', time() - 3600, $params['path'] ?? '/', $params['domain'] ?? '', true, true);
    }
}

/* Unset all session variables */
$_SESSION = [];

/* Delete the session cookie */
if (ini_get('session.use_cookies')) {
    $params = session_get_cookie_params();
    setcookie(
        session_name(),
        '',
        time() - 42000,
        $params['path'] ?? '/',
        $params['domain'] ?? '',
        (bool)($params['secure'] ?? true),
        (bool)($params['httponly'] ?? true)
    );
}

/* Destroy the session */
session_destroy();

/* Start a short session to hold flash message (optional) */
@session_start();
$_SESSION['flash_info'] = "You have been logged out.";

/* Redirect to login */
$LOGIN_URL = 'https://broriser.in/brocrm/mobile/welcome/login/';
header('Location: ' . $LOGIN_URL);
exit;
