<?php
session_start();
require_once '../config/db.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}
$user_id = $_SESSION['user_id'];

// Listar clientes para select
$stmt = $pdo->prepare("SELECT id, name FROM client_customers WHERE user_id = ? ORDER BY name");
$stmt->execute([$user_id]);
$clientes = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Filtros
$cliente_id = isset($_GET['cliente_id']) ? intval($_GET['cliente_id']) : '';
$data_ini = $_GET['data_ini'] ?? '';
$data_fim = $_GET['data_fim'] ?? '';
$tipo_venda = $_GET['tipo_venda'] ?? 'abertas'; // abertas | pagas
$gerou_relatorio = false;
$fiados = [];

if (isset($_GET['gerar'])) {
    if ($tipo_venda == 'abertas') {
        $sql = "
            SELECT c.name as cliente, f.description, SUM(f.saldo) as valor, f.created_at as data_compra
            FROM fiados f
            JOIN client_customers c ON c.id = f.customer_id
            WHERE f.user_id = ?
        ";
        $params = [$user_id];
        if ($cliente_id) {
            $sql .= " AND c.id = ? ";
            $params[] = $cliente_id;
        }
        if ($data_ini) {
            $sql .= " AND f.created_at >= ? ";
            $params[] = $data_ini;
        }
        if ($data_fim) {
            $sql .= " AND f.created_at <= ? ";
            $params[] = $data_fim;
        }
        $sql .= " GROUP BY f.id, c.name, f.description, f.created_at HAVING valor > 0 ORDER BY c.name ASC";
    } elseif ($tipo_venda == 'pagas') { // pagas
        $sql = "
            SELECT c.name as cliente, f.description, SUM(f.valor_pago) as valor, f.created_at as data_compra
            FROM fiados f
            JOIN client_customers c ON c.id = f.customer_id
            WHERE f.user_id = ?
        ";
        $params = [$user_id];
        if ($cliente_id) {
            $sql .= " AND c.id = ? ";
            $params[] = $cliente_id;
        }
        if ($data_ini) {
            $sql .= " AND f.created_at >= ? ";
            $params[] = $data_ini;
        }
        if ($data_fim) {
            $sql .= " AND f.created_at <= ? ";
            $params[] = $data_fim;
        }
        $sql .= " GROUP BY f.id, c.name, f.description, f.created_at HAVING valor > 0 ORDER BY c.name ASC";
    } else { // todas
        $sql = "
            SELECT c.name as cliente, f.description, SUM(f.saldo) as saldo_total, SUM(f.valor_pago) as valor_pago_total, f.created_at as data_compra
            FROM fiados f
            JOIN client_customers c ON c.id = f.customer_id
            WHERE f.user_id = ?
        ";
        $params = [$user_id];
        if ($cliente_id) {
            $sql .= " AND c.id = ? ";
            $params[] = $cliente_id;
        }
        if ($data_ini) {
            $sql .= " AND f.created_at >= ? ";
            $params[] = $data_ini;
        }
        if ($data_fim) {
            $sql .= " AND f.created_at <= ? ";
            $params[] = $data_fim;
        }
        $sql .= " GROUP BY f.id, c.name, f.description, f.created_at ORDER BY c.name ASC";
    }
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $fiados = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $gerou_relatorio = true;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Relatórios - Fiado Fácil</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
<style>
/* --- Aqui você insere todo o CSS do menu lateral e da página (igual ao que já estava funcionando) --- */
body { font-family: 'Inter', sans-serif; background: #f8fafc; color: #1e293b; margin:0; }
.sidebar{position:fixed;left:0;top:0;bottom:0;width:280px;background:#fff;border-right:1px solid #e2e8f0;display:flex;flex-direction:column;z-index:100;}
.sidebar .logo{padding:32px 24px;font-size:1.75rem;font-weight:800;color:#1876F2;display:flex;align-items:center;gap:12px;border-bottom:1px solid #e2e8f0;}
.sidebar nav{flex:1;padding:24px 16px;}
.sidebar nav a{display:flex;align-items:center;gap:16px;color:#64748b;text-decoration:none;font-size:0.95rem;font-weight:500;padding:14px 20px;margin:4px 0;border-radius:12px;transition:all 0.3s;}
.sidebar nav a.active, .sidebar nav a:hover{color:white;background:#1876F2;transform:translateX(4px);}
.sidebar .bottom{padding:24px;border-top:1px solid #e2e8f0;}
.logout-link{color:#ef4444;font-weight:600;text-decoration:none;padding:12px 16px;border-radius:12px;display:flex;align-items:center;gap:12px;}
.main-content{margin-left:280px;padding:32px;}
.page-header{display:flex;align-items:center;gap:16px;margin-bottom:32px;padding-bottom:24px;border-bottom:1px solid #e2e8f0;}
.page-header h2{font-size:2rem;font-weight:700;}
.filters-card, .results-card{background:#fff;border-radius:20px;box-shadow:0 4px 6px -1px rgb(0 0 0 / 0.1);border:1px solid #e2e8f0;margin-bottom:32px;}
.filters-form{padding:32px;display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:24px;align-items:end;}
.form-group{display:flex;flex-direction:column;gap:8px;}
.form-label{font-size:0.9rem;font-weight:600;color:#64748b;text-transform:uppercase;}
.form-input, .form-select{padding:12px 16px;border:2px solid #e2e8f0;border-radius:12px;font-size:1rem;}
.submit-btn{background:#1876F2;color:white;font-weight:600;border:none;border-radius:12px;padding:14px 24px;cursor:pointer;display:flex;align-items:center;gap:8px;}
.results-table{width:100%;border-collapse:collapse;}
.results-table th{background:#eaf4ff;color:#1876F2;font-size:0.9rem;font-weight:700;text-transform:uppercase;padding:16px 20px;text-align:left;border-bottom:1px solid #e2e8f0;}
.results-table td{padding:16px 20px;border-bottom:1px solid #e2e8f0;}
.table-container{overflow-x:auto;}
.empty-state{text-align:center;padding:48px 32px;color:#64748b;}
#client-search-results { border: 1px solid #ccc; max-height: 150px; overflow-y: auto; }
#client-search-results div { padding: 8px; cursor: pointer; }
#client-search-results div:hover { background-color: #f0f0f0; }
</style>
</head>
<body>

<!-- Menu lateral -->
<aside class="sidebar" id="sidebar">
    <div class="logo">
        <i class="fa-solid fa-wallet"></i>
        <span>Fiado Fácil</span>
    </div>
    <nav>
        <a href="dashboard.php"><i class="fa-solid fa-house"></i> <span>Painel</span></a>
        <a href="clientes.php"><i class="fa-solid fa-users"></i> <span>Clientes</span></a>
        <a href="fiados.php"><i class="fa-solid fa-file-invoice-dollar"></i> <span>Fiados</span></a>
        <a href="carne.php"><i class="fa-solid fa-file-pdf"></i> <span>Carnê PDF</span></a>
        <a href="relatorios.php" class="active"><i class="fa-solid fa-chart-line"></i> <span>Relatórios</span></a>
        <a href="configuracao.php"><i class="fa-solid fa-cog"></i> <span>Configuração</span></a>
    </nav>
    <div class="bottom">
        <a href="logout.php" class="logout-link"><i class="fa-solid fa-right-from-bracket"></i> <span>Sair</span></a>
    </div>
</aside>
<button class="menu-toggle" id="menuToggle"><i class="fa-solid fa-bars"></i></button>
<div class="overlay" id="overlay"></div>

<div class="main-content">
    <div class="page-header">
        <h2>Relatórios</h2>
    </div>

    <div class="filters-card">
        <form method="get" class="filters-form" autocomplete="off">
            <div class="form-group">
                <label for="cliente_nome" class="form-label">Cliente</label>
                <input type="text" id="cliente_nome" name="cliente_nome" class="form-input" placeholder="Digite o nome do cliente">
                <input type="hidden" name="cliente_id" id="cliente_id">
                <div id="client-search-results" class="list-group"></div>
            </div>
            <div class="form-group">
                <label for="data_ini" class="form-label">Data Início</label>
                <input type="date" name="data_ini" id="data_ini" value="<?= htmlspecialchars($data_ini) ?>" class="form-input">
            </div>
            <div class="form-group">
                <label for="data_fim" class="form-label">Data Fim</label>
                <input type="date" name="data_fim" id="data_fim" value="<?= htmlspecialchars($data_fim) ?>" class="form-input">
            </div>
            <div class="form-group">
                <label for="tipo_venda" class="form-label">Tipo de Relatório</label>
                <select name="tipo_venda" id="tipo_venda" class="form-select">
                    <option value="abertas" <?= $tipo_venda=='abertas'?'selected':'' ?>>Vendas a Receber</option>
                    <option value="pagas" <?= $tipo_venda=='pagas'?'selected':'' ?>>Vendas Pagas</option>
                    <option value="todas" <?= $tipo_venda=='todas'?'selected':'' ?>>Todas as Vendas</option>
                </select>
            </div>
            <div class="form-group">
                <button type="submit" name="gerar" value="1" class="submit-btn">
                    <i class="fa-solid fa-chart-bar"></i> Gerar Relatório
                </button>
            </div>
        </form>
    </div>

    <?php if ($gerou_relatorio): ?>
    <div class="results-card">
        <?php if (empty($fiados)): ?>
            <div class="empty-state">
                <i class="fa-solid fa-chart-line-up"></i>
                <h4>Nenhum resultado encontrado</h4>
                <p>Não foram encontrados dados com os filtros selecionados.</p>
            </div>
        <?php else: ?>
            <div class="table-container">
                <table class="results-table">
                    <thead>
                        <tr>
                            <th>Cliente</th>
                            <th>Descrição</th>
                            <th>Data de Compra</th>
                            <th>Valor</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $total=0; foreach($fiados as $f): 
                            if ($tipo_venda == 'todas') {
                                $current_value = $f['saldo_total'] + $f['valor_pago_total'];
                            } else {
                                $current_value = $f['valor'];
                            }
                            $total+=$current_value; 
                        ?>
                        <tr>
                            <td><?= htmlspecialchars($f['cliente']) ?></td>
                            <td><?= htmlspecialchars($f['description']) ?></td>
                            <td><?= date('d/m/Y', strtotime($f['data_compra'])) ?></td>
                            <td>
                                <?php if ($tipo_venda == 'todas'): ?>
                                    A Receber: R$ <?= number_format($f['saldo_total'],2,',','.') ?><br>
                                    Pagos: R$ <?= number_format($f['valor_pago_total'],2,',','.') ?><br>
                                    Total: R$ <?= number_format($current_value,2,',','.') ?>
                                <?php else: ?>
                                    R$ <?= number_format($f['valor'],2,',','.') ?>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr style="font-weight:700;">
                            <td colspan="3" style="text-align:right;">TOTAL:</td>
                            <td>R$ <?= number_format($total,2,',','.') ?></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>

<script>
const menuToggle = document.getElementById('menuToggle');
const sidebar = document.getElementById('sidebar');
const overlay = document.getElementById('overlay');

menuToggle.addEventListener('click', ()=>{ sidebar.classList.toggle('open'); overlay.classList.toggle('active'); });
overlay.addEventListener('click', ()=>{ sidebar.classList.remove('open'); overlay.classList.remove('active'); });
sidebar.querySelectorAll('nav a, .logout-link').forEach(link => { link.addEventListener('click', ()=>{
if(window.innerWidth<=768){ sidebar.classList.remove('open'); overlay.classList.remove('active'); } }); });

const clientNameInput = document.getElementById('cliente_nome');
const clientIdInput = document.getElementById('cliente_id');
const searchResultsContainer = document.getElementById('client-search-results');

const clients = <?php echo json_encode($clientes); ?>;

clientNameInput.addEventListener('input', function() {
    const searchTerm = this.value.toLowerCase();
    searchResultsContainer.innerHTML = '';

    if (searchTerm.length === 0) {
        return;
    }

    const filteredClients = clients.filter(client => client.name.toLowerCase().includes(searchTerm));

    filteredClients.forEach(client => {
        const clientDiv = document.createElement('div');
        clientDiv.textContent = client.name;
        clientDiv.dataset.clientId = client.id;
        clientDiv.addEventListener('click', function() {
            clientNameInput.value = this.textContent;
            clientIdInput.value = this.dataset.clientId;
            searchResultsContainer.innerHTML = '';
        });
        searchResultsContainer.appendChild(clientDiv);
    });
});

</script>


</body>
</html>