<?php
require_once __DIR__ . '/../auth/verifica.php';
require_once __DIR__ . "/../config/conexao.php";

// filtros
$data_inicio = $_GET['data_inicio'] ?? '';
$data_fim = $_GET['data_fim'] ?? '';
$busca = $_GET['busca'] ?? '';

$where = "WHERE 1=1";

if($data_inicio) $where .= " AND DATE(criado_em) >= :data_inicio";
if($data_fim) $where .= " AND DATE(criado_em) <= :data_fim";
if($busca) $where .= " AND (cliente LIKE :busca OR descricao LIKE :busca)";

$sql = "SELECT * FROM recibos $where ORDER BY id DESC";
$stmt = $pdo->prepare($sql);

if($data_inicio) $stmt->bindValue(':data_inicio',$data_inicio);
if($data_fim) $stmt->bindValue(':data_fim',$data_fim);
if($busca) $stmt->bindValue(':busca','%'.$busca.'%');

$stmt->execute();
$dados = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Relatório de Recibos</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

<script>
function exportCSV(){
    let csv = [];
    let rows = document.querySelectorAll("table tr");
    for (let row of rows) {
        let cols = row.querySelectorAll("td, th");
        let data = [];
        cols.forEach(col => data.push(col.innerText));
        csv.push(data.join(","));
    }
    let blob = new Blob([csv.join("\n")], { type: 'text/csv' });
    let a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = "recibos.csv";
    a.click();
}
</script>

</head>

<body class="p-4">

<h3>Relatório de Recibos</h3>

<form class="row g-2 mb-3">
<div class="col"><input type="date" name="data_inicio" class="form-control"></div>
<div class="col"><input type="date" name="data_fim" class="form-control"></div>
<div class="col"><input type="text" name="busca" placeholder="Buscar..." class="form-control"></div>
<div class="col">
<button class="btn btn-primary">Filtrar</button>
<button type="button" onclick="window.print()" class="btn btn-secondary">Imprimir</button>
<button type="button" onclick="exportCSV()" class="btn btn-success">Excel</button>
</div>
</form>

<table class="table table-bordered table-striped">
<tr>
<th>ID</th>
<th>Cliente</th>
<th>Descrição</th>
<th>Valor</th>
<th>Status</th>
</tr>

<?php foreach($dados as $row): ?>
<tr>
<td><?= $row['id'] ?></td>
<td><?= $row['cliente'] ?? '-' ?></td>
<td><?= $row['descricao'] ?? '-' ?></td>
<td>R$ <?= number_format($row['valor'] ?? 0,2,',','.') ?></td>
<td><?= $row['status'] ?? '-' ?></td>
</tr>
<?php endforeach; ?>

</table>

</body>
</html>
