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

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

    $gambar = null;
    if (!empty($_FILES['gambar']['name'])) {
        $gambar = time() . '_' . $_FILES['gambar']['name'];
        move_uploaded_file($_FILES['gambar']['tmp_name'], "uploads/" . $gambar);
    }

    $sql = "INSERT INTO pelajar (nama, no_ic, no_pendaftaran, jantina, bangsa, agama, warganegara, emel, no_telefon, program, username, kata_laluan, status, gambar) 
            VALUES ('$nama','$no_ic','$no_pendaftaran','$jantina','$bangsa','$agama','$warganegara','$emel','$no_telefon','$program','$username','$kata_laluan','$status','$gambar')";

    if (mysqli_query($conn, $sql)) {
        echo "<script>alert('Pendaftaran pelajar berjaya!'); window.location='senarai_pelajar.php';</script>";
    } else {
        echo "<script>alert('Ralat: " . mysqli_error($conn) . "');</script>";
    }
}
?>

<div style="margin-left: 180px; margin-top: 100px; padding: 20px; max-width: 1000px;">
    <div class="card shadow-sm border-0">
        <div class="card-header bg-primary text-white">
            <h4 class="mb-0">Daftar Pelajar Baharu</h4>
        </div>
        <div class="card-body">
            <form method="POST" enctype="multipart/form-data">

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

                <div class="d-flex justify-content-between">
                    <a href="senarai_pelajar.php" class="btn btn-secondary">
                        <i class="bi bi-arrow-left"></i> Kembali
                    </a>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-save"></i> Daftar Pelajar
                    </button>
                </div>

            </form>
        </div>
    </div>
</div>

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