<?php
// admin_juri.php
require_once '../../config.php';
requireRole('admin');

$conn = connectDB();
$error = '';
$success = '';

// Proses tambah juri baru
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'add') {
    $username = strtoupper(sanitizeInput($_POST['username']));
    $password = strtoupper($_POST['password']);
    $nama = sanitizeInput($_POST['nama']);
    $email = sanitizeInput($_POST['email']);
    $id_cabang_lomba = $_POST['id_cabang_lomba'] != '' ? (int)$_POST['id_cabang_lomba'] : null;

    // Cek username sudah ada atau belum
    $stmt = $conn->prepare("SELECT id FROM users WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $error = "Username sudah digunakan!";
    } else {
        // Cek email sudah ada atau belum
        $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            $error = "Email sudah digunakan!";
        } else {
            // Hash password
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);

            // Insert user baru tanpa domisili
            $stmt = $conn->prepare("INSERT INTO users (username, password, role, nama_lengkap, email, id_cabang_lomba) VALUES (?, ?, 'juri', ?, ?, ?)");
            $stmt->bind_param("ssssi", $username, $hashed_password, $nama, $email, $id_cabang_lomba);

            if ($stmt->execute()) {
                $success = "Juri berhasil ditambahkan!";
            } else {
                $error = "Gagal menambahkan juri: " . $conn->error;
            }
        }
    }
}

// Proses edit juri
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'edit') {
    $id = (int)$_POST['id'];
    $nama = sanitizeInput($_POST['nama']);
    $email = sanitizeInput($_POST['email']);
    $id_cabang_lomba = $_POST['id_cabang_lomba'] != '' ? (int)$_POST['id_cabang_lomba'] : null;
    $password = !empty($_POST['password']) ? strtoupper($_POST['password']) : '';

    // Cek email sudah ada atau belum (selain user yang sedang diedit)
    $stmt = $conn->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
    $stmt->bind_param("si", $email, $id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $error = "Email sudah digunakan oleh pengguna lain!";
    } else {
        if (empty($password)) {
            // Update tanpa password baru tanpa domisili
            $stmt = $conn->prepare("UPDATE users SET nama_lengkap = ?, email = ?, id_cabang_lomba = ? WHERE id = ?");
            $stmt->bind_param("ssii", $nama, $email, $id_cabang_lomba, $id);
        } else {
            // Update dengan password baru tanpa domisili
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("UPDATE users SET nama_lengkap = ?, email = ?, id_cabang_lomba = ?, password = ? WHERE id = ?");
            $stmt->bind_param("ssisi", $nama, $email, $id_cabang_lomba, $hashed_password, $id);
        }

        if ($stmt->execute()) {
            $success = "Juri berhasil diperbarui!";
        } else {
            $error = "Gagal memperbarui juri: " . $conn->error;
        }
    }
}

// Proses hapus juri
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'delete') {
    $id = (int)$_POST['id'];

    // Cek apakah juri sudah memberi penilaian
    $stmt = $conn->prepare("SELECT id FROM penilaian WHERE id_juri = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $error = "Juri tidak dapat dihapus karena sudah memberikan penilaian!";
    } else {
        $stmt = $conn->prepare("DELETE FROM users WHERE id = ? AND role = 'juri'");
        $stmt->bind_param("i", $id);

        if ($stmt->execute() && $stmt->affected_rows > 0) {
            $success = "Juri berhasil dihapus!";
        } else {
            $error = "Gagal menghapus juri: " . $conn->error;
        }
    }
}

// Proses import CSV
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'import') {
    if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] == 0) {
        $file_tmp = $_FILES['csv_file']['tmp_name'];
        $file_type = $_FILES['csv_file']['type'];

        // Cek tipe file (harus CSV)
        if ($file_type == 'text/csv' || $file_type == 'application/vnd.ms-excel' || $file_type == 'application/octet-stream') {
            // Buka file CSV
            $handle = fopen($file_tmp, "r");

            if ($handle !== FALSE) {
                // Skip header row
                $header = fgetcsv($handle, 1000, ",");

                $success_count = 0;
                $error_count = 0;
                $errors = [];

                // Loop data CSV
                while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    if (count($data) >= 5) {
                        $username = strtoupper(sanitizeInput($data[0]));
                        $password = strtoupper(sanitizeInput($data[1]));
                        $nama = sanitizeInput($data[2]);
                        $email = sanitizeInput($data[3]);

                        // Cabang lomba (jika ada)
                        $cabang_lomba_nama = isset($data[4]) ? trim($data[4]) : '';
                        $id_cabang_lomba = null;

                        if (!empty($cabang_lomba_nama)) {
                            // Cari ID cabang lomba berdasarkan nama
                            $stmt_cabang = $conn->prepare("SELECT ID FROM cabang_lomba WHERE Bidang_Lomba = ?");
                            $stmt_cabang->bind_param("s", $cabang_lomba_nama);
                            $stmt_cabang->execute();
                            $cabang_result = $stmt_cabang->get_result();

                            if ($cabang_result->num_rows > 0) {
                                $cabang_row = $cabang_result->fetch_assoc();
                                $id_cabang_lomba = $cabang_row['ID'];
                            }
                        }

                        // Cek username dan email
                        $stmt_check = $conn->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
                        $stmt_check->bind_param("ss", $username, $email);
                        $stmt_check->execute();
                        $check_result = $stmt_check->get_result();

                        if ($check_result->num_rows > 0) {
                            $error_count++;
                            $errors[] = "Baris gagal: $username, $email (Username atau email sudah digunakan)";
                            continue;
                        }

                        // Hash password dan insert data tanpa domisili
                        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                        $stmt_insert = $conn->prepare("INSERT INTO users (username, password, role, nama_lengkap, email, id_cabang_lomba) VALUES (?, ?, 'juri', ?, ?, ?)");
                        $stmt_insert->bind_param("ssssi", $username, $hashed_password, $nama, $email, $id_cabang_lomba);

                        if ($stmt_insert->execute()) {
                            $success_count++;
                        } else {
                            $error_count++;
                            $errors[] = "Baris gagal: $username, $email (Error database: " . $conn->error . ")";
                        }
                    } else {
                        $error_count++;
                        $errors[] = "Baris gagal: Format CSV tidak valid";
                    }
                }

                fclose($handle);

                // Tampilkan hasil import
                $success = "Import CSV selesai. Berhasil: $success_count, Gagal: $error_count";
                if ($error_count > 0) {
                    $error = implode("<br>", $errors);
                }
            } else {
                $error = "Gagal membuka file CSV";
            }
        } else {
            $error = "Format file harus CSV";
        }
    } else {
        $error = "Gagal mengupload file";
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="shortcut icon" href="../../../assets/logoFLS3N.png" type="image/x-icon" />
    <title>Kelola Juri - Sistem Penilaian Karya Siswa</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" />
    <style>
        .custom-file-label::after {
            content: "Browse";
        }
        .text-uppercase {
            text-transform: uppercase;
        }
    </style>
</head>
<body>
    <?php include '../sidebar.php'; ?>
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">Kelola Juri</h1>
                    <div>
                        <button type="button" class="btn btn-success me-2" data-bs-toggle="modal" data-bs-target="#importCSVModal">
                            <i class="fas fa-file-import"></i> Import CSV
                        </button>
                        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addJuriModal">
                            <i class="fas fa-plus"></i> Tambah Juri
                        </button>
                    </div>
                </div>

                <?php if (!empty($error)): ?>
                    <div class="alert alert-danger"><?php echo $error; ?></div>
                <?php endif; ?>

                <?php if (!empty($success)): ?>
                    <div class="alert alert-success"><?php echo $success; ?></div>
                <?php endif; ?>

                <div class="card">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>Username</th>
                                        <th>Nama</th>
                                        <th>Email</th>
                                        <th>Cabang Lomba</th>
                                        <th>Tgl Dibuat</th>
                                        <th>Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $sql = "SELECT u.id, u.username, u.nama_lengkap, u.email, c.Bidang_Lomba, u.id_cabang_lomba, u.created_at 
                                            FROM users u
                                            LEFT JOIN cabang_lomba c ON u.id_cabang_lomba = c.ID
                                            WHERE u.role = 'juri'
                                            ORDER BY u.id";
                                    $result = $conn->query($sql);

                                    if ($result->num_rows > 0) {
                                        while($row = $result->fetch_assoc()) {
                                            echo "<tr>";
                                            echo "<td class='text-uppercase'>" . $row["username"] . "</td>";
                                            echo "<td>" . $row["nama_lengkap"] . "</td>";
                                            echo "<td>" . $row["email"] . "</td>";
                                            echo "<td>" . ($row["Bidang_Lomba"] ? $row["Bidang_Lomba"] : "Belum ditentukan") . "</td>";
                                            echo "<td>" . date('d-m-Y H:i', strtotime($row["created_at"])) . "</td>";
                                            echo "<td>";
                                            echo "<button type='button' class='btn btn-sm btn-info me-1' data-bs-toggle='modal' data-bs-target='#editJuriModal' 
                                                  data-id='" . $row["id"] . "'
                                                  data-nama='" . $row["nama_lengkap"] . "'
                                                  data-email='" . $row["email"] . "'
                                                  data-cabang='" . $row["id_cabang_lomba"] . "'>
                                                  <i class='fas fa-edit'></i></button>";
                                            echo "<button type='button' class='btn btn-sm btn-danger' data-bs-toggle='modal' data-bs-target='#deleteJuriModal' data-id='" . $row["id"] . "' data-nama='" . $row["nama_lengkap"] . "'>
                                                  <i class='fas fa-trash'></i></button>";
                                            echo "</td>";
                                            echo "</tr>";
                                        }
                                    } else {
                                        echo "<tr><td colspan='6' class='text-center'>Tidak ada data juri</td></tr>";
                                    }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Import CSV -->
    <div class="modal fade" id="importCSVModal" tabindex="-1" aria-labelledby="importCSVModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="importCSVModalLabel">Import Data Juri dari CSV</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post" action="" enctype="multipart/form-data">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="import" />

                        <div class="mb-3">
                            <label for="csv_file" class="form-label">File CSV</label>
                            <input type="file" class="form-control" id="csv_file" name="csv_file" accept=".csv" required />
                        </div>

                        <div class="alert alert-info">
                            <h6>Format CSV:</h6>
                            <p>1. Baris pertama adalah header (akan diabaikan)</p>
                            <p>2. Kolom: Username, Password, Nama Lengkap, Email, Cabang Lomba</p>
                            <p>3. Contoh:</p>
                            <pre>Username,Password,Nama Lengkap,Email,Cabang Lomba
juri1,password1,Nama Juri 1,juri1@email.com,Tari
juri2,password2,Nama Juri 2,juri2@email.com,Musik</pre>
                            <p><small>Catatan: Username dan Password akan otomatis diubah menjadi huruf kapital</small></p>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-primary">Import</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal Tambah Juri -->
    <div class="modal fade" id="addJuriModal" tabindex="-1" aria-labelledby="addJuriModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addJuriModalLabel">Tambah Juri</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post" action="">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="add" />
                        <div class="mb-3">
                            <label for="username" class="form-label">Username</label>
                            <input type="text" class="form-control text-uppercase" id="username" name="username" required oninput="this.value = this.value.toUpperCase()" />
                        </div>
                        <div class="mb-3">
                            <label for="password" class="form-label">Password</label>
                            <input type="password" class="form-control text-uppercase" id="password" name="password" required oninput="this.value = this.value.toUpperCase()" />
                        </div>
                        <div class="mb-3">
                            <label for="nama" class="form-label">Nama Lengkap</label>
                            <input type="text" class="form-control" id="nama" name="nama" required />
                        </div>
                        <div class="mb-3">
                            <label for="email" class="form-label">Email</label>
                            <input type="email" class="form-control" id="email" name="email" required />
                        </div>
                        <div class="mb-3">
                            <label for="id_cabang_lomba" class="form-label">Cabang Lomba</label>
                            <select class="form-select" id="id_cabang_lomba" name="id_cabang_lomba">
                                <option value="">Pilih Cabang Lomba</option>
                                <?php
                                $sql = "SELECT ID, Bidang_Lomba FROM cabang_lomba ORDER BY Bidang_Lomba";
                                $result = $conn->query($sql);

                                if ($result->num_rows > 0) {
                                    while($row = $result->fetch_assoc()) {
                                        echo "<option value='" . $row["ID"] . "'>" . $row["Bidang_Lomba"] . "</option>";
                                    }
                                }
                                ?>
                            </select>
                        </div>
                        <!-- Domisili dihapus -->
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-primary">Simpan</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal Edit Juri -->
    <div class="modal fade" id="editJuriModal" tabindex="-1" aria-labelledby="editJuriModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editJuriModalLabel">Edit Juri</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post" action="">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="edit" />
                        <input type="hidden" name="id" id="edit-id" />
                        <div class="mb-3">
                            <label for="edit-nama" class="form-label">Nama Lengkap</label>
                            <input type="text" class="form-control" id="edit-nama" name="nama" required />
                        </div>
                        <div class="mb-3">
                            <label for="edit-email" class="form-label">Email</label>
                            <input type="email" class="form-control" id="edit-email" name="email" required />
                        </div>
                        <div class="mb-3">
                            <label for="edit-password" class="form-label">Password Baru (kosongkan jika tidak diubah)</label>
                            <input type="password" class="form-control text-uppercase" id="edit-password" name="password" oninput="this.value = this.value.toUpperCase()" />
                        </div>
                        <div class="mb-3">
                            <label for="edit-id_cabang_lomba" class="form-label">Cabang Lomba</label>
                            <select class="form-select" id="edit-id_cabang_lomba" name="id_cabang_lomba">
                                <option value="">Pilih Cabang Lomba</option>
                                <?php
                                $sql = "SELECT ID, Bidang_Lomba FROM cabang_lomba ORDER BY Bidang_Lomba";
                                $result = $conn->query($sql);

                                if ($result->num_rows > 0) {
                                    while($row = $result->fetch_assoc()) {
                                        echo "<option value='" . $row["ID"] . "'>" . $row["Bidang_Lomba"] . "</option>";
                                    }
                                }
                                ?>
                            </select>
                        </div>
                        <!-- Domisili dihapus -->
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal Hapus Juri -->
    <div class="modal fade" id="deleteJuriModal" tabindex="-1" aria-labelledby="deleteJuriModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteJuriModalLabel">Konfirmasi Hapus</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Apakah Anda yakin ingin menghapus juri <span id="delete-juri-nama"></span>?</p>
                </div>
                <div class="modal-footer">
                    <form method="post" action="">
                        <input type="hidden" name="action" value="delete" />
                        <input type="hidden" name="id" id="delete-id" />
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-danger">Hapus</button>
                    </form>
                </div>
            </div>
        </div>

    <script>
        // Script untuk mengisi modal edit
        document.getElementById('editJuriModal').addEventListener('show.bs.modal', function (event) {
            var button = event.relatedTarget;
            var id = button.getAttribute('data-id');
            var nama = button.getAttribute('data-nama');
            var email = button.getAttribute('data-email');
            var cabang = button.getAttribute('data-cabang');

            document.getElementById('edit-id').value = id;
            document.getElementById('edit-nama').value = nama;
            document.getElementById('edit-email').value = email;
            document.getElementById('edit-id_cabang_lomba').value = cabang;
        });

        // Script untuk mengisi modal hapus
        document.getElementById('deleteJuriModal').addEventListener('show.bs.modal', function (event) {
            var button = event.relatedTarget;
            var id = button.getAttribute('data-id');
            var nama = button.getAttribute('data-nama');

            document.getElementById('delete-id').value = id;
            document.getElementById('delete-juri-nama').textContent = nama;
        });
    </script>

    <?php include '../sidebar-footer.php'; ?>

<?php $conn->close(); ?>