<?php
// ==========================================================
// 1. CONFIGURAÇÕES E SISTEMA
// ==========================================================
ini_set('display_errors', 1);
error_reporting(E_ALL);

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

// Configurações Básicas
$houseConfig = [
    // 'image_path' e 'default_image' não são mais necessários com o novo sistema CSS
    'towns' => [
        1 => 'Saffron', 2 => 'Cerulean', 3 => 'Lavender', 4 => 'Fuchsia', 5 => 'Celadon', 
        6 => 'Viridian', 7 => 'Vermilion', 8 => 'Pewter', 10 => 'Cinnabar', 12 => 'Ilha',
        21 => 'Castelia', 22 => 'Goldenrod', 24 => 'Violet', 29 => 'Cianwood'
    ]
];

// SEO
$serverName = "Pokemon Relics";
$page_title = "Catálogo de Casas - $serverName";
$metaDesc   = "Explore o mapa de $serverName. Veja detalhes das casas, localização GPS e proprietários.";

// ==========================================================
// 2. FRONTEND: FILTROS E PAGINAÇÃO
// ==========================================================
$page   = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$town   = isset($_GET['town']) ? $_GET['town'] : 'all';
$status = isset($_GET['status']) ? $_GET['status'] : 'all';
$limit  = 12; 
$offset = ($page - 1) * $limit;

// Construção da Query
$where = ["h.id > 0"]; 
$params = [];

// Filtro Cidade
if ($town !== 'all') {
    $where[] = "h.town_id = ?";
    $params[] = $town;
}

// Filtro Status
if ($status === 'vacant') {
    $where[] = "h.owner = 0";
} elseif ($status === 'occupied') {
    $where[] = "h.owner > 0";
}

$whereSQL = implode(" AND ", $where);

// Contagem
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM houses h WHERE $whereSQL");
$countStmt->execute($params);
$totalHouses = $countStmt->fetchColumn();
$totalPages = ceil($totalHouses / $limit);

// Busca
$sql = "SELECT h.*, p.name as owner_name 
        FROM houses h 
        LEFT JOIN players p ON h.owner = p.id 
        WHERE $whereSQL 
        ORDER BY h.owner DESC, h.size DESC 
        LIMIT $limit OFFSET $offset";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$houses = $stmt->fetchAll(PDO::FETCH_ASSOC);

include 'includes/header.php';
?>

<link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
<script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<meta name="description" content="<?php echo $metaDesc; ?>">
<meta property="og:title" content="<?php echo $page_title; ?>">

<style>
    /* --- DESIGN SYSTEM (Deep Blue) --- */
    :root {
        --bg-dark: #0b1120;
        --bg-card: #162032;
        --primary: #3b82f6;
        --primary-dark: #1e3a8a;
        --accent: #facc15;
        --success: #10b981;
        --danger: #ef4444;
        --text-bright: #ffffff;
        --text-soft: #cbd5e1;
        --border-light: rgba(255, 255, 255, 0.1);
    }

    body {
        background-color: var(--bg-dark);
        color: var(--text-bright);
        font-family: 'Segoe UI', sans-serif;
        overflow-x: hidden;
    }

    /* HERO SECTION */
    .catalog-hero {
        background: linear-gradient(180deg, rgba(11,17,32,0.85) 0%, #0b1120 100%), url('images/hero-houses.jpg') center/cover;
        padding: 80px 0 40px 0;
        text-align: center;
        border-bottom: 1px solid var(--border-light);
        margin-top: -20px;
    }
    .hero-title {
        font-family: 'Rajdhani', sans-serif;
        font-size: 3.5rem;
        font-weight: 800;
        letter-spacing: 2px;
        text-transform: uppercase;
        background: linear-gradient(to right, #fff, #93c5fd);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        text-shadow: 0 0 20px rgba(59, 130, 246, 0.5);
    }

    /* FILTROS */
    .filter-bar {
        background: var(--bg-card);
        border: 1px solid var(--border-light);
        border-radius: 12px;
        padding: 20px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.3);
        margin-bottom: 40px;
    }
    .form-label { color: var(--text-soft); font-weight: 700; font-size: 0.8rem; text-transform: uppercase; }
    .form-select, .btn-filter {
        background-color: rgba(255,255,255,0.05);
        border: 1px solid rgba(255,255,255,0.2);
        color: white;
        font-weight: 600;
    }
    .form-select:focus {
        background-color: rgba(255,255,255,0.1);
        border-color: var(--primary);
        box-shadow: 0 0 10px rgba(59, 130, 246, 0.3);
        color: white;
    }
    option { background-color: #1e293b; color: white; }

    /* CARD DE CASA */
    .house-card {
        background: var(--bg-card);
        border: 1px solid var(--border-light);
        border-radius: 16px;
        overflow: hidden;
        transition: all 0.3s ease;
        height: 100%;
        display: flex;
        flex-direction: column;
    }
    .house-card:hover {
        transform: translateY(-8px);
        border-color: var(--primary);
        box-shadow: 0 0 25px rgba(59, 130, 246, 0.2);
        background: #1e293b;
    }

    /* --- NOVA ÁREA DE IMAGEM CSS --- */
    .house-img-wrapper {
        height: 220px;
        position: relative;
        overflow: hidden;
        border-bottom: 1px solid var(--border-light);
    }
    
    .house-css-img {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        position: relative;
        /* O background é definido via style inline no PHP */
    }

    /* Elementos dentro da imagem CSS */
    .css-town-badge {
        position: absolute;
        top: 15px;
        left: 15px;
        background: rgba(0,0,0,0.5);
        padding: 5px 10px;
        border-radius: 4px;
        font-weight: 700;
        font-size: 0.8rem;
        color: var(--accent);
        text-transform: uppercase;
        border: 1px solid rgba(24acc15, 0.3);
        backdrop-filter: blur(4px);
    }

    .css-house-id {
        font-family: 'Rajdhani', sans-serif;
        font-size: 5rem;
        font-weight: 800;
        color: white;
        opacity: 0.15; /* Bem transparente para ficar no fundo */
        line-height: 1;
        user-select: none;
    }

    .css-coords {
        position: absolute;
        bottom: 15px;
        left: 50%;
        transform: translateX(-50%);
        font-family: 'Courier New', monospace;
        background: rgba(0,0,0,0.6);
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 0.85rem;
        color: var(--text-soft);
        border: 1px solid var(--border-light);
        white-space: nowrap;
    }
    /* -------------------------------- */

    /* Status Badge (Mantido) */
    .status-badge {
        position: absolute; top: 15px; right: 15px;
        padding: 6px 14px; border-radius: 8px;
        font-weight: 800; font-size: 0.75rem; text-transform: uppercase;
        backdrop-filter: blur(5px);
        box-shadow: 0 4px 10px rgba(0,0,0,0.5);
        z-index: 2;
    }
    .status-free { background: rgba(16, 185, 129, 0.9); color: #fff; } 
    .status-occupied { background: rgba(239, 68, 68, 0.9); color: #fff; }

    /* Conteúdo do Card */
    .house-body { padding: 20px; flex-grow: 1; display: flex; flex-direction: column; }
    
    .house-title {
        font-family: 'Rajdhani', sans-serif;
        font-weight: 700;
        font-size: 1.5rem;
        color: white;
        margin-bottom: 15px;
        white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
    }
    
    .info-grid {
        display: grid; grid-template-columns: 1fr 1fr; gap: 10px;
        margin-bottom: 20px;
        background: rgba(0,0,0,0.2);
        padding: 15px; border-radius: 8px;
        border: 1px solid var(--border-light);
    }
    .info-item { text-align: center; }
    .info-label { display: block; font-size: 0.7rem; color: var(--primary); text-transform: uppercase; letter-spacing: 1px; }
    .info-value { display: block; font-size: 1.2rem; color: white; font-weight: 700; }

    .house-footer { margin-top: auto; }
    .owner-display {
        background: rgba(255,255,255,0.05);
        padding: 10px; border-radius: 6px;
        text-align: center; font-size: 0.9rem;
        border: 1px solid var(--border-light);
    }
    .btn-gps {
        width: 100%; background: var(--primary); color: white; font-weight: 800;
        border: none; padding: 12px; border-radius: 8px; text-transform: uppercase; letter-spacing: 1px; transition: 0.3s;
    }
    .btn-gps:hover { background: #2563eb; box-shadow: 0 0 15px var(--primary-glow); }

    /* PAGINAÇÃO */
    .pagination .page-link {
        background: rgba(255,255,255,0.05); color: white; border: 1px solid var(--border-light); margin: 0 3px; border-radius: 6px;
    }
    .pagination .page-link:hover, .pagination .page-item.active .page-link {
        background: var(--primary); border-color: var(--primary); color: white;
    }
</style>

<div class="catalog-hero">
    <div class="container" data-aos="fade-down">
        <h1 class="hero-title">IMÓVEIS GLOBAIS</h1>
        <p class="text-soft fs-5">Descubra cada detalhe do mundo de <?php echo $serverName; ?></p>
        <div class="d-inline-block border border-white border-opacity-25 px-4 py-1 rounded-pill mt-3 text-soft bg-black bg-opacity-25">
            <i class="fas fa-map me-2"></i> <?php echo $totalHouses; ?> Residências Mapeadas
        </div>
    </div>
</div>

<div class="container my-5">

    <div class="filter-bar" data-aos="fade-up">
        <form method="GET" class="row g-3 align-items-end">
            <div class="col-md-4">
                <label class="form-label"><i class="fas fa-map-marked-alt me-1"></i> Localização</label>
                <select name="town" class="form-select" onchange="this.form.submit()">
                    <option value="all">Todas as Cidades</option>
                    <?php foreach ($houseConfig['towns'] as $tid => $tname): ?>
                        <option value="<?php echo $tid; ?>" <?php echo ($town == $tid) ? 'selected' : ''; ?>><?php echo $tname; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4">
                <label class="form-label"><i class="fas fa-door-open me-1"></i> Disponibilidade</label>
                <select name="status" class="form-select" onchange="this.form.submit()">
                    <option value="all">Qualquer Status</option>
                    <option value="vacant" <?php echo ($status == 'vacant') ? 'selected' : ''; ?>>Livres (Vacant)</option>
                    <option value="occupied" <?php echo ($status == 'occupied') ? 'selected' : ''; ?>>Ocupadas</option>
                </select>
            </div>
            <div class="col-md-4">
                <a href="houses.php" class="btn btn-filter w-100 py-2 d-flex align-items-center justify-content-center text-decoration-none">
                    <i class="fas fa-sync-alt me-2"></i> Resetar Filtros
                </a>
            </div>
        </form>
    </div>

    <div class="row g-4">
        <?php if (empty($houses)): ?>
            <div class="col-12 text-center py-5">
                <div class="p-5 rounded border border-white border-opacity-10 bg-black bg-opacity-25">
                    <i class="fas fa-search-location fa-4x text-soft mb-3 opacity-50"></i>
                    <h3 class="fw-bold text-white">Nenhum imóvel encontrado.</h3>
                    <p class="text-soft">Tente selecionar outra cidade.</p>
                </div>
            </div>
        <?php else: 
            foreach ($houses as $h): 
                $isOwned = ($h['owner'] > 0);
                
                // --- GERAÇÃO DA IMAGEM CSS DINÂMICA ---
                $townName = $houseConfig['towns'][$h['town_id']] ?? 'Unknown';
                $coords = (isset($h['posx']) && $h['posx'] > 0) ? "{$h['posx']}, {$h['posy']}, {$h['posz']}" : 'Sem GPS';
                
                // Gera uma cor única baseada no ID para o gradiente
                // Usamos o ID para gerar um HUE (matiz) entre 0 e 360.
                // Multiplicar por um primo (ex: 37) ajuda a espalhar as cores.
                $hue = ($h['id'] * 37) % 360;
                // Gradiente: Azul escuro do tema -> Cor gerada (escura e dessaturada para manter o padrão)
                $bgStyle = "background: linear-gradient(135deg, var(--bg-dark) 0%, hsl($hue, 50%, 20%) 100%);";
                // --------------------------------------
        ?>
        <div class="col-md-6 col-lg-4" data-aos="fade-up">
            <div class="house-card">
                
                <div class="house-img-wrapper">
                    <div class="house-css-img" style="<?php echo $bgStyle; ?>">
                         <div class="css-town-badge">
                             <i class="fas fa-map-marker-alt me-1"></i> <?php echo strtoupper($townName); ?>
                         </div>
                         
                         <div class="css-house-id">#<?php echo $h['id']; ?></div>
                         
                         <div class="css-coords">
                             <i class="fas fa-compass me-1"></i> GPS: <?php echo $coords; ?>
                         </div>
                    </div>

                    <?php if ($isOwned): ?>
                        <span class="status-badge status-occupied">OCUPADA</span>
                    <?php else: ?>
                        <span class="status-badge status-free">LIVRE</span>
                    <?php endif; ?>
                </div>

                <div class="house-body">
                    <h4 class="house-title" title="<?php echo htmlspecialchars($h['name']); ?>">
                        <?php echo htmlspecialchars($h['name']); ?>
                    </h4>

                    <div class="info-grid">
                        <div class="info-item">
                            <span class="info-label">Tamanho</span>
                            <span class="info-value"><?php echo $h['size']; ?> SQM</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">Camas</span>
                            <span class="info-value"><?php echo $h['beds']; ?></span>
                        </div>
                    </div>

                    <div class="house-footer">
                        <?php if ($isOwned): ?>
                            <div class="owner-display">
                                <small class="text-soft text-uppercase d-block mb-1" style="font-size:0.7rem">Proprietário</small>
                                <span class="text-white fw-bold text-truncate d-block"><i class="fas fa-user-check text-success me-1"></i> <?php echo htmlspecialchars($h['owner_name']); ?></span>
                            </div>
                        <?php else: ?>
                            <div class="owner-display border-success border-opacity-25 bg-success bg-opacity-10">
                                <span class="text-success fw-bold"><i class="fas fa-check-circle me-1"></i> Disponível para compra</span>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

            </div>
        </div>
        <?php endforeach; endif; ?>
    </div>

    <?php if ($totalPages > 1): ?>
    <div class="d-flex justify-content-center mt-5">
        <nav>
            <ul class="pagination">
                <li class="page-item <?php echo ($page <= 1) ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?page=<?php echo $page-1; ?>&town=<?php echo $town; ?>&status=<?php echo $status; ?>">Anterior</a>
                </li>
                
                <?php for($i = max(1, $page-2); $i <= min($totalPages, $page+2); $i++): ?>
                    <li class="page-item <?php echo ($page == $i) ? 'active' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $i; ?>&town=<?php echo $town; ?>&status=<?php echo $status; ?>"><?php echo $i; ?></a>
                    </li>
                <?php endfor; ?>

                <li class="page-item <?php echo ($page >= $totalPages) ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?page=<?php echo $page+1; ?>&town=<?php echo $town; ?>&status=<?php echo $status; ?>">Próxima</a>
                </li>
            </ul>
        </nav>
    </div>
    <?php endif; ?>

</div>

<script>
    AOS.init({ once: true });
    // Função de copiar GPS removida pois agora o GPS já está visível na imagem
</script>

<?php include 'includes/footer.php'; ?>