<?php
session_start();
if (!isset($_SESSION['admin_id'])) {
    header('Location: login_admin.php');
    exit;
}
include 'includes/header.php';
include 'includes/sidebar.php';
include 'includes/config.php';

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nama = trim($_POST['nama']);
    $no_ic = trim($_POST['no_ic']);
    $no_pendaftaran = trim($_POST['no_pendaftaran']);
    $jantina = $_POST['jantina'];
    $bangsa = $_POST['bangsa'];
    $agama = $_POST['agama'];
    $warganegara = $_POST['warganegara'];
    $emel = trim($_POST['emel']);
    $no_telefon = trim($_POST['no_telefon']);
    $program = $_POST['program'];
    $username = trim($_POST['username']);
    $kata_laluan = password_hash($_POST['kata_laluan'], PASSWORD_DEFAULT);
    $status = $_POST['status'];

    // Check duplicate IC / email / username
    $check = mysqli_query($conn, "SELECT id FROM pelajar WHERE no_ic='$no_ic' OR emel='$emel' OR username='$username' LIMIT 1");
    if (mysqli_num_rows($check) > 0) {
        $errors[] = "No IC, E-mel, atau Username telah digunakan.";
    }

    // Upload gambar jika ada
    $gambar = null;
    if (!empty($_FILES['gambar']['name'])) {
        $allowed_ext = ['jpg','jpeg','png','gif'];
        $file_ext = strtolower(pathinfo($_FILES['gambar']['name'], PATHINFO_EXTENSION));
        if (!in_array($file_ext, $allowed_ext)) {
            $errors[] = "Hanya format JPG, JPEG, PNG, GIF dibenarkan.";
        } else {
            if (!is_dir('uploads')) mkdir('uploads', 0777, true);
            $gambar = 'pelajar_' . time() . '.' . $file_ext;
            move_uploaded_file($_FILES['gambar']['tmp_name'], 'uploads/' . $gambar);
        }
    }

    if (empty($errors)) {
        $stmt = $conn->prepare("INSERT INTO pelajar (nama,no_ic,no_pendaftaran,jantina,bangsa,agama,warganegara,emel,gambar,no_telefon,program,username,kata_laluan,status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        $stmt->bind_param("ssssssssssssss", $nama,$no_ic,$no_pendaftaran,$jantina,$bangsa,$agama,$warganegara,$emel,$gambar,$no_telefon,$program,$username,$kata_laluan,$status);
        if ($stmt->execute()) {
            echo "<script>alert('Pendaftaran pelajar berjaya.'); window.location='senarai_pelajar.php';</script>";
            exit;
        } else {
            $errors[] = "Gagal mendaftar pelajar.";
        }
    }
}
?>

<div class="container mt-4">
    <h3 class="mb-4">Daftar Pelajar (Admin)</h3>
    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger"><?= implode('<br>', $errors) ?></div>
    <?php endif; ?>

    <form action="" method="post" enctype="multipart/form-data">
        <?php include 'includes/form_pelajar_fields.php'; ?>
        <div class="mt-3">
            <button type="submit" class="btn btn-primary">Daftar</button>
            <a href="senarai_pelajar.php" class="btn btn-secondary">Kembali</a>
        </div>
    </form>
</div>

<?php include 'includes/footer.php'; ?>
