<?php
$title='Facturas';
require_once __DIR__ . '/../inc/header.php';
require_once __DIR__ . '/../inc/docs.php';
ensure_part2_tables();
$pdo = db();

// Asegura tabla de pagos (por si aún no existe)
$pdo->exec("
  CREATE TABLE IF NOT EXISTS invoice_payments(
    id INT AUTO_INCREMENT PRIMARY KEY,
    invoice_id INT NOT NULL,
    paid_at DATE NOT NULL,
    amount DECIMAL(12,2) NOT NULL DEFAULT 0,
    note VARCHAR(255) NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_inv (invoice_id),
    CONSTRAINT fk_pay_invoice FOREIGN KEY (invoice_id) REFERENCES documents(id) ON DELETE CASCADE
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

// Listado con pendiente calculado
$sql = "
  SELECT d.*,
         c.nombre, c.apellidos,
         IFNULL(p.paid_total,0) AS paid_total,
         ROUND(GREATEST(d.total - IFNULL(p.paid_total,0), 0), 2) AS pending_total
  FROM documents d
  JOIN clients c ON c.id=d.client_id
  LEFT JOIN (
     SELECT invoice_id, SUM(amount) AS paid_total
     FROM invoice_payments
     GROUP BY invoice_id
  ) p ON p.invoice_id=d.id
  WHERE d.doc_type='invoice'
  ORDER BY d.issue_date DESC, d.id DESC
";
$rows = $pdo->query($sql)->fetchAll();

function eur($n){ return number_format((float)$n,2,',','.') . " €"; }
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="mb-0">Facturas</h4>
    <div class="text-muted">Listado y estado de cobro</div>
  </div>
  <a class="btn btn-primary" href="<?= url('facturas/new.php') ?>">+ Nueva factura</a>
</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 class="text-end">Total</th>
            <th class="text-end">Pendiente</th>
            <th>Estado</th>
            <th class="text-end"></th>
          </tr>
        </thead>
        <tbody>
          <?php foreach($rows as $r): ?>
            <?php
              $pending = (float)$r['pending_total'];
              $is_paid = $pending <= 0.00001 || $r['status']==='paid';
            ?>
            <tr>
              <td class="fw-semibold"><?= h($r['doc_code']) ?></td>
              <td><?= h(trim($r['nombre'].' '.$r['apellidos'])) ?></td>
              <td><?= h($r['issue_date']) ?></td>
              <td class="text-end"><?= eur($r['total']) ?></td>
              <td class="text-end">
                <?php if($is_paid): ?>
                  <span class="badge text-bg-success">0,00 €</span>
                <?php else: ?>
                  <span class="badge text-bg-warning"><?= eur($pending) ?></span>
                <?php endif; ?>
              </td>
              <td><?= h($r['status']) ?></td>
              <td class="text-end">
                <a class="btn btn-sm btn-outline-secondary" href="<?= url('facturas/edit.php?id='.(int)$r['id']) ?>">Editar</a>
                <a class="btn btn-sm btn-outline-primary" target="_blank" href="<?= url('facturas/pdf.php?id='.(int)$r['id']) ?>">PDF</a>
              </td>
            </tr>
          <?php endforeach; ?>
          <?php if(count($rows)===0): ?>
            <tr><td colspan="7" class="text-muted">No hay facturas aún.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

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