<?php
// admin/houses_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 = "Importador de Casas e Mapa";

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

$msg = '';
$insertedCount = 0;
$updatedCount = 0;

// --- PROCESSAMENTO ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    // A. UPLOAD IMAGEM
    if (!empty($_FILES['map_file']['name'])) {
        $target_dir = "../images/";
        if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);
        
        $target_file = $target_dir . "map.png"; 

        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $_FILES['map_file']['tmp_name']);
        
        if ($mime == 'image/png' || $mime == 'image/jpeg') {
            if (move_uploaded_file($_FILES['map_file']['tmp_name'], $target_file)) {
                $msg .= '<div class="alert alert-success shadow-sm border-0"><i class="fas fa-check-circle me-2"></i> Mapa (map.png) atualizado com sucesso!</div>';
            } else {
                $msg .= '<div class="alert alert-danger shadow-sm border-0">Erro ao mover o arquivo. Verifique as permissões da pasta images.</div>';
            }
        } else {
             $msg .= '<div class="alert alert-danger shadow-sm border-0">Formato inválido. Use apenas PNG ou JPG.</div>';
        }
    }
    
    // B. IMPORTAR XML
    if (!empty($_POST['xml_content'])) {
        libxml_use_internal_errors(true);
        $xml = simplexml_load_string($_POST['xml_content']);

        if ($xml === false) {
            $msg .= '<div class="alert alert-danger shadow-sm border-0"><i class="fas fa-bug me-2"></i> Erro no XML. Verifique a sintaxe ou se copiou corretamente.</div>';
        } else {
            $pdo->beginTransaction();
            try {
                // CORREÇÃO AQUI: Adicionado 'owner' com valor 0
                $stmt = $pdo->prepare("
                    INSERT INTO houses (id, owner, name, rent, town_id, size, beds, posx, posy, posz)
                    VALUES (:id, 0, :name, :rent, :townid, :size, :beds, :posx, :posy, :posz)
                    ON DUPLICATE KEY UPDATE
                    name = VALUES(name), rent = VALUES(rent), town_id = VALUES(town_id), size = VALUES(size),
                    posx = VALUES(posx), posy = VALUES(posy), posz = VALUES(posz), beds = VALUES(beds)
                ");

                foreach ($xml->house as $house) {
                    $data = [
                        ':id'       => (int)$house['houseid'],
                        ':name'     => (string)$house['name'],
                        ':rent'     => (int)$house['rent'],
                        ':townid'   => (int)$house['townid'],
                        ':size'     => (int)$house['size'],
                        ':beds'     => 0, 
                        ':posx'     => (int)$house['entryx'],
                        ':posy'     => (int)$house['entryy'],
                        ':posz'     => (int)$house['entryz'],
                    ];
                    
                    $stmt->execute($data);
                    
                    if ($stmt->rowCount() == 1) $insertedCount++;
                    else $updatedCount++;
                }

                $pdo->commit();
                $msg .= '<div class="alert alert-success shadow-sm border-0"><i class="fas fa-home me-2"></i> Sincronização concluída! <strong>'.$insertedCount.'</strong> novas casas, <strong>'.$updatedCount.'</strong> atualizadas.</div>';

            } catch (Exception $e) {
                $pdo->rollBack();
                $msg .= '<div class="alert alert-danger shadow-sm border-0">Erro SQL: ' . $e->getMessage() . '</div>';
            }
        }
    }
}

$mapImageExists = file_exists("../images/map.png");
?>

<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; }
    .form-control { background-color: #0f172a; border: 1px solid rgba(255,255,255,0.2); color: #fff; }
    .form-control:focus { background-color: #0f172a; color: #fff; border-color: #3b82f6; box-shadow: 0 0 0 0.25rem rgba(59, 130, 246, 0.25); }
    .form-control::placeholder { color: rgba(255,255,255,0.3); }
    
    /* Substituição do text-muted por text-white-50 para visibilidade */
    .text-white-50 { color: rgba(255,255,255,0.6) !important; }
    
    .btn-file { position: relative; overflow: hidden; }
    .code-area { font-family: 'Consolas', monospace; font-size: 0.85rem; color: #a5b4fc; background: #0b1120; border: 1px solid #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-tools text-primary me-2"></i>Importador Houses/Map</h2>
            <p class="text-white-50 m-0">Sincronize o site com o mapa do servidor.</p>
        </div>
    </div>

    <?php echo $msg; ?>

    <div class="alert alert-info bg-opacity-10 border-info text-info shadow-sm d-flex align-items-center mb-4">
        <i class="fas fa-info-circle fa-2x me-3"></i>
        <div>
            <strong>Importante:</strong> Use esta ferramenta sempre que atualizar o <code>houses.xml</code> ou o arquivo <code>.otbm</code> do servidor. Isso garante que a lista de casas e o minimapa estejam sincronizados.
        </div>
    </div>

    <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-map text-warning me-2"></i> 1. Imagem do Minimap
                </div>
                <div class="card-body">
                    <form method="POST" enctype="multipart/form-data">
                        <p class="text-white-50 small mb-3">
                            A imagem deve ser gerada pelo map editor e nomeada preferencialmente como <strong>map.png</strong>. 
                            Ela é usada no visualizador de casas.
                        </p>
                        
                        <div class="mb-4">
                            <label for="mapFile" class="form-label text-white fw-bold">Selecionar Arquivo</label>
                            <input class="form-control" type="file" id="mapFile" name="map_file" accept="image/png, image/jpeg" required>
                        </div>
                        
                        <div class="p-3 rounded bg-dark border border-secondary mb-3 d-flex align-items-center justify-content-between">
                            <span class="text-white-50">Status Atual:</span>
                            <?php if($mapImageExists): ?>
                                <span class="badge bg-success"><i class="fas fa-check me-1"></i> map.png Encontrado</span>
                            <?php else: ?>
                                <span class="badge bg-danger"><i class="fas fa-times me-1"></i> Ausente</span>
                            <?php endif; ?>
                        </div>

                        <button type="submit" class="btn btn-warning w-100 fw-bold text-dark">
                            <i class="fas fa-cloud-upload-alt me-2"></i> FAZER UPLOAD
                        </button>
                    </form>
                </div>
            </div>
        </div>
        
        <div class="col-lg-6">
            <div class="card shadow h-100 border-top border-4 border-success">
                <div class="card-header bg-transparent text-white fw-bold py-3">
                    <i class="fas fa-code text-success me-2"></i> 2. XML das Casas
                </div>
                <div class="card-body">
                    <form method="POST">
                        <p class="text-white-50 small mb-3">
                            Abra o arquivo <code>data/world/houses.xml</code> do seu servidor, copie todo o conteúdo e cole abaixo.
                        </p>
                        
                        <div class="mb-3">
                            <textarea name="xml_content" class="form-control code-area" rows="12" placeholder="Cole aqui: <houses> ... </houses>"></textarea>
                        </div>

                        <button type="submit" class="btn btn-success w-100 fw-bold">
                            <i class="fas fa-sync me-2"></i> SINCRONIZAR HOUSES
                        </button>
                    </form>
                </div>
            </div>
        </div>

    </div>
</div>

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