<?php
require_once '../config/database.php';
require_once '../includes/header.php';

// Cek apakah request adalah POST (untuk keamanan)
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    echo "<script>
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Metode request tidak valid'
        }).then(() => {
            window.location.href = 'index.php';
        });
    </script>";
    exit;
}

// Ambil ID GTK dari URL
$id_gtk = $_GET['id'] ?? 0;

if (!$id_gtk) {
    echo "<script>
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'ID GTK tidak valid'
        }).then(() => {
            window.location.href = 'index.php';
        });
    </script>";
    exit;
}

// Ambil data GTK untuk mendapatkan nama dan informasi foto
$query_gtk = "SELECT * FROM bind_gtk WHERE id_gtk = $id_gtk";
$result_gtk = mysqli_query($conn, $query_gtk);
$gtk = mysqli_fetch_assoc($result_gtk);

if (!$gtk) {
    echo "<script>
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Data GTK tidak ditemukan'
        }).then(() => {
            window.location.href = 'index.php';
        });
    </script>";
    exit;
}

// Hapus foto jika ada
if ($gtk['foto']) {
    $target_file = "../uploads/foto-gtk/" . $gtk['foto'];
    if (file_exists($target_file)) {
        unlink($target_file);
    }
}

// Query untuk menghapus data
$query_delete = "DELETE FROM bind_gtk WHERE id_gtk = $id_gtk";
$result_delete = mysqli_query($conn, $query_delete);

if ($result_delete) {
    echo "<script>
        Swal.fire({
            icon: 'success',
            title: 'Berhasil',
            text: 'Data GTK " . addslashes($gtk['nama']) . " berhasil dihapus'
        }).then(() => {
            window.location.href = 'index.php';
        });
    </script>";
} else {
    echo "<script>
        Swal.fire({
            icon: 'error',
            title: 'Gagal',
            text: 'Terjadi kesalahan: " . addslashes(mysqli_error($conn)) . "'
        }).then(() => {
            window.location.href = 'index.php';
        });
    </script>";
}

require_once '../includes/footer.php';
?>