<?php
$title='Factura';
require_once __DIR__ . '/../inc/header.php';
require_once __DIR__ . '/../inc/docs.php';
require_login();

$pdo = db();
ensure_part2_tables();
ensure_schema_safe();

$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;
");

$id = (int)($_GET['id'] ?? 0);
$st = $pdo->prepare("SELECT d.*, c.nombre, c.apellidos, c.nif_cif, c.direccion, c.postal_code, c.localidad, c.provincia
                     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'); }

$paidSt = $pdo->prepare("SELECT IFNULL(SUM(amount),0) AS paid_total FROM invoice_payments WHERE invoice_id=?");
$paidSt->execute([$id]);
$paid_total = (float)($paidSt->fetch()['paid_total'] ?? 0);
$total = (float)($doc['total'] ?? 0);
$pending = max($total - $paid_total, 0);

$locked = false;
$status = strtolower((string)($doc['status'] ?? ''));
if ($pending <= 0.0001) $locked = true;
if (in_array($status, ['paid','pagada','cerrada','closed'], true)) $locked = true;

if($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action'] ?? '') === 'add_payment'){
  csrf_check();
  if($locked){
    flash_set('warning','Esta factura está pagada al 100% y queda bloqueada. Si necesitas corregirla, crea una rectificativa.');
    redirect('facturas/edit.php?id='.$id);
  }
  $paid_at = trim((string)($_POST['paid_at'] ?? ''));
  $amount_raw = trim((string)($_POST['amount'] ?? '0'));
  $amount_raw = str_replace([' ','.'], ['', ''], $amount_raw);
  $amount_raw = str_replace(',', '.', $amount_raw);
  $amount  = (float)$amount_raw;
  $note    = trim((string)($_POST['note'] ?? ''));

  if($paid_at==='') $paid_at = date('Y-m-d');
  if($amount <= 0){
    flash_set('danger','Importe inválido.');
    redirect('facturas/edit.php?id='.$id);
  }

  $pdo->prepare("INSERT INTO invoice_payments(invoice_id, paid_at, amount, note) VALUES(?,?,?,?)")
      ->execute([$id, $paid_at, $amount, $note ?: null]);

  flash_set('success','Pago añadido.');
  redirect('facturas/edit.php?id='.$id);
}

if($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action'] ?? '') === 'delete_payment'){
  csrf_check();
  if($locked){
    flash_set('warning','La factura está bloqueada. No se pueden borrar pagos.');
    redirect('facturas/edit.php?id='.$id);
  }
  $pid = (int)($_POST['payment_id'] ?? 0);
  if($pid){
    $pdo->prepare("DELETE FROM invoice_payments WHERE id=? AND invoice_id=?")->execute([$pid, $id]);
    flash_set('success','Pago eliminado.');
  }
  redirect('facturas/edit.php?id='.$id);
}

$payRowsSt = $pdo->prepare("SELECT * FROM invoice_payments WHERE invoice_id=? ORDER BY paid_at DESC, id DESC");
$payRowsSt->execute([$id]);
$payments = $payRowsSt->fetchAll();

$linesSt = $pdo->prepare("SELECT * FROM document_lines WHERE document_id=? ORDER BY line_no");
$linesSt->execute([$id]);
$lines = $linesSt->fetchAll();

function eurx($n){ return number_format((float)$n,2,',','.') . " €"; }
$clientName = trim(($doc['nombre']??'').' '.($doc['apellidos']??''));
?>
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
  <div>
    <h4 class="mb-0">Factura <?= h($doc['doc_code']) ?></h4>
    <div class="text-muted small">
      Cliente: <span class="fw-semibold"><?= h($clientName) ?></span>
      · Total: <span class="fw-semibold"><?= eurx($total) ?></span>
      · Pagado: <span class="fw-semibold"><?= eurx($paid_total) ?></span>
      · Pendiente: <span class="fw-semibold <?= $pending>0?'text-warning':'text-success' ?>"><?= eurx($pending) ?></span>
      <?php if($locked): ?> · <span class="badge text-bg-success">Bloqueada</span><?php endif; ?>
    </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-primary" href="<?= url('documents/email.php?id='.$id) ?>">Enviar</a>
    <a class="btn btn-outline-secondary" href="<?= url('facturas/list.php') ?>">Volver</a>
  </div>
</div>

<div class="row g-3">
  <div class="col-lg-7">
    <div class="card shadow-sm">
      <div class="card-body">
        <h6 class="mb-2">Líneas</h6>
        <?php if($locked): ?>
          <div class="alert alert-info">Factura pagada al 100%. Edición bloqueada. Para corregir, crea una rectificativa.</div>
        <?php endif; ?>
        <div class="table-responsive">
          <table class="table table-sm align-middle">
            <thead><tr><th>Concepto</th><th class="text-end">Cant.</th><th class="text-end">Precio</th><th class="text-end">IVA</th><th class="text-end">Total</th></tr></thead>
            <tbody>
              <?php foreach($lines as $l): ?>
                <tr>
                  <td><?= h($l['description'] ?? '') ?></td>
                  <td class="text-end"><?= h($l['quantity'] ?? $l['qty'] ?? 1) ?></td>
                  <td class="text-end"><?= eurx($l['unit_price'] ?? 0) ?></td>
                  <td class="text-end"><?= h(($l['vat_rate'] ?? 21).'%') ?></td>
                  <td class="text-end"><?= eurx($l['total'] ?? $l['line_total'] ?? 0) ?></td>
                </tr>
              <?php endforeach; ?>
              <?php if(count($lines)===0): ?><tr><td colspan="5" class="text-muted">Sin líneas.</td></tr><?php endif; ?>
            </tbody>
          </table>
        </div>
        <div class="text-end">
          <div><span class="text-muted">Subtotal</span> <span class="fw-semibold"><?= eurx($doc['subtotal'] ?? 0) ?></span></div>
          <div><span class="text-muted">IVA</span> <span class="fw-semibold"><?= eurx($doc['tax_total'] ?? 0) ?></span></div>
          <div class="fs-5"><span class="text-muted">TOTAL</span> <span class="fw-semibold"><?= eurx($total) ?></span></div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-lg-5">
    <div class="card shadow-sm">
      <div class="card-body">
        <div class="d-flex justify-content-between align-items-center mb-2">
          <h6 class="mb-0">Pagos a cuenta</h6>
          <span class="text-muted small">Historial</span>
        </div>

        <?php if(!$locked): ?>
        <form method="post" class="row g-2 mb-3">
          <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
          <input type="hidden" name="action" value="add_payment">
          <div class="col-5">
            <label class="form-label small mb-1">Fecha</label>
            <input class="form-control form-control-sm" type="date" name="paid_at" value="<?= h(date('Y-m-d')) ?>">
          </div>
          <div class="col-4">
            <label class="form-label small mb-1">Importe</label>
            <input class="form-control form-control-sm" name="amount" placeholder="0,00" required>
          </div>
          <div class="col-12">
            <label class="form-label small mb-1">Nota</label>
            <input class="form-control form-control-sm" name="note" placeholder="(opcional)">
          </div>
          <div class="col-12 d-grid">
            <button class="btn btn-sm btn-primary">Añadir pago</button>
          </div>
        </form>
        <?php else: ?>
          <div class="alert alert-success mb-3">Factura pagada al 100%. No se pueden añadir ni borrar pagos.</div>
        <?php endif; ?>

        <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"></th></tr></thead>
            <tbody>
              <?php foreach($payments as $p): ?>
                <tr>
                  <td><?= h($p['paid_at']) ?></td>
                  <td class="text-end"><?= eurx($p['amount']) ?></td>
                  <td class="text-muted small"><?= h($p['note'] ?? '') ?></td>
                  <td class="text-end">
                    <?php if(!$locked): ?>
                      <form method="post" onsubmit="return confirm('¿Eliminar este pago?');" style="display:inline">
                        <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                        <input type="hidden" name="action" value="delete_payment">
                        <input type="hidden" name="payment_id" value="<?= (int)$p['id'] ?>">
                        <button class="btn btn-sm btn-outline-danger">Eliminar</button>
                      </form>
                    <?php endif; ?>
                  </td>
                </tr>
              <?php endforeach; ?>
              <?php if(count($payments)===0): ?><tr><td colspan="4" class="text-muted">Sin pagos registrados.</td></tr><?php endif; ?>
            </tbody>
          </table>
        </div>

        <div class="d-flex justify-content-between mt-2">
          <div class="text-muted small">Pagado</div>
          <div class="fw-semibold"><?= eurx($paid_total) ?></div>
        </div>
        <div class="d-flex justify-content-between">
          <div class="text-muted small">Pendiente</div>
          <div class="fw-semibold <?= $pending>0?'text-warning':'text-success' ?>"><?= eurx($pending) ?></div>
        </div>
      </div>
    </div>
  </div>
</div>

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