<?php
include '../includes/auth.php';
include '../includes/db.php';

if (isset($_GET['format']) && in_array($_GET['format'], ['csv', 'pdf'])) {
    $format = $_GET['format'];

    $stmt = $pdo->query("SELECT j.id, j.name, u.username, j.is_head
                         FROM judges j
                         LEFT JOIN users u ON j.id = u.judge_id
                         ORDER BY j.id ASC");
    $judges = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if ($format === 'csv') {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="judges_export.csv"');
        $output = fopen('php://output', 'w');
        fputcsv($output, ['ID', 'Name', 'Username', 'Role']);
        foreach ($judges as $j) {
            fputcsv($output, [$j['id'], $j['name'], $j['username'], $j['is_head'] ? 'Head Judge' : 'Judge']);
        }
        fclose($output);
        exit;
    }

    if ($format === 'pdf') {
        require_once '../vendor/autoload.php';
        use \setasign\Fpdi\Tcpdf\Fpdi;
        $pdf = new \TCPDF();
        $pdf->AddPage();
        $pdf->SetFont('helvetica', '', 12);
        $html = "<h1>Judge Account List</h1><table border='1' cellpadding='4'><tr>
                <th>ID</th><th>Name</th><th>Username</th><th>Role</th></tr>";
        foreach ($judges as $j) {
            $html .= "<tr><td>{$j['id']}</td><td>{$j['name']}</td><td>{$j['username']}</td><td>" .
                     ($j['is_head'] ? 'Head Judge' : 'Judge') . "</td></tr>";
        }
        $html .= "</table>";
        $pdf->writeHTML($html, true, false, true, false, '');
        $pdf->Output('judges_export.pdf', 'D');
        exit;
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Export Judges</title>
    <!-- style skin holder -->
<link id="bootswatch-theme"
      href="/v2/assets/bootswatch/<?= btTheme('nameCode') ?>/bootstrap.min.css"
      rel="stylesheet">
<link rel="stylesheet" href="/v2/assets/css/backgrounds.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">

</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
<div class="container-fluid container-StyleScore p-4">
    <h2>Export Judge Accounts</h2>
    <a href="?format=csv" class="btn btn-primary">Download CSV</a>
    <a href="?format=pdf" class="btn btn-danger">Download PDF</a>
</div>
</body>
</html>
