<?php
require_once 'config.php';
if (!isset($_SESSION['user_id'])) response(["blocking" => false]);

$userId = $_SESSION['user_id'];
$role = $_SESSION['user_role'];

// Admins are never blocked
if (in_array($role, ['admin', 'programmer', 'board'])) {
    response(["blocking" => false]);
}

try {
    // 1. Get property ID securely from server database, not from request
    $stmtProp = $pdo->prepare("SELECT property_id FROM residents WHERE user_id = ? LIMIT 1");
    $stmtProp->execute([$userId]);
    $res = $stmtProp->fetch();
    if (!$res) response(["blocking" => false]);
    $propertyId = $res['property_id'];

    // CHECK PRIORITY 1: LIVE ASSEMBLY
    $checkLive = $pdo->prepare("SELECT id, question FROM live_votes WHERE status = 'Activa' AND id NOT IN (SELECT vote_id FROM live_vote_responses WHERE property_id = ?) LIMIT 1");
    $checkLive->execute([$propertyId]);
    if ($vote = $checkLive->fetch()) {
        response(["blocking" => true, "target_tab" => "live-voting", "item_title" => $vote['question']]);
    }

    // CHECK PRIORITY 2: POLLS
    $checkPoll = $pdo->prepare("SELECT id, title FROM polls WHERE status = 'Abierta' AND id NOT IN (SELECT poll_id FROM poll_responses WHERE property_id = ?) LIMIT 1");
    $checkPoll->execute([$propertyId]);
    if ($poll = $checkPoll->fetch()) {
        response(["blocking" => true, "target_tab" => "polls", "item_title" => $poll['title']]);
    }

    response(["blocking" => false]);
} catch (PDOException $e) {
    response(["blocking" => false]);
}
?>