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

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

$id_admin = $_GET['id'] ?? $_GET['id_admin'] ?? '';
$id_user  = $_GET['id_user'] ?? '';

if (!empty($id_admin)) {
    $id_admin = mysqli_real_escape_string($koneksi, $id_admin);
    
    // Ambil data foto & id_user
    $q_foto = mysqli_query($koneksi, "SELECT path_photo_admin, id_user FROM tbl_admin WHERE id_admin = '$id_admin'");
    $d_foto = mysqli_fetch_assoc($q_foto);

    if ($d_foto) {
        if (empty($id_user)) {
            $id_user = $d_foto['id_user'];
        }

        // Hapus file foto fisik
        $file_foto = trim($d_foto['path_photo_admin'] ?? '');
        if (!empty($file_foto)) {
            $path_target = __DIR__ . '/../uploads/admin/' . basename($file_foto);
            if (file_exists($path_target)) {
                unlink($path_target);
            }
        }
    }

    // Hapus dari tbl_admin & tbl_users
    $del_admin = mysqli_query($koneksi, "DELETE FROM tbl_admin WHERE id_admin = '$id_admin'");

    if (!empty($id_user)) {
        $id_user = mysqli_real_escape_string($koneksi, $id_user);
        mysqli_query($koneksi, "DELETE FROM tbl_users WHERE id_user = '$id_user'");
    }

    if ($del_admin) {
        echo "<script>alert('Data admin berhasil dihapus!'); window.location.href = 'index.php?pages=admin';</script>";
        exit;
    } else {
        echo "<script>alert('Gagal menghapus data admin'); window.location.href = 'index.php?pages=admin';</script>";
        exit;
    }
} else {
    echo "<script>alert('ID Admin tidak ditemukan!'); window.location.href = 'index.php?pages=admin';</script>";
    exit;
}
?>