<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/bootstrap.php';

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: public, max-age=300');

function appTextsDb(): PDO {
    $db = new PDO('sqlite:' . __DIR__ . '/../ibo_panel.db');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $db;
}

function appTextsDefaults(): array {
    return require __DIR__ . '/../includes/app_texts_defaults.php';
}

function ensureAppTextsTable(PDO $db): void {
    $db->exec(
        'CREATE TABLE IF NOT EXISTS app_texts (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            key_name TEXT NOT NULL UNIQUE,
            label TEXT NOT NULL,
            category TEXT NOT NULL DEFAULT "geral",
            default_value TEXT NOT NULL DEFAULT "",
            current_value TEXT NOT NULL DEFAULT "",
            sort_order INTEGER NOT NULL DEFAULT 0,
            updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
        )'
    );
}

function seedMissingAppTexts(PDO $db): void {
    $defaults = appTextsDefaults();
    $select = $db->prepare('SELECT id FROM app_texts WHERE key_name = :key_name LIMIT 1');
    $insert = $db->prepare(
        'INSERT INTO app_texts (key_name, label, category, default_value, current_value, sort_order, updated_at)
         VALUES (:key_name, :label, :category, :default_value, :current_value, :sort_order, datetime("now"))'
    );
    $update = $db->prepare(
        'UPDATE app_texts
         SET label = :label, category = :category, default_value = :default_value, sort_order = :sort_order
         WHERE key_name = :key_name'
    );

    foreach ($defaults as $index => $row) {
        $key = (string)($row['key'] ?? '');
        if ($key === '') {
            continue;
        }
        $insertParams = [
            ':key_name' => $key,
            ':label' => (string)($row['label'] ?? $key),
            ':category' => (string)($row['category'] ?? 'geral'),
            ':default_value' => (string)($row['default'] ?? ''),
            ':current_value' => (string)($row['default'] ?? ''),
            ':sort_order' => $index + 1,
        ];
        $updateParams = [
            ':key_name' => $key,
            ':label' => (string)($row['label'] ?? $key),
            ':category' => (string)($row['category'] ?? 'geral'),
            ':default_value' => (string)($row['default'] ?? ''),
            ':sort_order' => $index + 1,
        ];
        $select->execute([':key_name' => $key]);
        if ($select->fetchColumn()) {
            $update->execute($updateParams);
        } else {
            $insert->execute($insertParams);
        }
    }
}

function buildPayload(PDO $db): array {
    $stmt = $db->query('SELECT key_name, current_value, default_value, updated_at FROM app_texts ORDER BY sort_order ASC, id ASC');
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $texts = [];
    $lastUpdated = '1970-01-01 00:00:00';
    foreach ($rows as $row) {
        $current = trim((string)($row['current_value'] ?? ''));
        $default = (string)($row['default_value'] ?? '');
        $texts[(string)$row['key_name']] = $current !== '' ? $current : $default;
        if (!empty($row['updated_at']) && strcmp((string)$row['updated_at'], $lastUpdated) > 0) {
            $lastUpdated = (string)$row['updated_at'];
        }
    }

    return [
        'success' => true,
        'version' => crc32(json_encode($texts, JSON_UNESCAPED_UNICODE)),
        'updated_at' => $lastUpdated,
        'texts' => $texts,
    ];
}

try {
    $cacheFile = __DIR__ . '/../cache/app_texts_cache.json';
    if (is_file($cacheFile)) {
        $cached = @file_get_contents($cacheFile);
        if ($cached !== false && $cached !== '') {
            echo $cached;
            exit;
        }
    }

    $db = appTextsDb();
    ensureAppTextsTable($db);
    seedMissingAppTexts($db);
    $payload = buildPayload($db);

    $cacheDir = __DIR__ . '/../cache';
    if (!is_dir($cacheDir)) {
        @mkdir($cacheDir, 0755, true);
    }
    @file_put_contents($cacheFile, json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));

    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Erro ao carregar textos']);
}
