<?php
if (session_status() === PHP_SESSION_NONE) session_save_path("/home/evolucionamos/public_html/mejora/sessions");
session_start();
if (empty($_SESSION['adm']) || ($_SESSION['role'] != 1 && $_SESSION['role'] != 3)) {
    header("Location: index.php"); exit;
}

require_once '../app/models/conexion.php';
$conn = new \app\models\conexion();
$db   = $conn->DB();

// Filtro opcional por zona
$zona = isset($_GET['zona']) ? strip_tags(trim($_GET['zona'])) : '';

// Obtener usuarios
if ($zona !== '') {
    $stmt = $db->prepare("SELECT user_id, name, username, zona, poder, activo,
        CASE WHEN voto IS NOT NULL THEN 'SÍ' ELSE 'NO' END AS voto_realizado,
        CASE WHEN quorum = 1 THEN 'SÍ' ELSE 'NO' END AS quorum_registrado
        FROM users WHERE zona = :zona AND activo = 1 ORDER BY zona, name");
    $stmt->execute([':zona' => $zona]);
} else {
    $stmt = $db->prepare("SELECT user_id, name, username, zona, poder, activo,
        CASE WHEN voto IS NOT NULL THEN 'SÍ' ELSE 'NO' END AS voto_realizado,
        CASE WHEN quorum = 1 THEN 'SÍ' ELSE 'NO' END AS quorum_registrado
        FROM users WHERE activo = 1 ORDER BY zona, name");
    $stmt->execute();
}
$usuarios = $stmt->fetchAll(\PDO::FETCH_ASSOC);

$filename = 'votantes_' . ($zona ?: 'todos') . '_' . date('Ymd_His') . '.csv';

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');

$out = fopen('php://output', 'w');
// BOM para Excel con UTF-8
fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));

fputcsv($out, ['ID', 'NOMBRE', 'CÉDULA', 'ZONA', 'PODER', 'ACTIVO', 'VOTÓ', 'QUÓRUM'], ';');

foreach ($usuarios as $u) {
    fputcsv($out, [
        $u['user_id'],
        $u['name'],
        $u['username'],
        $u['zona'],
        $u['poder'],
        $u['activo'] ? 'SÍ' : 'NO',
        $u['voto_realizado'],
        $u['quorum_registrado'],
    ], ';');
}

fclose($out);
exit;
