<?php
$title='Presupuestos';
require_once __DIR__ . '/../inc/header.php';
require_once __DIR__ . '/../inc/docs.php';
ensure_part2_tables();
$q=trim($_GET['q']??''); $params=[];
$sql="SELECT d.*, c.nombre, c.apellidos FROM documents d JOIN clients c ON c.id=d.client_id WHERE d.doc_type='quote'";
if($q!==''){ $like='%'.$q.'%'; $sql.=" AND (d.doc_code LIKE ? OR c.nombre LIKE ? OR c.apellidos LIKE ?)"; $params=[$like,$like,$like]; }
$sql.=" ORDER BY d.issue_date DESC, d.id DESC";
$st=db()->prepare($sql); $st->execute($params); $docs=$st->fetchAll();
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h4 class="mb-0">Presupuestos</h4>
  <a class="btn btn-primary" href="<?= url('presupuestos/new.php') ?>">+ Nuevo</a>
</div>

<div class="card shadow-sm mb-3"><div class="card-body">
  <form class="row g-2" method="get">
    <div class="col-md-10"><input class="form-control" name="q" value="<?= h($q) ?>" placeholder="Buscar por código o cliente"></div>
    <div class="col-md-2 d-grid"><button class="btn btn-outline-secondary">Buscar</button></div>
  </form>
</div></div>

<div class="card shadow-sm"><div class="card-body"><div class="table-responsive">
<table class="table table-hover align-middle">
<thead><tr><th>Código</th><th>Cliente</th><th>Fecha</th><th>Estado</th><th class="text-end">Total</th><th></th></tr></thead>
<tbody>
<?php foreach($docs as $d): $id=(int)$d['id']; ?>
<tr>
  <td class="fw-semibold"><?= h($d['doc_code']) ?></td>
  <td><?= h(trim($d['nombre'].' '.$d['apellidos'])) ?></td>
  <td><?= h($d['issue_date']) ?></td>
  <td><span class="badge text-bg-secondary"><?= h($d['status']) ?></span></td>
  <td class="text-end"><?= number_format((float)$d['total'],2,',','.') ?> €</td>
  <td class="text-end">
    <a class="btn btn-sm btn-outline-primary" target="_blank" href="<?= url('presupuestos/pdf.php?id='.$id) ?>">PDF</a>
    <a class="btn btn-sm btn-outline-secondary" href="<?= url('presupuestos/edit.php?id='.$id) ?>">Editar</a>
    <?php if(is_admin()): ?>
      <form class="d-inline" method="post" action="<?= url('presupuestos/delete.php?id='.$id) ?>" onsubmit="return confirm('¿Eliminar este documento?');">
        <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
        <button class="btn btn-sm btn-outline-danger">Eliminar</button>
      </form>
    <?php endif; ?>
  </td>
</tr>
<?php endforeach; ?>
<?php if(count($docs)===0): ?><tr><td colspan="6" class="text-center text-muted py-4">No hay documentos.</td></tr><?php endif; ?>
</tbody></table></div></div></div>

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