<?php
session_start();

if (!isset($_SESSION['admin_logged_in'])) {
    header('Location: ../public/admin_login.php');
    exit;
}

if (isset($_GET['id'])) {
    $id_to_delete = (int)$_GET['id'];
    $kandidat_data = json_decode(file_get_contents('../data/kandidat.json'), true);
    $hasil_data = json_decode(file_get_contents('../data/hasil.json'), true);

    $found_key = null;
    foreach ($kandidat_data as $key => $kandidat) {
        if ($kandidat['id'] === $id_to_delete) {
            $found_key = $key;
            // Hapus file foto
            $photo_to_delete = $kandidat['foto'];
            if (!empty($photo_to_delete) && file_exists('../public/assets/images/' . $photo_to_delete)) {
                unlink('../public/assets/images/' . $photo_to_delete);
            }
            break;
        }
    }

    if ($found_key !== null) {
        // Hapus kandidat dari daftar kandidat
        unset($kandidat_data[$found_key]);
        file_put_contents('../data/kandidat.json', json_encode(array_values($kandidat_data), JSON_PRETTY_PRINT));

        // Hapus suara kandidat dari hasil.json
        if (isset($hasil_data[$id_to_delete])) {
            unset($hasil_data[$id_to_delete]);
            file_put_contents('../data/hasil.json', json_encode($hasil_data, JSON_PRETTY_PRINT));
        }

        header('Location: ../public/admin_manage_kandidat.php?status=success_delete');
        exit;
    } else {
        echo "Gagal menghapus data. Kandidat tidak ditemukan.";
    }
} else {
    header('Location: ../public/admin_manage_kandidat.php');
    exit;
}
