<?php
session_start();
include '../koneksi.php';

// Cek role guru
if (!isset($_SESSION['id']) || $_SESSION['role'] !== 'guru') {
    header("Location: ../login.php");
    exit;
}

$user_id = $_SESSION['id'];

// Ambil data user
$user = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT * FROM users WHERE id='$user_id'"));
if (!$user) {
    die("User tidak ditemukan.");
}

// Ambil data guru (SELARAS dengan profil.php)
$guru = mysqli_fetch_assoc(mysqli_query($koneksi, "
    SELECT * FROM guru 
    WHERE nip='{$user['username']}' 
    OR id='$user_id'
"));

if (!$guru) {
    // fallback terakhir (sama seperti profil.php)
    $guru = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT * FROM guru ORDER BY id DESC LIMIT 1"));
    if (!$guru) {
        die("Data guru tidak ditemukan.");
    }
}

$guru_id = $guru['id']; // PENTING: id asli guru
$success = false;

if (isset($_POST['submit'])) {

    function esc($v){
        global $koneksi;
        return mysqli_real_escape_string($koneksi, $v);
    }

    $nip           = esc($_POST['nip']);
    $nama_lengkap  = esc($_POST['nama_lengkap']);
    $tempat_lahir  = esc($_POST['tempat_lahir']);
    $tanggal_lahir = esc($_POST['tanggal_lahir']);
    $jenis_kelamin = esc($_POST['jenis_kelamin']);
    $alamat        = esc($_POST['alamat']);
    $no_wa         = esc($_POST['no_wa']);
    $email         = esc($_POST['email']);
    $mapel         = esc($_POST['mapel']);
    $jabatan       = esc($_POST['jabatan']);
    $status        = esc($_POST['status']);

    // Foto
    $foto_nama = $guru['foto'];
    if (!empty($_FILES['foto']['name'])) {
        $ext = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg','jpeg','png'])) {
            $foto_nama = 'guru_'.$guru_id.'.'.$ext;
            move_uploaded_file($_FILES['foto']['tmp_name'], "../uploads/".$foto_nama);
        }
    }

    mysqli_query($koneksi, "
        UPDATE guru SET
            nip='$nip',
            nama_lengkap='$nama_lengkap',
            tempat_lahir='$tempat_lahir',
            tanggal_lahir='$tanggal_lahir',
            jenis_kelamin='$jenis_kelamin',
            alamat='$alamat',
            no_wa='$no_wa',
            email='$email',
            mapel='$mapel',
            jabatan='$jabatan',
            status='$status',
            foto='$foto_nama'
        WHERE id='$guru_id'
    ");

    $success = true;
}

// Foto preview
$foto_preview = "../assets/default-profile.png";
if (!empty($guru['foto']) && file_exists("../uploads/".$guru['foto'])) {
    $foto_preview = "../uploads/".$guru['foto'];
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Edit Data Diri Guru | MAYABSEN</title>

<link href="../bootstrap-5.3.8-dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
body{background:#f4f8f6;font-family:'Poppins',sans-serif;color:#555;}
.form-wrapper{width:92%;max-width:720px;margin:30px auto;}
.card-form{background:#fff;border-radius:22px;padding:26px;box-shadow:0 10px 30px rgba(0,0,0,.08);}
.section-title{font-weight:700;font-size:.85rem;letter-spacing:.7px;color:#2e8b57;margin:18px 0 10px;}
.photo-preview{width:120px;height:120px;border-radius:50%;object-fit:cover;box-shadow:0 8px 20px rgba(0,0,0,.2);}
.btn-save{background:linear-gradient(135deg,#2e8b57,#1f6f43);color:#fff;font-weight:600;}
</style>
</head>

<body>

<div class="form-wrapper">
<div class="card-form">

<a href="profil.php" class="text-secondary">
    <i class="bi bi-arrow-left fs-4"></i>
</a>

<form method="POST" enctype="multipart/form-data">

<div class="section-title">DATA GURU</div>

<div class="form-floating mb-3">
    <input type="text" name="nip" class="form-control" value="<?= $guru['nip'] ?>" required>
    <label>NIP</label>
</div>

<div class="form-floating mb-3">
    <input type="text" name="nama_lengkap" class="form-control" value="<?= $guru['nama_lengkap'] ?>" required>
    <label>Nama Lengkap</label>
</div>

<div class="row g-3">
    <div class="col-md-6 form-floating">
        <input type="text" name="tempat_lahir" class="form-control" value="<?= $guru['tempat_lahir'] ?>" required>
        <label>Tempat Lahir</label>
    </div>
    <div class="col-md-6 form-floating">
        <input type="date" name="tanggal_lahir" class="form-control" value="<?= $guru['tanggal_lahir'] ?>" required>
        <label>Tanggal Lahir</label>
    </div>
</div>

<div class="form-floating my-3">
<select name="jenis_kelamin" class="form-select" required>
    <option value="L" <?= $guru['jenis_kelamin']=='L'?'selected':'' ?>>Laki-laki</option>
    <option value="P" <?= $guru['jenis_kelamin']=='P'?'selected':'' ?>>Perempuan</option>
</select>
<label>Jenis Kelamin</label>
</div>

<div class="form-floating my-3">
<textarea name="alamat" class="form-control" style="height:90px" required><?= $guru['alamat'] ?></textarea>
<label>Alamat</label>
</div>

<div class="row g-3">
    <div class="col-md-6 form-floating">
        <input type="text" name="no_wa" class="form-control" value="<?= $guru['no_wa'] ?>" required>
        <label>No WhatsApp</label>
    </div>
    <div class="col-md-6 form-floating">
        <input type="email" name="email" class="form-control" value="<?= $guru['email'] ?>" required>
        <label>Email</label>
    </div>
</div>

<div class="row g-3">
    <div class="col-md-6 form-floating">
        <input type="text" name="mapel" class="form-control" value="<?= $guru['mapel'] ?>" required>
        <label>Mata Pelajaran</label>
    </div>
    <div class="col-md-6 form-floating">
        <input type="text" name="jabatan" class="form-control" value="<?= $guru['jabatan'] ?>" required>
        <label>Jabatan</label>
    </div>
</div>

<div class="form-floating my-3">
<select name="status" class="form-select" required>
    <option value="Aktif" <?= $guru['status']=='Aktif'?'selected':'' ?>>Aktif</option>
    <option value="Nonaktif" <?= $guru['status']=='Nonaktif'?'selected':'' ?>>Nonaktif</option>
</select>
<label>Status</label>
</div>

<div class="section-title">FOTO PROFIL</div>

<div class="text-center mb-2">
    <img id="previewFoto" src="<?= $foto_preview ?>" class="photo-preview">
</div>

<input type="file" name="foto" class="form-control" accept="image/*" onchange="previewImage(this)">

<button name="submit" class="btn btn-save w-100 rounded-pill py-2 mt-4">
    <i class="bi bi-save me-1"></i> Simpan Perubahan
</button>

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

<script>
function previewImage(input){
    if(input.files && input.files[0]){
        const reader = new FileReader();
        reader.onload = e => document.getElementById('previewFoto').src = e.target.result;
        reader.readAsDataURL(input.files[0]);
    }
}
</script>

<?php if($success): ?>
<script>
Swal.fire({
    icon:'success',
    title:'Berhasil!',
    text:'Data berhasil diperbarui',
    showConfirmButton:false,
    timer:1300
});
setTimeout(()=>window.location='profil.php',1300);
</script>
<?php endif; ?>

<script src="../bootstrap-5.3.8-dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
