<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/tcpdf/tcpdf.php';

check_role('administrador');

$format = $_GET['format'] ?? 'excel';
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

// Base query
$query = "SELECT u.id, u.username, u.email, r.name as role, u.first_name, u.last_name, u.created_at FROM users u JOIN roles r ON u.role_id = r.id WHERE u.deleted_at IS NULL";
$params = [];
if ($search) {
    $query .= " AND (u.username LIKE ? OR u.email LIKE ? OR r.name LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ?)";
    $params = ["%$search%", "%$search%", "%$search%", "%$search%", "%$search%"];
}
$query .= " ORDER BY u.created_at DESC";

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

if ($format == 'excel') {
    // --- EXCEL (CSV) EXPORT ---
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=usuarios.csv');

    $output = fopen('php://output', 'w');

    // Add UTF-8 BOM for Excel compatibility
    fwrite($output, "\xEF\xBB\xBF");

    // Header row
    fputcsv($output, [
        'ID',
        'Username',
        'Email',
        'Role',
        'Nombre Completo',
        'Fecha de Registro'
    ], ';', '"', '\\');

    // Data rows
    foreach ($users as $user) {
        fputcsv($output, [
            $user['id'],
            $user['username'] ?? '',
            $user['email'] ?? '',
            $user['role'] ?? '',
            ($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''),
            $user['created_at'] ?? ''
        ], ';', '"', '\\');
    }

    fclose($output);
    exit;

} elseif ($format == 'pdf') {
    // --- PDF EXPORT ---

    class MYPDF extends TCPDF {
        
        public function Header() {
            $logoPath = dirname(__DIR__) . '/assets/img/logo.png';
            if (file_exists($logoPath)) {
                $this->Image($logoPath, 15, 10, 20, 0, 'PNG', '', 'T', false, 300, '', false, false, 0, false, false, false);
            }

            $this->SetFont('helvetica', 'B', 18);
            $this->SetTextColorArray($this->header_color);
            $this->SetXY(40, 12);
            $this->Cell(0, 10, 'BOLSA DE TRABAJO', 0, false, 'L');

            $this->SetFont('helvetica', 'B', 12);
            $this->SetXY(40, 20);
            $this->Cell(0, 10, 'Reporte de Usuarios', 0, false, 'L');

            $this->SetFont('helvetica', '', 9);
            $this->SetTextColor(100, 100, 100);
            $this->SetXY(0, 12);
            $this->Cell(0, 10, 'Generado: ' . date('d/m/Y H:i'), 0, false, 'R', 0, '', 0, false, 'T', 'M');

            // Línea divisoria
            $this->Line(15, 32, $this->getPageWidth() - 15, 32);
            $this->Ln(20);
        }

        public function Footer() {
            $this->SetY(-15);
            $this->SetFont('helvetica', 'I', 8);
            $this->SetTextColor(128);
            $this->Cell(0, 10, 'BOLSA DE TRABAJO | Página '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
        }

        public function drawTable($header, $data) {
            // Colores y fuentes
            $this->SetFillColor($this->header_color[0], $this->header_color[1], $this->header_color[2]);
            $this->SetTextColorArray($this->header_text_color);
            $this->SetFont('helvetica', 'B', 9);
            $w = [20, 50, 60, 30, 70, 45]; // Anchos de las columnas
            $num_headers = count($header);
            for($i = 0; $i < $num_headers; ++$i) {
                $this->Cell($w[$i], 7, $header[$i], 1, 0, 'C', 1);
            }
            $this->Ln();

            // Restaurar colores y fuentes
            $this->SetFillColor(245, 245, 245);
            $this->SetTextColor(0);
            $this->SetFont('');

            // Datos
            $fill = 0;
            foreach($data as $row) {
                $this->Cell($w[0], 6, $row['id'], 'LR', 0, 'L', $fill);
                $this->Cell($w[1], 6, htmlspecialchars($row['username'] ?? ''), 'LR', 0, 'L', $fill);
                $this->Cell($w[2], 6, htmlspecialchars($row['email'] ?? ''), 'LR', 0, 'L', $fill);
                $this->Cell($w[3], 6, htmlspecialchars($row['role'] ?? ''), 'LR', 0, 'L', $fill);
                $this->Cell($w[4], 6, htmlspecialchars(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? '')), 'LR', 0, 'L', $fill);
                $this->Cell($w[5], 6, htmlspecialchars($row['created_at'] ?? ''), 'LR', 0, 'L', $fill);
                $this->Ln();
                $fill=!$fill;
            }
            $this->Cell(array_sum($w), 0, '', 'T');
        }
    }

    $pdf = new MYPDF('L', PDF_UNIT, 'A4', true, 'UTF-8', false);

    $pdf->SetMargins(15, 35, 15);
    $pdf->SetHeaderMargin(10);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

    $pdf->AddPage();
    $pdf->SetFont('helvetica', '', 8);

    // Build HTML table
    $header = ['ID', 'Username', 'Email', 'Rol', 'Nombre Completo', 'Fecha de Registro'];
    $pdf->drawTable($header, $users);

    $pdf->Output('usuarios.pdf', 'D');
    exit;
}

header('Location: users.php');
exit;
?>