<?php
// ════════════════════════════════════════════════════════
// LANGUAGES API
// Place in: Triangle_Tree_Life_Number/api/data/languages.php
// ════════════════════════════════════════════════════════

error_reporting(E_ALL);
ini_set('display_errors', 0);

// Remove any existing headers first
if (function_exists('header_remove')) {
    header_remove('Access-Control-Allow-Methods');
}

// Force CORS headers
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

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

// Verify JWT token
$headers = getallheaders();
$authHeader = $headers['Authorization'] ?? '';

if (empty($authHeader) || !preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

$token = $matches[1];
$jwtSecret = getenv('JWT_SECRET') ?: 'default_secret_change_this';
$payload = verifyJWT($token, $jwtSecret);

if (!$payload) {
    http_response_code(401);
    echo json_encode(['error' => 'Invalid token']);
    exit();
}

$method = $_SERVER['REQUEST_METHOD'];

try {
    if ($method === 'GET') {
        // ══════════════════════════════════════
        // GET - Load all language strings
        // Returns { en: {key:value,...}, ms: {...}, zh: {...} }
        // ══════════════════════════════════════
        $stmt = $pdo->query("SELECT lang, lang_key, lang_value FROM language_strings");
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $result = [];
        foreach ($rows as $r) {
            $val = json_decode($r['lang_value'], true);
            // If the stored value is valid JSON use the decoded form, else raw text
            $result[$r['lang']][$r['lang_key']] =
                ($val !== null && json_last_error() === JSON_ERROR_NONE)
                ? $val
                : $r['lang_value'];
        }

        echo json_encode($result);

    } elseif ($method === 'POST') {
        // ══════════════════════════════════════
        // POST - Save language strings
        // Expects { en: {key:value,...}, ms: {...}, zh: {...} }
        // ══════════════════════════════════════
        $input = json_decode(file_get_contents('php://input'), true);

        if (!is_array($input)) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid JSON payload']);
            exit();
        }

        $pdo->beginTransaction();

        try {
            $stmt = $pdo->prepare("
                INSERT INTO language_strings (lang, lang_key, lang_value)
                VALUES (?, ?, ?)
                ON DUPLICATE KEY UPDATE lang_value = VALUES(lang_value)
            ");

            $count = 0;
            foreach ($input as $lang => $keys) {
                if (!is_array($keys)) continue;
                foreach ($keys as $key => $value) {
                    $stored = is_array($value)
                        ? json_encode($value, JSON_UNESCAPED_UNICODE)
                        : (string)$value;
                    $stmt->execute([$lang, $key, $stored]);
                    $count++;
                }
            }

            $pdo->commit();
            echo json_encode([
                'success' => true,
                'message' => 'Languages saved to database',
                'saved'   => $count
            ]);

        } catch (Exception $e) {
            $pdo->rollBack();
            http_response_code(500);
            echo json_encode([
                'error'   => 'Save failed',
                'message' => $e->getMessage()
            ]);
        }

    } else {
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error'   => 'Server error',
        'message' => $e->getMessage()
    ]);
}
?>
