<?php
// admin/config_importer.php
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();
require '../includes/conexao.php';

// SEGURANÇA
if (!isset($_SESSION['account_id'])) { header("Location: ../login.php"); exit; }
$stmt = $pdo->prepare("SELECT page_access FROM accounts WHERE id = ?");
$stmt->execute([$_SESSION['account_id']]);
$acc = $stmt->fetch();
if (!$acc || $acc['page_access'] < 3) die("Acesso Negado.");

$page_title = "Importar Config.lua";

if(file_exists('../includes/admin_header.php')) include '../includes/admin_header.php';
else include '../includes/header.php';

$msg = '';

// PROCESSAR LUA
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['lua_content'])) {
    $content = $_POST['lua_content'];
    $count = 0;
    
    $allowList = [
        'serverName', 'ip', 'motd', 'worldType', 'maxPlayers', 
        'housePriceEachSQM', 'protectionLevel', 'loginProtocolPort', 'gameProtocolPort',
        'rateExp', 'rateSkill', 'rateLoot', 'rateMagic', 'rateSpawn'
    ];

    if (preg_match_all('/^\s*([a-zA-Z0-9_]+)\s*=\s*(.*)/m', $content, $matches, PREG_SET_ORDER)) {
        $pdo->beginTransaction();
        try {
            foreach ($matches as $match) {
                $key = trim($match[1]);
                $cleanValue = trim(explode('--', $match[2])[0]); // Remove comentários
                $cleanValue = str_replace(['"', "'"], '', $cleanValue); // Remove aspas

                if (in_array($key, $allowList)) {
                    $stmt = $pdo->prepare("INSERT INTO server_config (config, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = ?");
                    $stmt->execute([$key, $cleanValue, $cleanValue]);
                    $count++;
                }
            }
            $pdo->commit();
            $msg = '<div class="alert alert-success shadow-sm border-0"><i class="fas fa-check-circle me-2"></i> <strong>'.$count.'</strong> configurações atualizadas!</div>';
        } catch (Exception $e) {
            $pdo->rollBack();
            $msg = '<div class="alert alert-danger shadow-sm border-0">Erro SQL: ' . $e->getMessage() . '</div>';
        }
    } else {
        $msg = '<div class="alert alert-warning shadow-sm border-0">Nenhuma configuração válida encontrada.</div>';
    }
}

$currentConfig = $pdo->query("SELECT * FROM server_config")->fetchAll(PDO::FETCH_KEY_PAIR);
?>

<style>
    /* Admin Dark Theme */
    body { background-color: #0f172a; color: #f8fafc; font-family: 'Poppins', sans-serif; }
    .card { background-color: #1e293b; border: 1px solid rgba(255,255,255,0.1); color: #fff; border-radius: 12px; }
    .code-editor { background-color: #0b1120; color: #a5b4fc; font-family: 'Consolas', monospace; font-size: 0.85rem; border: 1px solid rgba(255,255,255,0.1); }
    .code-editor:focus { background-color: #0b1120; color: #e0e7ff; border-color: #3b82f6; }
    .table { color: #cbd5e1; }
    .table tbody tr:hover { background-color: rgba(255,255,255,0.02); }
    .table thead th { background-color: #0f172a; border-bottom: 2px solid #334155; color: #94a3b8; }
</style>

<div class="container my-5">
    
    <div class="d-flex justify-content-between align-items-center mb-4 border-bottom border-secondary pb-3">
        <div>
            <h2 class="fw-bold text-white mb-0"><i class="fas fa-file-code text-warning me-2"></i>Sincronização Config.lua</h2>
            <p class="text-white-50 m-0">Atualize rates, IP e nome do servidor facilmente.</p>
        </div>
    </div>

    <?php echo $msg; ?>

    <div class="row g-4">
        
        <div class="col-lg-6">
            <div class="card shadow h-100 border-top border-4 border-warning">
                <div class="card-header bg-transparent text-white fw-bold py-3">
                    <i class="fas fa-paste me-2 text-warning"></i> Colar Código LUA
                </div>
                <div class="card-body">
                    <form method="POST">
                        <p class="text-white-50 small mb-3">Copie todo o conteúdo do seu <code>config.lua</code> e cole abaixo.</p>
                        <textarea name="lua_content" class="form-control code-editor mb-3" rows="18" placeholder="-- Config.lua content..."></textarea>
                        <button type="submit" class="btn btn-warning w-100 fw-bold text-dark"><i class="fas fa-sync-alt me-2"></i> PROCESSAR E SALVAR</button>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-lg-6">
            <div class="card shadow h-100">
                <div class="card-header bg-dark text-white fw-bold py-3">
                    <i class="fas fa-database me-2 text-info"></i> Dados Atuais no Site
                </div>
                <div class="table-responsive">
                    <table class="table table-hover mb-0 align-middle">
                        <thead>
                            <tr>
                                <th class="ps-3">Chave</th>
                                <th>Valor</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $keys = [
                                'serverName' => 'Nome', 'ip' => 'IP', 'rateExp' => 'Exp Rate', 
                                'rateLoot' => 'Loot Rate', 'rateSkill' => 'Skill Rate', 
                                'worldType' => 'PVP Type', 'maxPlayers' => 'Slots'
                            ];
                            foreach($keys as $k => $label): 
                                $val = $currentConfig[$k] ?? '<span class="text-danger small">N/A</span>';
                            ?>
                            <tr>
                                <td class="ps-3">
                                    <strong class="text-white"><?php echo $label; ?></strong>
                                    <div class="small text-white-50 font-monospace"><?php echo $k; ?></div>
                                </td>
                                <td class="text-info fw-bold"><?php echo $val; ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <div class="card-footer bg-transparent border-top border-secondary text-white-50 small">
                    Estes dados são exibidos na Home e Downloads.
                </div>
            </div>
        </div>

    </div>
</div>

<?php if(file_exists('../includes/admin_footer.php')) include '../includes/admin_footer.php'; else include '../includes/footer.php'; ?>