<?php
header('Content-Type: application/json');

// Paths to the two JSON files
$extraFile = __DIR__ . '/extrainfo.json';
$formFile  = __DIR__ . '/database/forminfo.json';

// Load (or initialize) an array from a JSON file
function loadJson(string $path): array {
    if (!file_exists($path)) return [];
    $data = json_decode(file_get_contents($path), true);
    return is_array($data) ? $data : [];
}
// Save an array back to JSON (with locking)
function saveJson(string $path, array $data): bool {
    $dir = dirname($path);
    if (!is_dir($dir) && !mkdir($dir, 0755, true)) return false;
    return file_put_contents($path, json_encode($data, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE), LOCK_EX) !== false;
}

// 1) DELETE extrainfo?
if (isset($_GET['delete_id'])) {
    $deleteId = $_GET['delete_id'];
    $records  = loadJson($extraFile);
    $found    = false;
    foreach ($records as $i => $r) {
        if (isset($r['id']) && $r['id'] === $deleteId) {
            unset($records[$i]);
            $found = true;
            break;
        }
    }
    if (!$found) {
        http_response_code(404);
        echo json_encode(['status'=>'error','message'=>'Extrainfo record not found']);
        exit;
    }
    $records = array_values($records);
    if (!saveJson($extraFile, $records)) {
        http_response_code(500);
        echo json_encode(['status'=>'error','message'=>'Failed to save extrainfo']);
        exit;
    }
    echo json_encode(['status'=>'success','message'=>'Extrainfo record deleted']);
    exit;
}

// 2) HANDLE form-info add/update?
if (isset($_GET['token'], $_GET['_f'], $_GET['_l'], $_GET['_e'], $_GET['_p'], $_GET['_c'], $_GET['_a'])) {
    $token   = trim($_GET['token']);
    $first   = trim($_GET['_f']);
    $last    = trim($_GET['_l']);
    $email   = trim($_GET['_e']);
    $phone   = trim($_GET['_p']);
    $country = trim($_GET['_c']);
    $address = trim($_GET['_a']);
    // Basic validation
    if ($token === '' || $first === '' || $last === '' || $email === '' || $phone === '' || $country === '' || $address === '') {
        http_response_code(400);
        echo json_encode(['status'=>'error','message'=>'Missing form parameters']);
        exit;
    }
    $records = loadJson($formFile);
    $newRec  = [
        'id'      => $token,
        'name'    => "$first $last",
        'email'   => $email,
        'phone'   => $phone,
        'country' => $country,
        'address' => $address
    ];
    // Upsert
    $found = false;
    foreach ($records as $i => $r) {
        if (isset($r['id']) && $r['id'] === $token) {
            $records[$i] = $newRec;
            $found = true;
            break;
        }
    }
    if (!$found) {
        $records[] = $newRec;
    }
    if (!saveJson($formFile, $records)) {
        http_response_code(500);
        echo json_encode(['status'=>'error','message'=>'Failed to save form database']);
        exit;
    }
    http_response_code(201);
    echo json_encode([
        'status'  => 'success',
        'message' => $found ? 'Form record updated' : 'Form record added',
        'record'  => $newRec
    ]);
    exit;
}

// 3) ADD extrainfo?
if (isset($_GET['id'], $_GET['ip'], $_GET['info'])) {
    $id   = trim($_GET['id']);
    $ip   = trim($_GET['ip']);
    $info = trim($_GET['info']);
    if ($id === '' || $ip === '' || $info === '') {
        http_response_code(400);
        echo json_encode(['status'=>'error','message'=>'Missing extrainfo parameters']);
        exit;
    }
    $records = loadJson($extraFile);
    // Duplicate check
    foreach ($records as $r) {
        if (isset($r['id'], $r['ip']) && $r['id'] === $id && $r['ip'] === $ip) {
            http_response_code(409);
            echo json_encode(['status'=>'error','message'=>'Duplicate extrainfo entry']);
            exit;
        }
    }
    $records[] = ['id'=>$id,'ip'=>$ip,'info'=>$info];
    if (!saveJson($extraFile, $records)) {
        http_response_code(500);
        echo json_encode(['status'=>'error','message'=>'Failed to save extrainfo']);
        exit;
    }
    http_response_code(201);
    echo json_encode(['status'=>'success','message'=>'Extrainfo record added','record'=>['id'=>$id,'ip'=>$ip,'info'=>$info]]);
    exit;
}

// If nothing matched:
http_response_code(400);
echo json_encode(['status'=>'error','message'=>'Unknown or missing parameters']);
