<?php
// Endpoint: obtener el desk actual del usuario
if (session_status() === PHP_SESSION_NONE) { session_start(); }
define('BASE_PATH', dirname(__DIR__, 2));
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

header('Content-Type: application/json; charset=utf-8');

function isLoggedIn(){ return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']); }
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success'=>false,'message'=>'No autorizado']);
    exit;
}

try {
    $db = getDB();
    $uid = (int)$_SESSION['user_id'];
    $row = $db->selectOne(
        "SELECT d.id AS desk_id, d.name AS desk_name
         FROM desks d
         INNER JOIN desk_users du ON du.desk_id = d.id
         WHERE du.user_id = ?
         ORDER BY du.assigned_at DESC
         LIMIT 1",
        [$uid]
    );

    if (!$row) {
        echo json_encode(['success'=>true,'desk_id'=>null,'desk_name'=>null]);
        exit;
    }

    echo json_encode(['success'=>true,'desk_id'=>(int)$row['desk_id'],'desk_name'=>$row['desk_name']]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success'=>false,'message'=>'Error del servidor','error'=>$e->getMessage()]);
}
?>