<?php

require_once __DIR__ . '/../../includes/header.php';

/*
=========================================
FILTROS
=========================================
*/

$evento_id = intval($_GET['evento_id'] ?? 0);
$aluno = trim($_GET['aluno'] ?? '');
$status_pagamento = $_GET['status_pagamento'] ?? '';

$data_inicial = $_GET['data_inicial'] ?? '';
$data_final = $_GET['data_final'] ?? '';

$where = " 1=1 ";
$params = [];

/*
=========================================
EVENTO
=========================================
*/

if($evento_id > 0){

    $where .= " AND ev.evento_id = :evento_id ";

    $params['evento_id'] = $evento_id;
}

/*
=========================================
ALUNO
=========================================
*/

if($aluno != ''){

    $where .= " AND a.nome LIKE :aluno ";

    $params['aluno'] = "%{$aluno}%";
}

/*
=========================================
STATUS PAGAMENTO
=========================================
*/

if($status_pagamento == 'S'){

    $where .= " AND ev.pago = 'S' ";

}

if($status_pagamento == 'N'){

    $where .= " AND ev.pago = 'N' ";

}

/*
=========================================
PERIODO
=========================================
*/

if($data_inicial != ''){

    $where .= " AND DATE(ev.criado_em) >= :data_inicial ";

    $params['data_inicial'] = $data_inicial;
}

if($data_final != ''){

    $where .= " AND DATE(ev.criado_em) <= :data_final ";

    $params['data_final'] = $data_final;
}

/*
=========================================
EVENTOS FILTRO
=========================================
*/

$eventos = $pdo->query("
SELECT *
FROM eventos
ORDER BY data_evento DESC
")->fetchAll(PDO::FETCH_ASSOC);

/*
=========================================
RESUMO FINANCEIRO
=========================================
*/

$sqlResumo = "

SELECT

COUNT(ev.id) total_vendas,

SUM(ev.valor_total) total_vendido,

SUM(
CASE
WHEN ev.pago='S'
THEN ev.valor_total
ELSE 0
END
) total_recebido,

SUM(
CASE
WHEN ev.pago='N'
THEN ev.valor_total
ELSE 0
END
) total_pendente

FROM evento_vendas ev

INNER JOIN alunos a
ON a.id = ev.aluno_id

WHERE {$where}

";

$stmt = $pdo->prepare($sqlResumo);
$stmt->execute($params);

$resumo = $stmt->fetch(PDO::FETCH_ASSOC);

/*
=========================================
CONVITES
=========================================
*/

$sqlConvites = "

SELECT

COUNT(ec.id) total_convites,

SUM(
CASE
WHEN ec.utilizado='S'
THEN 1
ELSE 0
END
) utilizados

FROM evento_convites ec

INNER JOIN alunos a
ON a.id = ec.aluno_id

INNER JOIN evento_vendas ev
ON ev.id = ec.venda_id

WHERE {$where}

";

$stmt = $pdo->prepare($sqlConvites);
$stmt->execute($params);

$convites = $stmt->fetch(PDO::FETCH_ASSOC);

$total_convites = intval($convites['total_convites']);
$utilizados = intval($convites['utilizados']);

$pendentes = $total_convites - $utilizados;

$taxa_presenca = $total_convites > 0
? round(($utilizados / $total_convites) * 100,1)
: 0;

/*
=========================================
LISTAGEM
=========================================
*/

$sql = "

SELECT

ev.*,

a.nome aluno,

e.nome evento

FROM evento_vendas ev

INNER JOIN alunos a
ON a.id = ev.aluno_id

INNER JOIN eventos e
ON e.id = ev.evento_id

WHERE {$where}

ORDER BY ev.id DESC

";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);

$vendas = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>

<div class="page-header">

<div>

<h2>📊 Relatório Geral de Eventos</h2>

<div class="subtitle">

Controle financeiro e presença

</div>

</div>

</div>

<form method="GET" class="card-premium" style="padding:20px;margin-bottom:20px;">

<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:15px;">

<div>

<label>Evento</label>

<select name="evento_id" class="form-control">

<option value="0">Todos</option>

<?php foreach($eventos as $e): ?>

<option
value="<?= $e['id'] ?>"
<?= $evento_id == $e['id'] ? 'selected' : '' ?>>

<?= htmlspecialchars($e['nome']) ?>

</option>

<?php endforeach; ?>

</select>

</div>

<div>

<label>Aluno</label>

<input
type="text"
name="aluno"
class="form-control"
value="<?= htmlspecialchars($aluno) ?>">

</div>

<div>

<label>Data Inicial</label>

<input
type="date"
name="data_inicial"
class="form-control"
value="<?= $data_inicial ?>">

</div>

<div>

<label>Data Final</label>

<input
type="date"
name="data_final"
class="form-control"
value="<?= $data_final ?>">

</div>

<div>

<label>Status</label>

<select
name="status_pagamento"
class="form-control">

<option value="">Todos</option>
<option value="S" <?= $status_pagamento=='S'?'selected':'' ?>>Pago</option>
<option value="N" <?= $status_pagamento=='N'?'selected':'' ?>>Pendente</option>

</select>

</div>

<div style="display:flex;align-items:flex-end;">

<button class="btn btn-primary">

Filtrar

</button>

</div>

</div>

</form>

<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:15px;margin-bottom:20px;">

<div class="card-premium">
<h3><?= intval($resumo['total_vendas']) ?></h3>
<div>Vendas</div>
</div>

<div class="card-premium">
<h3><?= moeda($resumo['total_vendido']) ?></h3>
<div>Total Vendido</div>
</div>

<div class="card-premium">
<h3 style="color:#22c55e;">
<?= moeda($resumo['total_recebido']) ?>
</h3>
<div>Recebido</div>
</div>

<div class="card-premium">
<h3 style="color:#ef4444;">
<?= moeda($resumo['total_pendente']) ?>
</h3>
<div>Pendente</div>
</div>

<div class="card-premium">
<h3><?= $total_convites ?></h3>
<div>Convites</div>
</div>

<div class="card-premium">
<h3><?= $utilizados ?></h3>
<div>Entradas</div>
</div>

<div class="card-premium">
<h3><?= $taxa_presenca ?>%</h3>
<div>Presença</div>
</div>

</div>

<div class="card-premium">

<h3 style="margin-bottom:15px;">
💰 Vendas
</h3>

<div class="table-responsive">

<table class="table-premium">

<thead>

<tr>

<th>Data</th>
<th>Evento</th>
<th>Aluno</th>
<th>Responsável</th>
<th>Qtd</th>
<th>Total</th>
<th>Status</th>

</tr>

</thead>

<tbody>

<?php foreach($vendas as $v): ?>

<tr>

<td>

<?= date(
'd/m/Y',
strtotime($v['criado_em'])
) ?>

</td>

<td>

<?= htmlspecialchars($v['evento']) ?>

</td>

<td>

<?= htmlspecialchars($v['aluno']) ?>

</td>

<td>

<?= htmlspecialchars($v['responsavel']) ?>

</td>

<td>

<?= intval($v['quantidade']) ?>

</td>

<td>

<?= moeda($v['valor_total']) ?>

</td>

<td>

<span class="badge <?= $v['pago']=='S'
? 'badge-ativo'
: 'badge-inativo' ?>">

<?= $v['pago']=='S'
? 'Pago'
: 'Pendente' ?>

</span>

</td>

</tr>

<?php endforeach; ?>

</tbody>

</table>

</div>

</div>

<div class="card-premium" style="margin-top:20px;">

<h3 style="margin-bottom:15px;">
⏳ Pendências Financeiras
</h3>

<div class="table-responsive">

<table class="table-premium">

<thead>

<tr>

<th>Aluno</th>
<th>Responsável</th>
<th>Qtd</th>
<th>Valor</th>

</tr>

</thead>

<tbody>

<?php foreach($vendas as $v): ?>

<?php if($v['pago'] != 'S'): ?>

<tr>

<td><?= htmlspecialchars($v['aluno']) ?></td>

<td><?= htmlspecialchars($v['responsavel']) ?></td>

<td><?= intval($v['quantidade']) ?></td>

<td><?= moeda($v['valor_total']) ?></td>

</tr>

<?php endif; ?>

<?php endforeach; ?>

</tbody>

</table>

</div>

</div>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>