<?php
// Обработка CRUD для таблицы languages
header('Content-Type: application/json; charset=utf-8');
ini_set('display_errors',1);
error_reporting(E_ALL);

require '/home/jwfnsshf/v.centrx.eu/config/db.php';

$method = $_SERVER['REQUEST_METHOD'];

try {
    if ($method === 'GET') {
        $langs = $pdo->query("SELECT code,name,flag_icon FROM languages ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($langs, JSON_UNESCAPED_UNICODE);
        exit;
    }
    if ($method === 'POST') {
        // ожидаем JSON {"code":"es","name":"Español","flag_icon":"/flags/es.png"}
        $data = json_decode(file_get_contents('php://input'), true);
        $stmt = $pdo->prepare("INSERT INTO languages (code,name,flag_icon) VALUES (:code,:name,:icon)");
        $stmt->execute(['code'=>$data['code'],'name'=>$data['name'],'icon'=>$data['flag_icon']]);
        http_response_code(201);
        echo json_encode(['success'=>true], JSON_UNESCAPED_UNICODE);
        exit;
    }
    if ($method === 'PUT' && isset($_GET['code'])) {
        $code = $_GET['code'];
        $data = json_decode(file_get_contents('php://input'), true);
        $stmt = $pdo->prepare("UPDATE languages SET name=:name, flag_icon=:icon WHERE code=:code");
        $stmt->execute(['name'=>$data['name'],'icon'=>$data['flag_icon'],'code'=>$code]);
        echo json_encode(['success'=>true], JSON_UNESCAPED_UNICODE);
        exit;
    }
    if ($method === 'DELETE' && isset($_GET['code'])) {
        $stmt = $pdo->prepare("DELETE FROM languages WHERE code=:code");
        $stmt->execute(['code'=>$_GET['code']]);
        http_response_code(204);
        exit;
    }
    http_response_code(405);
    echo json_encode(['error'=>'Method not allowed']);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error'=>$e->getMessage()], JSON_UNESCAPED_UNICODE);
}
