<?php
    include("../protecao_admin.php");
    include("../../conectar_db.php");

   // Consulta otimizada: Buscamos os imóveis e tentamos trazer a primeira imagem de cada um
    $consulta_imoveis = "SELECT i.*, 
                        (SELECT imagem FROM imoveis_imagem WHERE codigo = i.codigo AND numero_img = 1 LIMIT 1) as foto_capa 
                        FROM imoveis i 
                        ORDER BY i.codigo DESC";

    $con_imoveis = mysqli_query($conn, $consulta_imoveis);
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Painel de Controle - OAlmeida</title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">

    <style>
        :root {
            --sidebar-width: 260px;
            --primary-color: #0d6efd;
            --dark-bg: #1e1e2d;
        }

        body { background-color: #f5f7fb; font-family: 'Inter', sans-serif; display: flex; min-height: 100vh; overflow-x: hidden; }

        /* Sidebar Estilizada */
        .sidebar {
            width: var(--sidebar-width);
            background-color: var(--dark-bg);
            color: #a2a3b7;
            position: fixed;
            height: 100vh;
            transition: all 0.3s;
            z-index: 1000;
        }

        .sidebar .nav-link {
            color: #a2a3b7;
            padding: 12px 25px;
            display: flex;
            align-items: center;
            font-size: 0.9rem;
            transition: 0.2s;
        }

        .sidebar .nav-link i { margin-right: 15px; width: 20px; text-align: center; }

        .sidebar .nav-link:hover, .sidebar .nav-link.active {
            color: #fff;
            background-color: rgba(255,255,255,0.05);
        }

        .sidebar-header { padding: 30px 25px; color: #fff; font-weight: 700; font-size: 1.2rem; border-bottom: 1px solid rgba(255,255,255,0.05); }

        /* Conteúdo Principal */
        .main-content {
            flex: 1;
            margin-left: var(--sidebar-width);
            width: calc(100% - var(--sidebar-width));
        }

        .topbar {
            background: #fff;
            height: 70px;
            display: flex;
            align-items: center;
            padding: 0 30px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.02);
            margin-bottom: 30px;
        }

        .card-imovel {
            border: none;
            border-radius: 12px;
            background: #fff;
            box-shadow: 0 2px 10px rgba(0,0,0,0.03);
            transition: 0.3s;
        }

        .card-imovel:hover { box-shadow: 0 5px 15px rgba(0,0,0,0.08); }

        .img-capa {
            width: 150px;
            height: 130px;
            object-fit: cover;
            border-radius: 8px;
        }

        /* Responsividade */
        @media (max-width: 992px) {
            .sidebar { margin-left: calc(-1 * var(--sidebar-width)); }
            .main-content { margin-left: 0; width: 100%; }
            .sidebar.active { margin-left: 0; }
        }
    </style>
</head>
<body>

<nav class="sidebar">
    <div class="sidebar-header">
        <i class="fas fa-building text-primary me-2"></i> CRM OALMEIDA 
    </div>
    <div class="mt-4">
        <p class="px-4 text-uppercase small fw-bold opacity-50 mb-2">Imóveis</p>
        <a href="tela_cadastro_imoveis.php" class="nav-link active">
            <i class="fas fa-list"></i> Listagem
        </a>
        <a href="pagina_cad_imoveis.php" class="nav-link">
            <i class="fas fa-plus-circle"></i> Novo Cadastro
        </a>

        <p class="px-4 text-uppercase small fw-bold opacity-50 mt-4 mb-2">Configurações</p>
        <a href="pagina_cad_imoveis_cidade.php" class="nav-link">
            <i class="fas fa-city"></i> Cidades
        </a>
        <a href="pagina_cad_imoveis_bairro.php" class="nav-link">
            <i class="fas fa-map-marker-alt"></i> Bairros
        </a>
        <a href="pagina_cad_imoveis_tipo.php" class="nav-link">
            <i class="fas fa-tags"></i> Tipos de Imóvel
        </a>
        
        <hr class="mx-4 opacity-10">
        <a href="../logout.php" class="nav-link text-danger">
            <i class="fas fa-sign-out-alt"></i> Sair
        </a>
    </div>
</nav>

<main class="main-content">
    <div class="topbar d-flex justify-content-between">
        <h5 class="m-0 fw-bold">Gestão de Imóveis</h5>
        <div>
            <span class="text-muted me-3">Olá, Administrador</span>
            <img src="https://ui-avatars.com/api/?name=Admin&background=0D6EFD&color=fff" class="rounded-circle" width="35">
        </div>
    </div>

    <div class="container-fluid px-4">
        <div class="row mb-4">
            <div class="col-12 d-flex justify-content-between align-items-center">
                <h3 class="fw-bold">Lista de Imóveis</h3>
                <div class="text-muted small">Total: <?= mysqli_num_rows($con_imoveis) ?> registros</div>
                <a href="pagina_cad_imoveis.php" class="btn btn-primary px-4 py-2 fw-bold shadow-sm">
                    <i class="fas fa-plus me-2"></i>CADASTRAR IMÓVEL
                </a>
            </div>
        </div>

        <div class="card card-imovel p-0 overflow-hidden">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="bg-light">
                        <tr>
                            <th class="ps-4">Imóvel</th>
                            <th>Localização</th>
                            <th>Valor</th>
                            <th class="text-center">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while($row = mysqli_fetch_array($con_imoveis)): 
                            $codigo = $row['codigo'];
                            $img = !empty($row['foto_capa']) 
                                   ? "arquivos/img_imoveis_g/$codigo/".$row['foto_capa'] 
                                   : "../../img/sem-foto.png";

                             $dataOriginal = $row['data_cadastro'];
                            // Cria o objeto a partir da string
                            $data = new DateTime($dataOriginal);

                            // Formata para o padrão desejado (d = dia, m = mês, y = ano com 2 dígitos)
                            $novaData = $data->format('d-m-Y');
                        ?>
                        <tr>
                            <td class="ps-4">
                                <div class="d-flex align-items-center">
                                    <img src="<?= $img ?>" class="img-capa me-3">
                                    <div>
                                        <div class="fw-bold text-dark">#<?= $codigo ?> - <?= mb_strimwidth($row['titulo'], 0, 100, "...") ?></div>
                                        <div class="fw-bold text-dark"><i class="fas fa-map-marker-alt me-2"></i>Endereço: <?= mb_strimwidth($row['endereco'], 0, 100, "...") ?></div>
                                        <small class="text-muted">Ref: <?= $row['ref'] ?> - Data: <?= $novaData ?></small>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="small fw-semibold"><?= $row['bairro'] ?></div>
                                <div class="small text-muted"><?= $row['cidade'] ?></div>
                            </td>
                            <td>
                                <div class="fw-bold text-success">R$ <?= number_format($row['valor'], 2, ',', '.') ?></div>
                            </td>
                            <td class="text-center">
                                <div class="btn-group shadow-sm">
                                    <a href="pagina_edita_imoveis.php?codigo=<?= $codigo ?>" class="btn btn-white btn-sm border" title="Editar"><i class="fas fa-pen text-warning"></i></a>
                                    <a href="cadastro_imagem_imoveis.php?codigo=<?= $codigo ?>" class="btn btn-white btn-sm border" title="Fotos"><i class="fas fa-camera text-info"></i></a>
                                    <a href="delete_tela_imovel.php?codigo=<?= $codigo ?>" class="btn btn-white btn-sm border" onclick="return confirm('Excluir imóvel?')" title="Deletar"><i class="fas fa-trash text-danger"></i></a>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>