<?php
require_once 'config.php';

/**
 * SAC 2026 - SESSION VALIDATOR PRO v4.2
 * Recupera el contexto completo del usuario incluyendo su ID de Telegram.
 */

if (isset($_SESSION['user_id'])) {
    $stmt = $pdo->prepare("SELECT 
                            u.id, 
                            u.username, 
                            u.role, 
                            u.full_name, 
                            u.email, 
                            u.cedula, 
                            u.telegram_chat_id as telegramChatId,
                            p.code as property_code, 
                            p.id as property_id 
                           FROM users u 
                           LEFT JOIN residents r ON u.id = r.user_id 
                           LEFT JOIN properties p ON r.property_id = p.id 
                           WHERE u.id = ? 
                           LIMIT 1");
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch();

    if ($user) {
        // Refrescar persistencia en sesión de servidor
        $_SESSION['user_role'] = $user['role'];
        $_SESSION['property_id'] = $user['property_id'];
        
        response([
            "active" => true,
            "user" => [
                "id" => (int)$user['id'],
                "username" => $user['username'],
                "role" => $user['role'],
                "fullName" => $user['full_name'],
                "email" => $user['email'],
                "propertyCode" => $user['property_code'],
                "propertyId" => (int)$user['property_id'],
                "cedula" => $user['cedula'],
                "telegramChatId" => $user['telegramChatId']
            ]
        ]);
    }
}

response(["active" => false], 401);
?>