<?php
session_start();
include 'includes/config.php';

if (!isset($_SESSION['id_pelajar'])) {
    header('Location: login_pelajar.php');
    exit;
}

$id_pelajar = $_SESSION['id_pelajar'];

// Semak jika ada fail dihantar
if (isset($_FILES['gambar']) && $_FILES['gambar']['error'] == 0) {

    $allowed_ext = ['jpg', 'jpeg', 'png', 'gif'];
    $file_name = $_FILES['gambar']['name'];
    $file_tmp = $_FILES['gambar']['tmp_name'];
    $file_size = $_FILES['gambar']['size'];

    // Dapatkan extension fail
    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

    if (!in_array($file_ext, $allowed_ext)) {
        echo "<script>alert('Hanya format JPG, JPEG, PNG, GIF dibenarkan.'); window.location='dashboard_pelajar.php';</script>";
        exit;
    }

    // Pastikan folder uploads wujud
    if (!is_dir('uploads')) {
        mkdir('uploads', 0777, true);
    }

    // Nama fail unik (ikut ID pelajar)
    $new_file_name = 'pelajar_' . $id_pelajar . '.' . $file_ext;
    $file_path = 'uploads/' . $new_file_name;

    // Pindahkan fail ke folder uploads
    if (move_uploaded_file($file_tmp, $file_path)) {
        // Kemaskini DB
        $stmt = mysqli_prepare($conn, "UPDATE pelajar SET gambar = ? WHERE id = ?");
        mysqli_stmt_bind_param($stmt, 'si', $new_file_name, $id_pelajar);
        mysqli_stmt_execute($stmt);

        echo "<script>alert('Gambar berjaya dikemas kini.'); window.location='dashboard_pelajar.php';</script>";
        exit;
    } else {
        echo "<script>alert('Gagal memuat naik gambar.'); window.location='dashboard_pelajar.php';</script>";
        exit;
    }

} else {
    echo "<script>alert('Tiada fail dipilih.'); window.location='dashboard_pelajar.php';</script>";
    exit;
}
