<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = trim($_POST['name']);
    $surname = trim($_POST['surname']);
    $company = trim($_POST['company']);
    $wish = trim($_POST['wish']);
    $letter = trim($_POST['letter']);
    $special_letters = isset($_POST['special_letters']) ? $_POST['special_letters'] : [];

    if (empty($name) || empty($surname) || empty($company) || empty($wish)) {
        die("Bütün xanaları doldurmaq mütləqdir.");
    }

    $file = 'data.json';
    $data = [];

    if (file_exists($file)) {
        $json_data = file_get_contents($file);
        $data = json_decode($json_data, true);
    }

    foreach ($data as $entry) {
        if (strtolower($entry['name']) === strtolower($name) && strtolower($entry['surname']) === strtolower($surname)) {
            die("Bu ad və soyad ilə artıq qeydiyyat mövcuddur. <a href='index.html'>Geri qayıt</a>");
        }
    }

    $new_entry = [
        'name' => $name,
        'surname' => $surname,
        'company' => $company,
        'wish' => $wish,
        'letter' => $letter,
        'special_letters' => $special_letters
    ];

    $data[] = $new_entry;

    file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

    header("Location: list.php");
    exit();
}
?>