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

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

// Proses tambah admin 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']);

    // 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 dengan role admin
            $stmt = $conn->prepare("INSERT INTO users (username, password, role, nama_lengkap, email) VALUES (?, ?, 'admin', ?, ?)");
            $stmt->bind_param("ssss", $username, $hashed_password, $nama, $email);

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

// Proses edit admin
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'edit') {
    $id = (int)$_POST['id'];
    $nama = sanitizeInput($_POST['nama']);
    $email = sanitizeInput($_POST['email']);
    $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
            $stmt = $conn->prepare("UPDATE users SET nama_lengkap = ?, email = ? WHERE id = ?");
            $stmt->bind_param("ssi", $nama, $email, $id);
        } else {
            // Update dengan password baru
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("UPDATE users SET nama_lengkap = ?, email = ?, password = ? WHERE id = ?");
            $stmt->bind_param("sssi", $nama, $email, $hashed_password, $id);
        }

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

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

    // Cegah penghapusan admin super (asumsi ID 1)
    if ($id == 1) {
        $error = "Admin utama tidak dapat dihapus!";
    } else {
        $stmt = $conn->prepare("DELETE FROM users WHERE id = ? AND role = 'admin'");
        $stmt->bind_param("i", $id);

        if ($stmt->execute() && $stmt->affected_rows > 0) {
            $success = "Admin berhasil dihapus!";
        } else {
            $error = "Gagal menghapus admin: " . $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) >= 4) {
                        $username = strtoupper(sanitizeInput($data[0]));
                        $password = strtoupper(sanitizeInput($data[1]));
                        $nama = sanitizeInput($data[2]);
                        $email = sanitizeInput($data[3]);

                        // 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
                        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                        $stmt_insert = $conn->prepare("INSERT INTO users (username, password, role, nama_lengkap, email) VALUES (?, ?, 'admin', ?, ?)");
                        $stmt_insert->bind_param("ssss", $username, $hashed_password, $nama, $email);

                        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 Admin - 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 Admin</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="#addAdminModal">
                            <i class="fas fa-plus"></i> Tambah Admin
                        </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>Tgl Dibuat</th>
                                        <th>Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $sql = "SELECT u.id, u.username, u.nama_lengkap, u.email, u.created_at 
                                            FROM users u
                                            WHERE u.role = 'admin'
                                            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>" . 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='#editAdminModal' 
                                                  data-id='" . $row["id"] . "'
                                                  data-nama='" . $row["nama_lengkap"] . "'
                                                  data-email='" . $row["email"] . "'>
                                                  <i class='fas fa-edit'></i></button>";
                                            if ($row["id"] != 1) {
                                                echo "<button type='button' class='btn btn-sm btn-danger' data-bs-toggle='modal' data-bs-target='#deleteAdminModal' 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='5' class='text-center'>Tidak ada data admin</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 Admin 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</p>
                            <p>3. Contoh:</p>
                            <pre>Username,Password,Nama Lengkap,Email
admin1,password1,Nama Admin 1,admin1@email.com
admin2,password2,Nama Admin 2,admin2@email.com</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 Admin -->
    <div class="modal fade" id="addAdminModal" tabindex="-1" aria-labelledby="addAdminModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addAdminModalLabel">Tambah Admin</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>
                    <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 Admin -->
    <div class="modal fade" id="editAdminModal" tabindex="-1" aria-labelledby="editAdminModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editAdminModalLabel">Edit Admin</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>
                    <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 Admin -->
    <div class="modal fade" id="deleteAdminModal" tabindex="-1" aria-labelledby="deleteAdminModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteAdminModalLabel">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 admin <span id="delete-admin-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('editAdminModal').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');

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

        // Script untuk mengisi modal hapus
        document.getElementById('deleteAdminModal').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-admin-nama').textContent = nama;
        });
    </script>

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

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