<?php
if (!isset($koneksi)) {
    $koneksi = mysqli_connect("localhost", "root", "", "db_rpl2526");
}

if (!$koneksi) {
    die("Koneksi gagal: " . mysqli_connect_error());
}

// Ambil ID Admin dari URL
$id_admin = $_GET['id'] ?? '';
if (empty($id_admin)) {
    echo "<script>alert('ID Admin tidak valid!'); window.location.href = 'index.php?pages=admin';</script>";
    exit;
}

$id_admin = mysqli_real_escape_string($koneksi, $id_admin);

// Ambil data lama admin & user terkait
$query_get = mysqli_query($koneksi, "
    SELECT tbl_admin.*, tbl_users.email 
    FROM tbl_admin 
    JOIN tbl_users ON tbl_admin.id_user = tbl_users.id_user 
    WHERE tbl_admin.id_admin = '$id_admin'
");
$data_lama = mysqli_fetch_assoc($query_get);

if (!$data_lama) {
    echo "<script>alert('Data admin tidak ditemukan!'); window.location.href = 'index.php?pages=admin';</script>";
    exit;
}

// Proses jika tombol Update/Simpan ditekan
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $nama_admin    = mysqli_real_escape_string($koneksi, $_POST['nama_admin'] ?? '');
    $alamat_admin  = mysqli_real_escape_string($koneksi, $_POST['alamat_admin'] ?? '');
    $telepon_admin = mysqli_real_escape_string($koneksi, $_POST['telepon_admin'] ?? '');
    $jenis_kelamin = mysqli_real_escape_string($koneksi, $_POST['jenis_kelamin'] ?? '');
    $email         = mysqli_real_escape_string($koneksi, $_POST['email'] ?? '');
    $password      = $_POST['password'] ?? '';

    if ($nama_admin == '' || $alamat_admin == '' || $telepon_admin == '' || $email == '') {
        echo "<script>alert('Semua field teks wajib diisi!'); history.back();</script>";
        exit;
    }

    $id_user_terkait = $data_lama['id_user'];

    // 1. Update tabel tbl_users (Email & Password opsional)
    if (!empty($password)) {
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        $q_user = "UPDATE tbl_users SET email = '$email', password = '$hashed_password' WHERE id_user = '$id_user_terkait'";
    } else {
        $q_user = "UPDATE tbl_users SET email = '$email' WHERE id_user = '$id_user_terkait'";
    }
    mysqli_query($koneksi, $q_user);

    // 2. Handle Upload Foto Baru (jika ada)
    $nama_foto_db = $data_lama['path_photo_admin'];

    if (isset($_FILES['photo_admin']) && $_FILES['photo_admin']['error'] == UPLOAD_ERR_OK) {
        $nama_file = $_FILES['photo_admin']['name'];
        $tmp_file  = $_FILES['photo_admin']['tmp_name'];
        $ekstensi  = strtolower(pathinfo($nama_file, PATHINFO_EXTENSION));
        $allowed   = ['jpg', 'jpeg', 'png', 'bmp'];

        if (in_array($ekstensi, $allowed)) {
            $target_dir = "../uploads/admin/";
            if (!is_dir($target_dir)) {
                mkdir($target_dir, 0777, true);
            }

            $nama_foto_baru = uniqid("admin_") . "." . $ekstensi;
            $target_file = $target_dir . $nama_foto_baru;

            if (move_uploaded_file($tmp_file, $target_file)) {
                // Hapus foto lama jika ada
                if (!empty($data_lama['path_photo_admin'])) {
                    $old_file_path = $target_dir . basename($data_lama['path_photo_admin']);
                    if (file_exists($old_file_path)) {
                        unlink($old_file_path);
                    }
                }
                $nama_foto_db = $nama_foto_baru;
            }
        }
    }

    // 3. Update tabel tbl_admin
    $query_update_admin = "UPDATE tbl_admin SET 
        nama_admin = '$nama_admin',
        alamat_admin = '$alamat_admin',
        telepon_admin = '$telepon_admin',
        jenis_kelamin = '$jenis_kelamin',
        path_photo_admin = '$nama_foto_db'
        WHERE id_admin = '$id_admin'";

    $exec_update = mysqli_query($koneksi, $query_update_admin);

    if ($exec_update) {
        echo "
        <script>
            alert('Data admin berhasil diperbarui!');
            window.location.href = 'index.php?pages=admin';
        </script>";
        exit;
    } else {
        echo "<script>alert('Gagal memperbarui data admin: " . addslashes(mysqli_error($koneksi)) . "'); history.back();</script>";
        exit;
    }
}
?>

<div class="card shadow-sm border" style="border-radius: 8px;">
    <div class="card-header bg-warning text-dark fw-bold">
        Edit Data Pengguna Admin
    </div>

    <div class="card-body">
        <form action="" method="POST" enctype="multipart/form-data">
            
            <div class="row mb-3 align-items-center">
                <label for="id-admin" class="col-sm-3 col-form-label fw-bold">ID Admin</label>
                <div class="col-sm-9">
                    <input type="text" id="id-admin" value="<?= htmlspecialchars($data_lama['id_admin']); ?>" readonly class="form-control bg-light">
                </div>
            </div>

            <div class="row mb-3 align-items-center">
                <label for="id-user" class="col-sm-3 col-form-label fw-bold">ID User</label>
                <div class="col-sm-9">
                    <input type="text" id="id-user" value="<?= htmlspecialchars($data_lama['id_user']); ?>" readonly class="form-control bg-light">
                </div>
            </div>

            <div class="row mb-3 align-items-center">
                <label for="nama-admin" class="col-sm-3 col-form-label fw-bold">Nama Admin</label>
                <div class="col-sm-9">
                    <input type="text" id="nama-admin" name="nama_admin" value="<?= htmlspecialchars($data_lama['nama_admin']); ?>" class="form-control" required>
                </div>
            </div>

            <div class="row mb-3 align-items-center">
                <label for="alamat-admin" class="col-sm-3 col-form-label fw-bold">Alamat Admin</label>
                <div class="col-sm-9">
                    <textarea id="alamat-admin" name="alamat_admin" class="form-control" rows="3" required><?= htmlspecialchars($data_lama['alamat_admin']); ?></textarea>
                </div>
            </div>

            <div class="row mb-3 align-items-center">
                <label for="nomor-telepon" class="col-sm-3 col-form-label fw-bold">Nomor Telepon</label>
                <div class="col-sm-9">
                    <input type="text" id="nomor-telepon" name="telepon_admin" value="<?= htmlspecialchars($data_lama['telepon_admin']); ?>" class="form-control" required>
                </div>
            </div>

            <div class="row mb-3 align-items-center">
                <label class="col-sm-3 col-form-label fw-bold">Jenis Kelamin</label>
                <div class="col-sm-9">
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="jenis_kelamin" id="jk_l" value="L" <?= ($data_lama['jenis_kelamin'] == 'L') ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="jk_l">Laki-laki</label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="jenis_kelamin" id="jk_p" value="P" <?= ($data_lama['jenis_kelamin'] == 'P') ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="jk_p">Perempuan</label>
                    </div>
                </div>
            </div>

            <div class="row mb-3 align-items-center">
                <label for="email" class="col-sm-3 col-form-label fw-bold">Email</label>
                <div class="col-sm-9">
                    <input type="email" id="email" name="email" value="<?= htmlspecialchars($data_lama['email']); ?>" class="form-control" required>
                </div>
            </div>

            <div class="row mb-3 align-items-center">
                <label for="password" class="col-sm-3 col-form-label fw-bold">Password Baru</label>
                <div class="col-sm-9">
                    <input type="password" id="password" name="password" class="form-control" placeholder="Kosongkan jika tidak ingin mengubah password">
                    <small class="text-muted">Biarkan kosong jika password tidak ingin diganti.</small>
                </div>
            </div>

            <div class="row mb-3 align-items-center">
                <label for="photo-admin" class="col-sm-3 col-form-label fw-bold">Photo Admin</label>
                <div class="col-sm-9">
                    <?php if (!empty($data_lama['path_photo_admin']) && file_exists(__DIR__ . '/../uploads/admin/' . basename($data_lama['path_photo_admin']))): ?>
                        <div class="mb-2">
                            <img src="../uploads/admin/<?= htmlspecialchars(basename($data_lama['path_photo_admin'])); ?>" alt="Foto Lama" class="rounded-circle" width="60" height="60" style="object-fit: cover;">
                            <span class="d-block text-muted small">Foto saat ini</span>
                        </div>
                    <?php endif; ?>
                    <input type="file" id="photo-admin" name="photo_admin" class="form-control" accept="image/*">
                    <small class="text-muted">Pilih file baru jika ingin mengganti foto.</small>
                </div>
            </div>

            <div class="row mb-3">
                <div class="col-sm-9 offset-sm-3">
                    <button type="submit" class="btn btn-warning text-white fw-bold">Update</button>
                    <button type="button" class="btn btn-secondary fw-bold" onclick="window.location.href='index.php?pages=admin';">Cancel</button>
                </div>
            </div>

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