<?php
// admin/update_language_flag.php

require_once __DIR__ . '/../includes/session_check.php';
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/db.php';

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

// Solo para administradores
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    echo json_encode(['success' => false, 'error' => 'Acceso denegado.']);
    exit;
}

// Verificar que la solicitud sea AJAX y POST
if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '') !== 'xmlhttprequest' || $_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Solicitud no válida.']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);

$langId = $data['id'] ?? null;
$flagEmoji = $data['flag_emoji'] ?? '';

if ($langId === null) {
    echo json_encode(['success' => false, 'error' => 'ID de idioma no proporcionado.']);
    exit;
}

try {
    $stmt = $pdo->prepare("UPDATE supported_languages SET flag_emoji = ? WHERE id = ?");
    $stmt->execute([$flagEmoji, $langId]);

    echo json_encode(['success' => true]);

} catch (PDOException $e) {
    error_log("Error en update_language_flag.php: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Error en la base de datos.']);
}
?>
