<?php
session_start();

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

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['id'])) {
    $id = (int)$_POST['id'];
    $nama = $_POST['nama'];
    $visi = $_POST['visi'];
    $misi_string = $_POST['misi'];

    // Ubah string misi menjadi array, memisahkan setiap baris
    $misi = explode("\n", $misi_string);
    // Hapus spasi di awal dan akhir setiap item misi
    $misi = array_map('trim', $misi);
    // Hapus item yang kosong dari array
    $misi = array_filter($misi);

    $kandidat_data = json_decode(file_get_contents('../data/kandidat.json'), true);
    $found_key = null;

    foreach ($kandidat_data as $key => $kandidat) {
        if ($kandidat['id'] === $id) {
            $found_key = $key;
            break;
        }
    }

    if ($found_key !== null) {
        // Proses upload foto baru jika ada
        if (isset($_FILES['foto']) && $_FILES['foto']['error'] == 0) {
            $target_dir = "../public/assets/images/";
            $file_extension = pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION);
            $new_file_name = uniqid() . '.' . $file_extension;
            $target_file = $target_dir . $new_file_name;

            // Hapus foto lama jika ada
            $old_photo = $kandidat_data[$found_key]['foto'];
            if (!empty($old_photo) && file_exists($target_dir . $old_photo)) {
                unlink($target_dir . $old_photo);
            }

            // Pindahkan foto baru
            if (move_uploaded_file($_FILES['foto']['tmp_name'], $target_file)) {
                $kandidat_data[$found_key]['foto'] = $new_file_name;
            }
        }

        // Update data lainnya (Visi dan Misi)
        $kandidat_data[$found_key]['nama'] = $nama;
        $kandidat_data[$found_key]['visi'] = $visi;
        $kandidat_data[$found_key]['misi'] = $misi;

        file_put_contents('../data/kandidat.json', json_encode($kandidat_data, JSON_PRETTY_PRINT));
        header('Location: ../public/admin_manage_kandidat.php?status=success_update');
        exit;
    } else {
        echo "Gagal mengupdate data. Kandidat tidak ditemukan.";
    }
}
