<?php
$title='Clientes'; require_once __DIR__ . '/../inc/header.php';
$q=trim($_GET['q']??''); $params=[]; $sql='SELECT * FROM clients';
if($q!==''){ $like='%'.$q.'%'; $sql.=' WHERE nombre LIKE ? OR apellidos LIKE ? OR direccion LIKE ? OR nif_cif LIKE ? OR telefono LIKE ?'; $params=[$like,$like,$like,$like,$like]; }
$sql.=' ORDER BY created_at DESC';
$st=db()->prepare($sql); $st->execute($params); $clients=$st->fetchAll();
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h4 class="mb-0">Clientes</h4>
  <a class="btn btn-primary" href="<?= url('clientes/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 nombre, nif, dirección, teléfono..."></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>Cliente</th><th>NIF/CIF</th><th>Teléfono</th><th class="text-end">Nº cliente</th><th></th></tr></thead>
  <tbody>
  <?php foreach($clients as $c): $id=(int)$c['id']; ?>
    <tr>
      <td class="fw-semibold"><?= h(trim(($c['nombre']??'').' '.($c['apellidos']??''))) ?></td>
      <td><?= h($c['nif_cif']??'') ?></td>
      <td><?= h($c['telefono']??'') ?></td>
      <td class="text-end"><?= h($c['customer_number']??'') ?></td>
      <td class="text-end">
        <a class="btn btn-sm btn-outline-primary" href="<?= url('clientes/view.php?id='.$id) ?>">Ver</a>
        <a class="btn btn-sm btn-outline-secondary" href="<?= url('clientes/edit.php?id='.$id) ?>">Editar</a>
        <?php if(is_admin()): ?>
          <form class="d-inline" method="post" action="<?= url('clientes/delete.php?id='.$id) ?>" onsubmit="return confirm('¿Eliminar este cliente?');">
            <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($clients)===0): ?><tr><td colspan="5" class="text-center text-muted py-4">No hay clientes.</td></tr><?php endif; ?>
  </tbody>
</table>
</div></div></div>

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