<?php
session_start();

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

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

    // Convert the mission string into an array, splitting by new lines
    $misi = explode("\n", $misi_string);
    $misi = array_map('trim', $misi); // Remove whitespace
    $misi = array_filter($misi); // Remove empty items

    $foto = $_FILES['foto'];

    // File upload validation and processing
    $target_dir = "../public/assets/images/";
    $file_extension = pathinfo($foto["name"], PATHINFO_EXTENSION);
    $new_file_name = uniqid() . '.' . $file_extension;
    $target_file = $target_dir . $new_file_name;
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    // Check if the file is a real image
    $check = getimagesize($foto["tmp_name"]);
    if ($check === false) {
        echo "File bukan gambar.";
        $uploadOk = 0;
    }

    // Check if the file already exists
    if (file_exists($target_file)) {
        echo "Maaf, file sudah ada.";
        $uploadOk = 0;
    }

    // Restrict file size
    if ($foto["size"] > 500000) { // 500KB
        echo "Maaf, ukuran file terlalu besar.";
        $uploadOk = 0;
    }

    // Allow certain file formats
    if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
        echo "Maaf, hanya format JPG, JPEG, & PNG yang diperbolehkan.";
        $uploadOk = 0;
    }

    // Attempt to upload the file
    if ($uploadOk == 0) {
        echo "Maaf, file Anda tidak terunggah.";
    } else {
        if (move_uploaded_file($foto["tmp_name"], $target_file)) {
            // Read candidate data from the JSON file
            $kandidat_data = json_decode(file_get_contents('../data/kandidat.json'), true);
            $last_id = 0;
            if (!empty($kandidat_data)) {
                $last_id = end($kandidat_data)['id'];
            }
            $new_id = $last_id + 1;

            // Create new candidate data
            $new_kandidat = [
                "id" => $new_id,
                "nama" => $nama,
                "visi" => $visi,
                "misi" => $misi,
                "foto" => $new_file_name
            ];

            // Add the new candidate to the array
            $kandidat_data[] = $new_kandidat;
            file_put_contents('../data/kandidat.json', json_encode($kandidat_data, JSON_PRETTY_PRINT));

            // Add the new candidate to voting results with a 0 vote count
            $hasil_data = json_decode(file_get_contents('../data/hasil.json'), true);
            $hasil_data[$new_id] = 0;
            file_put_contents('../data/hasil.json', json_encode($hasil_data, JSON_PRETTY_PRINT));

            header('Location: ../public/admin_view.php?status=success_add');
            exit;
        } else {
            echo "Maaf, terjadi error saat mengunggah file Anda.";
        }
    }
} else {
    header('Location: ../public/admin_add_kandidat.php');
    exit;
}
