<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . "/../../config/db.php";

if (empty($_SESSION['user']['id'])) {
    header("Location: /eagle_client_istanbulcups/login.php");
    exit;
}

// Timeout POS (10 min)
$timeout = 600;
if (isset($_SESSION['pos_last_activity']) &&
    time() - $_SESSION['pos_last_activity'] > $timeout) {
    unset($_SESSION['pos_caisse_id'], $_SESSION['session_caisse_id']);
    header("Location: /eagle_client_istanbulcups/index.php?page=pos-select-caisse&timeout=1");
    exit;
}
$_SESSION['pos_last_activity'] = time();

// Vérifier session caisse
$caisse_id = $_SESSION['pos_caisse_id'] ?? null;
$session_id = $_SESSION['session_caisse_id'] ?? null;

if (!$caisse_id || !$session_id) {
    header("Location: /eagle_client_istanbulcups/index.php?page=pos-select-caisse");
    exit;
}

// Vérifier caisse active
$stmt = $conn->prepare("SELECT actif FROM caisses WHERE id=?");
$stmt->execute([$caisse_id]);
if (!$stmt->fetchColumn()) {
    unset($_SESSION['pos_caisse_id'], $_SESSION['session_caisse_id']);
    header("Location: /eagle_client_istanbulcups/index.php?page=pos-select-caisse&inactive=1");
    exit;
}

// Vérifier utilisateur affecté à la caisse
$user_id = $_SESSION['user']['id'];
$stmt = $conn->prepare("SELECT 1 FROM utilisateurs_caisses WHERE utilisateur_id=? AND caisse_id=?");
$stmt->execute([$user_id, $caisse_id]);
if (!$stmt->fetchColumn()) {
    unset($_SESSION['pos_caisse_id'], $_SESSION['session_caisse_id']);
    header("Location: /eagle_client_istanbulcups/index.php?page=pos-select-caisse&unauthorized=1");
    exit;
}

// Vérifier session ouverte
$stmt = $conn->prepare("SELECT id FROM sessions_caisse WHERE id=? AND statut='ouverte'");
$stmt->execute([$session_id]);
if (!$stmt->fetchColumn()) {
    header("Location: /eagle_client_istanbulcups/index.php?page=pos-pin");
    exit;
}
