<?php
require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/../helpers.php';

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

$db = db();
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true) ?? $_POST;
    $action = $input['action'] ?? '';

    if ($action === 'add' || $action === 'add_city') {
        $name_en = $input['name_en'] ?? $input['name'] ?? '';
        $name_ar = $input['name_ar'] ?? $input['name'] ?? '';
        
        if ($name_en && $name_ar) {
            try {
                $stmt = $db->prepare("INSERT INTO cities (name_en, name_ar) VALUES (?, ?)");
                $stmt->execute([$name_en, $name_ar]);
                $id = $db->lastInsertId();
                
                $lang = $_SESSION['lang'] ?? 'en';
                
                echo json_encode([
                    'success' => true,
                    'id' => $id,
                    'name_en' => $name_en,
                    'name_ar' => $name_ar,
                    'city' => [
                        'id' => $id,
                        'name' => ($lang === 'ar' && !empty($name_ar)) ? $name_ar : $name_en
                    ]
                ]);
            } catch (Exception $e) {
                echo json_encode(['success' => false, 'error' => $e->getMessage()]);
            }
        } else {
            echo json_encode(['success' => false, 'error' => 'Missing fields']);
        }
    } else {
        echo json_encode(['success' => false, 'error' => 'Invalid action']);
    }
    exit;
}

echo json_encode(['success' => false, 'error' => 'Invalid request method']);
