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

$message = '';

// Delete handler
if (isset($_GET['delete'])) {
    $pid = intval($_GET['delete']);
    $pdo->prepare("DELETE FROM participants WHERE id = ?")->execute([$pid]);
    $message = '<div class="alert alert-danger">Participant deleted.</div>';
}

// Delete all handler
if (isset($_GET['delete_all']) && $_GET['delete_all'] === '1') {
    $pdo->exec("DELETE FROM participants");
    $message = '<div class="alert alert-danger">All participants deleted.</div>';
}

// Filter parameters
$filter_gender = $_GET['gender'] ?? '';
$filter_category = $_GET['category'] ?? '';

// Build query
$where_clauses = [];
$params = [];

if ($filter_gender !== '') {
    $where_clauses[] = "gender = ?";
    $params[] = $filter_gender;
}

if ($filter_category !== '') {
    $where_clauses[] = "category = ?";
    $params[] = $filter_category;
}

$where_sql = $where_clauses ? "WHERE " . implode(" AND ", $where_clauses) : "";
$query = "SELECT * FROM participants $where_sql ORDER BY id DESC";
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$participants = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get distinct genders and categories for filters
$genders = $pdo->query("SELECT DISTINCT gender FROM participants WHERE gender IS NOT NULL AND gender != '' ORDER BY gender")->fetchAll(PDO::FETCH_COLUMN);
$categories = $pdo->query("SELECT DISTINCT category FROM participants WHERE category IS NOT NULL AND category != '' ORDER BY category")->fetchAll(PDO::FETCH_COLUMN);

// Export handler
if (isset($_GET['export']) && in_array($_GET['export'], ['csv', 'pdf'])) {
    $stmt = $pdo->query("SELECT * FROM participants ORDER BY id DESC");
    $participants = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if ($_GET['export'] === 'csv') {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="participants.csv"');
        $output = fopen('php://output', 'w');
        fputcsv($output, ['BIB', 'First Name', 'Last Name', 'Gender', 'FIS Code', 'Licence Code', 'Licence Type', 'Club', 'Country', 'Date of Birth', 'Category']);
        foreach ($participants as $p) {
            fputcsv($output, [
                $p['bib'], $p['first_name'], $p['last_name'], $p['gender'], $p['fis_code'],
                $p['licence_code'], $p['licence_type'], $p['club'], $p['country'],
                $p['date_of_birth'], $p['category']
            ]);
        }
        fclose($output);
        exit;
    }

    if ($_GET['export'] === 'pdf') {
        require_once '../vendor/autoload.php';
        $pdf = new \TCPDF();
        $pdf->AddPage();
        $pdf->SetFont('helvetica', '', 9);
        $html = "<h2>Participant List</h2><table border='1' cellpadding='4'><tr>
            <th>BIB</th><th>First</th><th>Last</th><th>Gender</th><th>FIS</th><th>Licence Code</th><th>Licence Type</th>
            <th>Club</th><th>Country</th><th>DOB</th><th>Category</th></tr>";
        foreach ($participants as $p) {
            $html .= "<tr>
                <td>{$p['bib']}</td><td>{$p['first_name']}</td><td>{$p['last_name']}</td><td>{$p['gender']}</td>
                <td>{$p['fis_code']}</td><td>{$p['licence_code']}</td><td>{$p['licence_type']}</td>
                <td>{$p['club']}</td><td>{$p['country']}</td><td>{$p['date_of_birth']}</td><td>{$p['category']}</td>
            </tr>";
        }
        $html .= "</table>";
        $pdf->writeHTML($html);
        $pdf->Output('participants.pdf', 'D');
        exit;
    }
}
// Import handler
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['import_file'])) {
    $file = $_FILES['import_file']['tmp_name'];
    if (($handle = fopen($file, 'r')) !== FALSE) {
        fgetcsv($handle); // skip header
        while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
            $stmt = $pdo->prepare("INSERT INTO participants (bib, first_name, last_name, gender, fis_code, licence_code, licence_type, club, country, date_of_birth, category)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([
                $data[0], $data[1], $data[2], $data[3], $data[4], $data[5], $data[6],
                $data[7], $data[8], $data[9], $data[10]
            ]);
        }
        fclose($handle);
        $message = '<div class="alert alert-success">Participants imported successfully.</div>';
    }
}

$participants = $pdo->query("SELECT * FROM participants ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);

?>
<!DOCTYPE html>
<html>
<head>
    <title>Participants</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">

    <style>td, th { font-size: 13px; }</style>
</head>
<body class="body-bg-aurora-bright">
<div class="container-fluid container-StyleScore p-4">
    <h2>Participants</h2>
    <?php echo $message; ?>
    <div class="mb-3">
        <a href="?export=csv" class="btn btn-outline-primary btn-sm">Export CSV</a>
        <a href="?export=pdf" class="btn btn-outline-danger btn-sm">Export PDF</a>
        <a href="?delete_all=1" class="btn btn-outline-danger btn-sm" onclick="return confirm('Are you sure you want to delete all participants?')">Delete All</a>
    </div>
    <form method="post" enctype="multipart/form-data" class="mb-4">
        <label class="form-label">Import Participants (CSV):</label>
        <input type="file" name="import_file" class="form-control mb-2" required>
        <button type="submit" class="btn btn-success">Import</button>
    </form>
    <form method="get" class="row g-2 mb-3">
        <div class="col-md-3">
            <select name="gender" class="form-select" onchange="this.form.submit()">
                <option value="">All Genders</option>
                <?php foreach ($genders as $gender): ?>
                    <option value="<?= $gender ?>" <?= $filter_gender === $gender ? 'selected' : '' ?>><?= $gender ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-3">
            <select name="category" class="form-select" onchange="this.form.submit()">
                <option value="">All Categories</option>
                <?php foreach ($categories as $cat): ?>
                    <option value="<?= $cat ?>" <?= $filter_category === $cat ? 'selected' : '' ?>><?= $cat ?></option>
                <?php endforeach; ?>
            </select>
        </div>
    </form>

    <div class="table-responsive">
    <table class="table table-bordered table-sm">
        <thead>
            <tr>
                <th>ID</th><th>BIB</th><th>First</th><th>Last</th><th>Gender</th><th>FIS</th><th>Licence Code</th>
                <th>Licence Type</th><th>Club</th><th>Country</th><th>DOB</th><th>Category</th><th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($participants as $p): ?>
            <tr>
                <td><?= $p['id'] ?></td>
                <td><?= $p['bib'] ?></td>
                <td><?= htmlspecialchars($p['first_name']) ?></td>
                <td><?= htmlspecialchars($p['last_name']) ?></td>
                <td><?= $p['gender'] ?></td>
                <td><?= $p['fis_code'] ?></td>
                <td><?= $p['licence_code'] ?></td>
                <td><?= $p['licence_type'] ?></td>
                <td><?= htmlspecialchars($p['club']) ?></td>
                <td><?= $p['country'] ?></td>
                <td><?= $p['date_of_birth'] ?></td>
                <td><?= $p['category'] ?></td>
                <td>
                    <a href="participant_edit.php?id=<?= $p['id'] ?>" class="btn btn-sm btn-outline-secondary">Edit</a>
                    <a href="?delete=<?= $p['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this participant?')">Delete</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    </div>
</div>
</body>
</html>
