<?php
$title='Editar factura';
require_once __DIR__ . '/../inc/header.php';
require_once __DIR__ . '/../inc/docs.php';
ensure_part2_tables();

$pdo=db();
$id=(int)($_GET['id']??0);

$st=$pdo->prepare("SELECT d.*, c.nombre, c.apellidos FROM documents d JOIN clients c ON c.id=d.client_id WHERE d.id=? AND d.doc_type='invoice'");
$st->execute([$id]);
$doc=$st->fetch();
if(!$doc){ http_response_code(404); exit('Factura no encontrada'); }

// Pagos
$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;
");
$ps=$pdo->prepare("SELECT * FROM invoice_payments WHERE invoice_id=? ORDER BY paid_at DESC, id DESC");
$ps->execute([$id]);
$payments=$ps->fetchAll();
$paid_total=0.0;
foreach($payments as $p){ $paid_total += (float)$p['amount']; }
$pending = round(max((float)$doc['total'] - $paid_total, 0), 2);

?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="mb-0"><?= h($doc['doc_code']) ?></h4>
    <div class="text-muted">Cliente: <?= h(trim($doc['nombre'].' '.$doc['apellidos'])) ?></div>
  </div>
  <div class="d-flex gap-2 flex-wrap">
    <a class="btn btn-outline-primary" target="_blank" href="<?= url('facturas/pdf.php?id='.$id) ?>">PDF</a>
    <a class="btn btn-outline-secondary" href="<?= url('facturas/list.php') ?>">Volver</a>
    <a class="btn btn-outline-warning" href="<?= url('facturas/rectificativa_new.php?id='.$id) ?>">Rectificativa</a>
    <a class="btn btn-outline-danger" href="<?= url('facturas/delete.php?id='.$id) ?>">Borrar</a>
  </div>
</div>

<div class="row g-3">
  <div class="col-lg-7">
    <div class="card shadow-sm"><div class="card-body">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <div class="text-muted small">Estado</div>
          <div class="fw-semibold"><?= h($doc['status']) ?></div>
          <?php if(!empty($doc['is_rectificativa']) && !empty($doc['rectifies_invoice_id'])): ?>
            <div class="text-muted small">Rectifica a la factura ID <?= (int)$doc['rectifies_invoice_id'] ?></div>
          <?php endif; ?>
        </div>
        <div class="text-end">
          <div class="text-muted small">Total</div>
          <div class="fw-bold fs-5"><?= eur($doc['total']) ?></div>
        </div>
      </div>
      <hr>
      <div class="d-flex justify-content-between">
        <div><span class="text-muted small">Pagado</span><div class="fw-semibold"><?= eur($paid_total) ?></div></div>
        <div class="text-end"><span class="text-muted small">Pendiente</span>
          <div class="fw-semibold <?= $pending>0?'text-warning':'text-success' ?>"><?= eur($pending) ?></div>
        </div>
      </div>
      <div class="text-muted small mt-2">Si la factura está pagada al 100%, el sistema puede bloquear la edición según tu configuración anterior.</div>
    </div></div>

    <div class="card shadow-sm mt-3"><div class="card-body">
      <h6 class="mb-2">Historial de pagos</h6>
      <div class="table-responsive">
        <table class="table table-sm align-middle">
          <thead><tr><th>Fecha</th><th class="text-end">Importe</th><th>Nota</th><th class="text-end">Acciones</th></tr></thead>
          <tbody>
            <?php foreach($payments as $p): ?>
              <tr>
                <td><?= h($p['paid_at']) ?></td>
                <td class="text-end"><?= eur($p['amount']) ?></td>
                <td><?= h($p['note'] ?? '') ?></td>
                <td class="text-end">
                  <form method="post" action="<?= url('facturas/payments_delete.php?id='.(int)$p['id'].'&invoice_id='.$id) ?>" onsubmit="return confirm('¿Eliminar este pago?');" style="display:inline">
                    <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                    <button class="btn btn-sm btn-outline-danger">Eliminar</button>
                  </form>
                </td>
              </tr>
            <?php endforeach; ?>
            <?php if(count($payments)===0): ?>
              <tr><td colspan="4" class="text-muted">Sin pagos aún.</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
      <div class="text-muted small">Nota: eliminar pagos es útil si metiste un pago por error.</div>
    </div></div>
  </div>

  <div class="col-lg-5">
    <div class="card shadow-sm"><div class="card-body">
      <h6 class="mb-2">Acciones rápidas</h6>
      <a class="btn btn-outline-primary w-100 mb-2" href="<?= url('clientes/view.php?id='.(int)$doc['client_id']) ?>">Ir a ficha del cliente</a>
      <a class="btn btn-outline-secondary w-100" href="<?= url('facturas/pdf.php?id='.$id) ?>" target="_blank">Ver PDF</a>
    </div></div>
  </div>
</div>

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