<?php
declare(strict_types=1);

// Define o fuso horário para o PHP
date_default_timezone_set('America/Sao_Paulo');

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

header('Content-Type: application/json; charset=utf-8');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Não autenticado']);
    exit;
}

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

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

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 (datetime(\'now\', \'localtime\'))
        )'
    );
}

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", "localtime"))'
    );
    $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;
        }

        $select->execute([':key_name' => $key]);
        $exists = (bool)$select->fetchColumn();

        $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,
        ];

        if ($exists) {
            $update->execute($updateParams);
        } else {
            $insert->execute($insertParams);
        }
    }
}

function buildAppTextsPayload(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,
    ];
}

function rebuildAppTextsCache(PDO $db): array {
    $payload = buildAppTextsPayload($db);
    $cacheDir = __DIR__ . '/../cache';
    if (!is_dir($cacheDir)) {
        @mkdir($cacheDir, 0755, true);
    }
    @file_put_contents(
        $cacheDir . '/app_texts_cache.json',
        json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
    );
    return $payload;
}

try {
    $db = appTextsDb();
    ensureAppTextsTable($db);
    seedMissingAppTexts($db);

    $input = json_decode(file_get_contents('php://input'), true);
    if (!is_array($input)) {
        $input = [];
    }

    $action = (string)($input['action'] ?? 'view');

    if ($action === 'view') {
        $stmt = $db->query('SELECT * FROM app_texts ORDER BY category ASC, sort_order ASC, id ASC');
        echo json_encode(['success' => true, 'data' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
        exit;
    }

    if ($action === 'update') {
        $keyName = trim((string)($input['key_name'] ?? ''));
        $currentValue = trim((string)($input['current_value'] ?? ''));

        if ($keyName === '') {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Chave inválida']);
            exit;
        }

        $stmt = $db->prepare(
            'UPDATE app_texts
             SET current_value = :current_value, updated_at = datetime("now", "localtime")
             WHERE key_name = :key_name'
        );
        $stmt->execute([
            ':current_value' => $currentValue,
            ':key_name' => $keyName,
        ]);

        rebuildAppTextsCache($db);
        echo json_encode(['success' => true, 'message' => 'Texto atualizado com sucesso']);
        exit;
    }

    if ($action === 'restore_one') {
        $keyName = trim((string)($input['key_name'] ?? ''));
        if ($keyName === '') {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Chave inválida']);
            exit;
        }

        $stmt = $db->prepare(
            'UPDATE app_texts
             SET current_value = default_value, updated_at = datetime("now", "localtime")
             WHERE key_name = :key_name'
        );
        $stmt->execute([':key_name' => $keyName]);

        rebuildAppTextsCache($db);
        echo json_encode(['success' => true, 'message' => 'Texto restaurado para o padrão']);
        exit;
    }

    if ($action === 'restore_all') {
        $db->exec('UPDATE app_texts SET current_value = default_value, updated_at = datetime("now", "localtime")');
        rebuildAppTextsCache($db);
        echo json_encode(['success' => true, 'message' => 'Todos os textos voltaram para o padrão']);
        exit;
    }

    if ($action === 'rebuild_cache') {
        $payload = rebuildAppTextsCache($db);
        echo json_encode(['success' => true, 'message' => 'Cache reconstruído', 'version' => $payload['version']]);
        exit;
    }

    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Ação inválida']);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Erro: ' . $e->getMessage()]);
}