<?php

/**
 * Clear PHP session and cookie, then redirect or emit JSON (for AJAX).
 */
function customer_session_force_logout(string $mode = 'redirect'): void
{
    $_SESSION = [];
    if (ini_get('session.use_cookies')) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params['path'], $params['domain'],
            $params['secure'], $params['httponly']
        );
    }
    session_destroy();

    if ($mode === 'json') {
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => 'Your session has ended. Please sign in again.']);
        exit;
    }

    header('Location: login.php?error=blocked');
    exit;
}

/**
 * If the logged-in customer row is missing or accstatus is blocked, force logout.
 */
function customer_session_abort_if_blocked(mysqli $con, string $mode = 'redirect'): void
{
    if (session_status() !== PHP_SESSION_ACTIVE || !isset($_SESSION['customerid'])) {
        return;
    }

    $cid = (int) $_SESSION['customerid'];
    if ($cid < 1) {
        return;
    }

    $stmt = $con->prepare('SELECT accstatus FROM customers WHERE customerid = ? LIMIT 1');
    if (!$stmt) {
        return;
    }
    $stmt->bind_param('i', $cid);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$row || (($row['accstatus'] ?? '') === 'blocked')) {
        customer_session_force_logout($mode);
    }
}
