<?php 
session_start();
require_once '../koneksi.php';
require_once '../auth.php';
cekAdminAtauGuru(); 

// Ambil ID dari URL dan amankan dari SQL Injection
$id = isset($_GET['id']) ? mysqli_real_escape_string($koneksi, $_GET['id']) : '';

// Jika ID kosong, kembalikan ke halaman utama
if (empty($id)) {
    header("Location: siswa.php");
    exit();
}

// Ambil data siswa berdasarkan ID
$query_siswa = mysqli_query($koneksi, "SELECT * FROM master_siswa WHERE id_siswa = '$id'");
$data = mysqli_fetch_array($query_siswa);

// Jika data siswa tidak ditemukan, kembalikan ke halaman utama
if (!$data) {
    echo "<script>alert('Data siswa tidak ditemukan!'); window.location.href='siswa.php';</script>";
    exit();
}

// Proses Update Data
if(isset($_POST['update'])) {
    $nis      = mysqli_real_escape_string($koneksi, $_POST['nis']);
    $nisn     = mysqli_real_escape_string($koneksi, $_POST['nisn']);
    $nama     = mysqli_real_escape_string($koneksi, $_POST['nama']);
    $jk       = mysqli_real_escape_string($koneksi, $_POST['jk']);
    $username = mysqli_real_escape_string($koneksi, $_POST['username']);
    $password = $_POST['password'];

    // 1. Logika Update Password (hanya diupdate jika diisi)
    if (!empty($password)) {
        // Menggunakan password_hash demi keamanan (ganti md5 jika sistem Anda masih memakai md5 lama)
        $password_secure = password_hash($password, PASSWORD_BCRYPT);
        $query_pwd = ", username='$username', password='$password_secure'";
    } else {
        $query_pwd = ", username='$username'";
    }
    
    // 2. Cek apakah ada upload foto baru
    if($_FILES['foto']['name'] != "") {
        $foto_nama_asli = $_FILES['foto']['name'];
        $ext = pathinfo($foto_nama_asli, PATHINFO_EXTENSION);
        
        // Buat nama file unik (Contoh: 12345678_20231024.jpg) untuk menghindari file tertimpa
        $foto = $nis . "_" . date('YmdHis') . "." . $ext;
        
        // Hapus foto lama di server jika ada, agar tidak menjadi sampah penyimpanan
        if (!empty($data['foto']) && file_exists("../assets/img/siswa/" . $data['foto'])) {
            unlink("../assets/img/siswa/" . $data['foto']);
        }
        
        move_uploaded_file($_FILES['foto']['tmp_name'], "../assets/img/siswa/".$foto);
        
        // Query dengan Foto Baru
        $sql_update = "UPDATE master_siswa SET nis='$nis', nisn='$nisn', nama='$nama', jk='$jk', foto='$foto' $query_pwd WHERE id_siswa='$id'";
    } else {
        // Query Tanpa Ganti Foto
        $sql_update = "UPDATE master_siswa SET nis='$nis', nisn='$nisn', nama='$nama', jk='$jk' $query_pwd WHERE id_siswa='$id'";
    }
    
    $eksekusi = mysqli_query($koneksi, $sql_update);
    
    if($eksekusi) {
        echo "<script>alert('Data berhasil diupdate'); window.location.href='siswa.php';</script>";
    } else {
        echo "<script>alert('Gagal mengupdate data: " . mysqli_error($koneksi) . "');</script>";
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Data Siswa</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="bg-light p-4">

<div class="container">
    <div class="card shadow-sm col-md-6 mx-auto border-0">
        <div class="card-header bg-primary text-white d-flex align-items-center gap-2">
            <i class="fa fa-user-edit"></i>
            <h5 class="mb-0">Edit Data Siswa</h5>
        </div>
        <div class="card-body p-4">
            <form method="POST" enctype="multipart/form-data">
                
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-bold">NIS</label>
                        <input type="text" name="nis" class="form-control" value="<?= htmlspecialchars($data['nis']) ?>" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-bold">NISN</label>
                        <input type="text" name="nisn" class="form-control" value="<?= htmlspecialchars($data['nisn'] ?? '') ?>" required>
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label fw-bold">Nama Lengkap</label>
                    <input type="text" name="nama" class="form-control" value="<?= htmlspecialchars($data['nama']) ?>" required>
                </div>

                <div class="mb-3">
                    <label class="form-label fw-bold">Jenis Kelamin</label>
                    <select name="jk" class="form-select">
                        <option value="L" <?= ($data['jk'] == 'L') ? 'selected' : '' ?>>Laki-laki</option>
                        <option value="P" <?= ($data['jk'] == 'P') ? 'selected' : '' ?>>Perempuan</option>
                    </select>
                </div>

                <hr class="text-muted my-4">
                <h6 class="text-primary fw-bold mb-3"><i class="fa fa-lock"></i> Akun Login Siswa</h6>

                <div class="mb-3">
                    <label class="form-label fw-bold">Username</label>
                    <input type="text" name="username" class="form-control" value="<?= htmlspecialchars($data['username'] ?? '') ?>" placeholder="Masukkan username untuk login siswa" required>
                </div>

                <div class="mb-3">
                    <label class="form-label fw-bold">Password Baru</label>
                    <input type="password" name="password" class="form-control" placeholder="Biarkan kosong jika tidak ingin mengubah password">
                    <div class="form-text text-muted">Isi kolom ini hanya jika siswa ingin mengganti password loginnya.</div>
                </div>

                <hr class="text-muted my-4">

                <div class="mb-4">
                    <label class="form-label fw-bold">Foto Siswa</label>
                    <input type="file" name="foto" class="form-control" accept="image/*">
                    <div class="form-text text-muted mt-2 d-flex align-items-center gap-2">
                        <?php 
                        $foto_path = (!empty($data['foto']) && file_exists('../assets/img/siswa/'.$data['foto'])) ? '../assets/img/siswa/'.$data['foto'] : '../assets/img/default.png';
                        ?>
                        <img src="<?= $foto_path ?>" width="40" height="40" class="rounded border" style="object-fit: cover;">
                        <span>File saat ini: <code class="text-secondary"><?= htmlspecialchars($data['foto'] ?: 'default.png') ?></code></span>
                    </div>
                </div>

                <div class="d-flex gap-2">
                    <button type="submit" name="update" class="btn btn-success px-4"><i class="fa fa-save me-1"></i> Simpan Perubahan</button>
                    <a href="siswa.php" class="btn btn-secondary px-4"><i class="fa fa-arrow-left me-1"></i> Batal</a>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>