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

include 'includes/header_pelajar.php';
include 'includes/sidebar_pelajar.php';
include 'includes/config.php';

$id_pelajar = (int) $_SESSION['id_pelajar'];
$message = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $kata_laluan_lama = $_POST['kata_laluan_lama'];
    $kata_laluan_baru = $_POST['kata_laluan_baru'];
    $ulang_kata_laluan_baru = $_POST['ulang_kata_laluan_baru'];

    // Dapatkan kata laluan semasa dari database
    $res = mysqli_query($conn, "SELECT kata_laluan FROM pelajar WHERE id=$id_pelajar LIMIT 1");
    $row = mysqli_fetch_assoc($res);

    if (!password_verify($kata_laluan_lama, $row['kata_laluan'])) {
        $message = "Kata laluan semasa tidak betul.";
    } elseif ($kata_laluan_baru !== $ulang_kata_laluan_baru) {
        $message = "Kata laluan baru dan pengesahan tidak sama.";
    } else {
        $hash_baru = password_hash($kata_laluan_baru, PASSWORD_DEFAULT);
        mysqli_query($conn, "UPDATE pelajar SET kata_laluan='$hash_baru' WHERE id=$id_pelajar");
        $message = "Kata laluan berjaya dikemaskini.";
    }
}
?>

<div class="main-content">
    <h2 class="page-title">Tukar Kata Laluan</h2>

    <?php if($message): ?>
        <div class="alert alert-info"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>

    <div class="card-container" style="max-width:500px;">
        <form method="POST">
            <div class="mb-3">
                <label>Kata Laluan Semasa</label>
                <input type="password" name="kata_laluan_lama" class="form-control" required>
            </div>
            <div class="mb-3">
                <label>Kata Laluan Baru</label>
                <input type="password" name="kata_laluan_baru" class="form-control" required>
            </div>
            <div class="mb-3">
                <label>Sahkan Kata Laluan Baru</label>
                <input type="password" name="ulang_kata_laluan_baru" class="form-control" required>
            </div>

            <div class="mt-3">
                <button type="submit" class="btn-official">Kemaskini Kata Laluan</button>
                <a href="profil_pelajar.php" class="btn-official">Kembali ke Profil</a>
            </div>
        </form>
    </div>
</div>

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