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

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

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

$page_title = "Importar Items.xml";

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

$msg = '';

// PROCESSAR UPLOAD/COLA DE XML
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['xml_content'])) {
    $xml_content = trim($_POST['xml_content']);
    $count = 0;

    if (empty($xml_content)) {
        $msg = '<div class="alert alert-warning shadow-sm border-0">Cole o conteúdo do items.xml antes de importar.</div>';
    } else {
        try {
            $xml = simplexml_load_string($xml_content);
            if ($xml === false) {
                $msg = '<div class="alert alert-danger shadow-sm border-0">Erro ao analisar o XML. Verifique o formato do arquivo.</div>';
            } else {
                $pdo->beginTransaction();
                $stmt = $pdo->prepare("INSERT INTO items_data (item_id, name, image_url) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE name = VALUES(name), image_url = VALUES(image_url)");
                
                foreach ($xml->item as $item) {
                    $item_id = (int)$item['id'];
                    $name = (string)$item['name'];
                    
                    if ($item_id > 0 && !empty($name)) {
                        // Simulação de URL de imagem (ajuste conforme seu servidor de imagens)
                        $image_url = "images/items/{$item_id}.gif"; 
                        $stmt->execute([$item_id, $name, $image_url]);
                        $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> itens importados/atualizados com sucesso!</div>';
            }
        } catch (Exception $e) {
            $pdo->rollBack();
            $msg = '<div class="alert alert-danger shadow-sm border-0">Erro: ' . $e->getMessage() . '</div>';
        }
    }
}

// CONTAGEM DE ITENS ATUAIS
$total_items = $pdo->query("SELECT COUNT(*) FROM items_data")->fetchColumn();
?>

<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); }
    .form-control { background-color: #0b1120; color: #f8fafc; border-color: #334155; }
</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-upload text-warning me-2"></i>Importar `items.xml`</h2>
            <p class="text-white-50 m-0">Use para atualizar a base de dados de nomes de itens para o Bazaar de Personagens.</p>
        </div>
    </div>

    <?php echo $msg; ?>

    <div class="card shadow p-4 border-top border-4 border-warning">
        <form method="POST">
            <div class="alert alert-info small">
                <i class="fas fa-info-circle me-1"></i> Atualmente, há <strong><?php echo $total_items; ?></strong> itens na base de dados.
            </div>
            
            <p class="text-white-50 small mb-3">Copie e cole o conteúdo completo do seu arquivo `data/items/items.xml` abaixo. O sistema irá extrair o `item_id` e o `name` e atualizar o banco de dados. Use a imagem de ID como URL base: `/images/items/{item_id}.gif`.</p>
            
            <textarea name="xml_content" class="form-control code-editor mb-3" rows="18" placeholder="&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;&#10;&lt;items&gt;&#10;    &lt;item id=&quot;100&quot; name=&quot;Great Ball&quot; /&gt;&#10;    ...&#10;&lt;/items&gt;"></textarea>
            
            <button type="submit" class="btn btn-warning w-100 fw-bold text-dark">
                <i class="fas fa-code me-2"></i> IMPORTAR DADOS DOS ITENS
            </button>
        </form>
    </div>
</div>

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