<?php
declare(strict_types=1);

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/conexao.php';
require_once __DIR__ . '/solicitacao_publica_helpers.php';

date_default_timezone_set('America/Sao_Paulo');
$mysqli->set_charset('utf8mb4');

$flash = spConsumirFlash();
$q = spTexto($_GET['q'] ?? '', 150);
$statusFiltro = spTexto($_GET['status'] ?? 'AGUARDANDO_ENTREGA', 40);
$pagina = max(1, (int) ($_GET['pagina'] ?? 1));
$porPagina = 40;
$offset = ($pagina - 1) * $porPagina;

$where = ['1=1'];
$tipos = '';
$valores = [];

if ($q !== '') {
    $where[] = "(protocolo LIKE ? OR nome LIKE ? OR email LIKE ? OR telefone LIKE ? OR setor LIKE ? OR tipo_equipamento LIKE ? OR patrimonio LIKE ? OR defeito LIKE ?)";
    $like = '%' . $q . '%';
    for ($i = 0; $i < 8; $i++) {
        $tipos .= 's';
        $valores[] = $like;
    }
}

if ($statusFiltro !== '') {
    $where[] = 'status = ?';
    $tipos .= 's';
    $valores[] = $statusFiltro;
}

$whereSql = implode(' AND ', $where);

$stmt = $mysqli->prepare("SELECT COUNT(*) AS total FROM solicitacoes_os_publicas WHERE {$whereSql}");
if ($tipos !== '') $stmt->bind_param($tipos, ...$valores);
$stmt->execute();
$total = (int) ($stmt->get_result()->fetch_assoc()['total'] ?? 0);
$stmt->close();

$stmt = $mysqli->prepare("
    SELECT *
    FROM solicitacoes_os_publicas
    WHERE {$whereSql}
    ORDER BY
        FIELD(status,'AGUARDANDO_ENTREGA','RECEBIDA','CANCELADA'),
        data_solicitacao DESC
    LIMIT ? OFFSET ?
");
$tiposLista = $tipos . 'ii';
$valoresLista = [...$valores, $porPagina, $offset];
$stmt->bind_param($tiposLista, ...$valoresLista);
$stmt->execute();
$solicitacoes = [];
$r = $stmt->get_result();
while ($linha = $r->fetch_assoc()) $solicitacoes[] = $linha;
$stmt->close();

$contagens = ['AGUARDANDO_ENTREGA'=>0,'RECEBIDA'=>0,'CANCELADA'=>0];
$r = $mysqli->query("SELECT status,COUNT(*) total FROM solicitacoes_os_publicas GROUP BY status");
if ($r) while ($l=$r->fetch_assoc()) $contagens[$l['status']] = (int)$l['total'];

$totalPaginas = max(1, (int) ceil($total / $porPagina));

function qsPagina(int $p): string {
    $dados=$_GET;$dados['pagina']=$p;return '?'.http_build_query($dados);
}
?>
<!doctype html><html lang="pt-BR"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Solicitações Públicas | Manutenção TI</title>
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
<link href="solicitacao_publica_style.css?v=1" rel="stylesheet">
<style>
.tech-kpis{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-top:14px}.tech-kpi{padding:17px;border:1px solid var(--border);border-radius:20px;background:rgba(255,255,255,.9);box-shadow:0 12px 30px rgba(11,59,120,.07)}.tech-kpi strong{display:block;font-size:28px;font-weight:950}.tech-kpi span{display:block;margin-top:6px;color:var(--muted);font-size:7px;font-weight:900;text-transform:uppercase}.filters{display:grid;grid-template-columns:minmax(260px,1fr) 220px auto;gap:9px}.table-wrap{overflow:auto}.table{width:100%;min-width:1250px;border-collapse:collapse}.table th{padding:12px;color:var(--muted);background:var(--soft);font-size:7px;text-align:left;text-transform:uppercase}.table td{padding:13px;border-top:1px solid var(--border);font-size:8px;vertical-align:middle}.table strong{display:block;font-size:9px}.table small{display:block;margin-top:4px;color:var(--muted);font-size:7px}.badge{display:inline-flex;align-items:center;gap:5px;padding:6px 8px;border-radius:999px;font-size:7px;font-weight:900}.badge.waiting{color:#805400;background:#fff4d6}.badge.received{color:#086247;background:#e8f8f1}.badge.cancelled{color:#922138;background:#fff0f3}.pagination{display:flex;justify-content:center;gap:5px;margin-top:14px}.page-link{width:36px;height:36px;display:grid;place-items:center;border:1px solid var(--border);border-radius:11px;color:var(--blue);background:#fff;font-size:8px;font-weight:900}.page-link.active{color:#fff;background:var(--blue)}
@media(max-width:720px){.tech-kpis,.filters{grid-template-columns:1fr}.table-wrap{overflow:visible}.table{min-width:0}.table thead{display:none}.table,.table tbody,.table tr,.table td{display:block;width:100%}.table tr{margin-bottom:10px;border:1px solid var(--border);border-radius:17px;overflow:hidden}.table td{display:grid;grid-template-columns:105px 1fr;gap:8px;background:#fff}.table td::before{content:attr(data-label);color:var(--light);font-size:6px;font-weight:900;text-transform:uppercase}}
</style></head><body><div class="top-line"></div><div class="bg-grid"></div><main class="page">
<section class="hero"><div class="brand"><div class="logo"><img src="assets/logo_pref.jpg" alt=""></div><div><span class="eyebrow"><i class="bi bi-inbox-fill"></i>Fila de pré-atendimento</span><h1>Solicitações públicas</h1><p>Estas solicitações ainda não são ordens de serviço. O prazo só começa quando o equipamento chegar e a equipe confirmar o recebimento.</p></div></div><aside class="hero-side"><strong><?= spE($_SESSION['usuario'] ?? 'Técnico') ?></strong><span>Usuário responsável pelas confirmações e cancelamentos.</span></aside></section>
<nav class="public-nav"><a class="nav-button" href="listar_os.php"><i class="bi bi-arrow-left"></i>Voltar às OS</a><a class="nav-button" target="_blank" href="solicitar_os.php"><i class="bi bi-box-arrow-up-right"></i>Abrir página pública</a></nav>

<?php if($flash):?><div class="notice <?= $flash['tipo']==='sucesso'?'success':'danger' ?>"><i class="bi bi-check-circle-fill"></i><span><?=spE($flash['mensagem'])?></span></div><?php endif;?>

<section class="tech-kpis">
<div class="tech-kpi"><strong><?=$contagens['AGUARDANDO_ENTREGA']?></strong><span>Aguardando entrega</span></div>
<div class="tech-kpi"><strong><?=$contagens['RECEBIDA']?></strong><span>Recebidas e convertidas em OS</span></div>
<div class="tech-kpi"><strong><?=$contagens['CANCELADA']?></strong><span>Canceladas</span></div>
</section>

<section class="card">
<div class="card-head"><div class="card-title"><span class="card-icon"><i class="bi bi-list-check"></i></span><div><h2>Fila de solicitações</h2><p><?=$total?> resultado(s).</p></div></div></div>
<form method="get" class="filters">
<input class="control" type="search" name="q" value="<?=spE($q)?>" placeholder="Protocolo, pessoa, setor, patrimônio ou defeito...">
<select class="control" name="status">
<option value="">Todos os status</option>
<option value="AGUARDANDO_ENTREGA" <?=$statusFiltro==='AGUARDANDO_ENTREGA'?'selected':''?>>Aguardando entrega</option>
<option value="RECEBIDA" <?=$statusFiltro==='RECEBIDA'?'selected':''?>>Recebidas</option>
<option value="CANCELADA" <?=$statusFiltro==='CANCELADA'?'selected':''?>>Canceladas</option>
</select>
<button class="button primary">Filtrar</button>
</form>

<div class="table-wrap"><table class="table"><thead><tr><th>Protocolo</th><th>Solicitante</th><th>Equipamento</th><th>Defeito</th><th>Solicitada em</th><th>Status</th><th>Ação</th></tr></thead><tbody>
<?php foreach($solicitacoes as $s):$st=spStatus($s['status']);?>
<tr>
<td data-label="Protocolo"><strong><?=spE($s['protocolo'])?></strong><small><?=spE($s['setor'])?></small></td>
<td data-label="Solicitante"><strong><?=spE($s['nome'])?></strong><small><?=spE($s['telefone'])?> • <?=spE($s['email'])?></small></td>
<td data-label="Equipamento"><strong><?=spE($s['tipo_equipamento'])?></strong><small>Pat. <?=spE($s['patrimonio']?:'não informado')?> • <?=spE(trim(($s['marca']?:'').' '.($s['modelo']?:''))?:'sem marca/modelo')?></small></td>
<td data-label="Defeito"><strong><?=spE($s['defeito'])?></strong><?php if($s['vnc']):?><small>VNC/AnyDesk: <?=spE($s['vnc'])?></small><?php endif;?></td>
<td data-label="Solicitada em"><strong><?=spE(spData($s['data_solicitacao']))?></strong></td>
<td data-label="Status"><span class="badge <?=spE($st['classe'])?>"><i class="bi <?=spE($st['icone'])?>"></i><?=spE($st['rotulo'])?></span><?php if($s['os_id']):?><small>OS ID <?=(int)$s['os_id']?></small><?php endif;?></td>
<td data-label="Ação"><?php if($s['status']==='AGUARDANDO_ENTREGA'):?><a class="button green" href="receber_solicitacao_publica.php?id=<?=(int)$s['id']?>"><i class="bi bi-box-arrow-in-down"></i>Confirmar chegada</a><?php elseif($s['os_id']):?><a class="button" href="detalhes_os.php?id=<?=(int)$s['os_id']?>"><i class="bi bi-eye-fill"></i>Abrir OS</a><?php else:?><span><?=spE($s['motivo_cancelamento']?:'Encerrada')?></span><?php endif;?></td>
</tr>
<?php endforeach;?>
<?php if(!$solicitacoes):?><tr><td colspan="7"><div class="protocol"><i class="bi bi-inbox" style="font-size:40px;color:var(--blue)"></i><h2>Nenhuma solicitação encontrada</h2></div></td></tr><?php endif;?>
</tbody></table></div>
<?php if($totalPaginas>1):?><div class="pagination"><?php for($p=max(1,$pagina-3);$p<=min($totalPaginas,$pagina+3);$p++):?><a class="page-link <?=$p===$pagina?'active':''?>" href="<?=spE(qsPagina($p))?>"><?=$p?></a><?php endfor;?></div><?php endif;?>
</section>
</main></body></html>
