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

$pdo = db();

/**
 * FIX CRÍTICO:
 * Aseguramos que exista la tabla invoice_payments ANTES de consultarla.
 */
$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
                   FROM documents d
                   JOIN clients c ON c.id=d.client_id
                   WHERE d.id=? AND d.doc_type='invoice'");
$st->execute([$id]);
$d=$st->fetch();
if(!$d){ http_response_code(404); echo "Factura no encontrada"; exit; }

$clients=$pdo->query("SELECT id,nombre,apellidos FROM clients ORDER BY nombre ASC")->fetchAll();
$ls=$pdo->prepare("SELECT * FROM document_lines WHERE document_id=? ORDER BY line_no ASC");
$ls->execute([$id]);
$lines=$ls->fetchAll();

// Totales de pagos
$sumPaidStmt=$pdo->prepare("SELECT IFNULL(SUM(amount),0) AS s FROM invoice_payments WHERE invoice_id=?");
$sumPaidStmt->execute([$id]);
$paid_total=(float)($sumPaidStmt->fetch()['s'] ?? 0.0);

$pending = max(0.0, round(((float)$d['total']) - $paid_total, 2));
$locked = ($pending <= 0.00001) || ($d['status'] === 'paid');

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

if($_SERVER['REQUEST_METHOD']==='POST'){
  csrf_check();
  $action=$_POST['action'] ?? 'save';

  if($action === 'add_payment'){
    $amt=(float)str_replace(',','.', $_POST['amount'] ?? '0');
    $date=$_POST['paid_at'] ?? date('Y-m-d');
    $note=trim($_POST['note'] ?? '');

    if($amt <= 0){
      flash_set('danger','El importe debe ser mayor que 0.');
      redirect('facturas/edit.php?id='.$id);
    }

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

    $sumPaidStmt->execute([$id]);
    $paid_total=(float)($sumPaidStmt->fetch()['s'] ?? 0.0);
    $pending = max(0.0, round(((float)$d['total']) - $paid_total, 2));

    if($pending <= 0.00001){
      $pdo->prepare("UPDATE documents SET status='paid' WHERE id=?")->execute([$id]);
    }

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

  if($action === 'save'){
    if($locked){
      flash_set('danger','Esta factura está pagada al 100% y no se puede modificar.');
      redirect('facturas/edit.php?id='.$id);
    }

    $client_id=(int)($_POST['client_id']??0);
    $issue_date=$_POST['issue_date']??$d['issue_date'];
    $due_date=trim($_POST['due_date']??'');
    $status=$_POST['status']??'draft';
    $notes=trim($_POST['notes']??'');

    $desc=$_POST['desc']??[]; $qty=$_POST['qty']??[]; $price=$_POST['price']??[]; $vat=$_POST['vat']??[];
    $newLines=[];
    for($i=0;$i<count($desc);$i++){
      $dd=trim($desc[$i]??''); if($dd==='') continue;
      $newLines[]=[
        'description'=>$dd,
        'qty'=>(float)str_replace(',','.', $qty[$i]??'1'),
        'unit_price'=>(float)str_replace(',','.', $price[$i]??'0'),
        'vat_rate'=>(int)($vat[$i]??21)
      ];
    }

    if($client_id<=0){ flash_set('danger','Selecciona un cliente.'); redirect('facturas/edit.php?id='.$id); }
    if(count($newLines)===0){ flash_set('danger','Añade al menos una línea.'); redirect('facturas/edit.php?id='.$id); }

    $calc=calc_totals($newLines);

    $pdo->beginTransaction();
    try{
      $pdo->prepare("UPDATE documents SET client_id=?, issue_date=?, due_date=?, status=?, notes=?, subtotal=?, tax_total=?, total=? WHERE id=?")
          ->execute([$client_id,$issue_date,$due_date?:null,$status,$notes?:null,$calc['subtotal'],$calc['tax_total'],$calc['total'],$id]);

      $pdo->prepare("DELETE FROM document_lines WHERE document_id=?")->execute([$id]);
      $ins=$pdo->prepare("INSERT INTO document_lines(document_id,line_no,description,qty,unit_price,vat_rate,line_subtotal,line_tax,line_total)
                          VALUES(?,?,?,?,?,?,?,?,?)");
      $n=1;
      foreach($calc['lines'] as $ln){
        $ins->execute([$id,$n++,$ln['description'],$ln['qty'],$ln['unit_price'],$ln['vat_rate'],$ln['line_subtotal'],$ln['line_tax'],$ln['line_total']]);
      }
      $pdo->commit();
      flash_set('success','Factura actualizada.');
      redirect('facturas/edit.php?id='.$id);
    }catch(Throwable $e){
      $pdo->rollBack(); throw $e;
    }
  }
}

// Recalcular por si cambió
$sumPaidStmt->execute([$id]);
$paid_total=(float)($sumPaidStmt->fetch()['s'] ?? 0.0);
$pending = max(0.0, round(((float)$d['total']) - $paid_total, 2));
$locked = ($pending <= 0.00001) || ($d['status'] === 'paid');

$base = (isset($_SERVER['HTTPS'])?'https':'http').'://'.$_SERVER['HTTP_HOST'];
$pdf_url = $base . "/facturas/pdf.php?id=" . $id;
$mailto = "mailto:?subject=" . rawurlencode("Factura " . $d['doc_code']) . "&body=" . rawurlencode("Hola, te paso el enlace al PDF: " . $pdf_url);
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="mb-0"><?= h($d['doc_code']) ?></h4>
    <div class="text-muted">Factura — IVA por línea</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) ?>">Ver PDF</a>
    <a class="btn btn-outline-secondary" href="<?= h($mailto) ?>">Enviar por email</a>
    <a class="btn btn-outline-secondary" href="<?= url('facturas/list.php') ?>">Volver</a>
  </div>
</div>

<?php if($locked): ?>
  <div class="alert alert-warning">
    Esta factura está <b>pagada al 100%</b> y queda bloqueada (no se pueden editar líneas ni totales).
  </div>
<?php endif; ?>

<div class="row g-3">
  <div class="col-lg-8">
    <div class="card shadow-sm"><div class="card-body">
      <form method="post">
        <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
        <input type="hidden" name="action" value="save">

        <div class="row g-3">
          <div class="col-lg-6">
            <label class="form-label">Cliente</label>
            <select class="form-select" name="client_id" <?= $locked?'disabled':'' ?> required>
              <?php foreach($clients as $c): $cid=(int)$c['id']; ?>
                <option value="<?= $cid ?>" <?= $cid===(int)$d['client_id']?'selected':'' ?>><?= h(trim($c['nombre'].' '.$c['apellidos'])) ?></option>
              <?php endforeach; ?>
            </select>
            <?php if($locked): ?><input type="hidden" name="client_id" value="<?= (int)$d['client_id'] ?>"><?php endif; ?>
          </div>
          <div class="col-lg-3">
            <label class="form-label">Fecha</label>
            <input class="form-control" type="date" name="issue_date" value="<?= h($d['issue_date']) ?>" <?= $locked?'disabled':'' ?>>
            <?php if($locked): ?><input type="hidden" name="issue_date" value="<?= h($d['issue_date']) ?>"><?php endif; ?>
          </div>
          <div class="col-lg-3">
            <label class="form-label">Vencimiento</label>
            <input class="form-control" type="date" name="due_date" value="<?= h($d['due_date']??'') ?>" <?= $locked?'disabled':'' ?>>
            <?php if($locked): ?><input type="hidden" name="due_date" value="<?= h($d['due_date']??'') ?>"><?php endif; ?>
          </div>
          <div class="col-lg-3">
            <label class="form-label">Estado</label>
            <select class="form-select" name="status" <?= $locked?'disabled':'' ?>>
              <?php foreach(['draft','sent','paid','cancelled'] as $s): ?>
                <option value="<?= $s ?>" <?= $s===$d['status']?'selected':'' ?>><?= h($s) ?></option>
              <?php endforeach; ?>
            </select>
            <?php if($locked): ?><input type="hidden" name="status" value="<?= h($d['status']) ?>"><?php endif; ?>
          </div>

          <div class="col-12">
            <label class="form-label">Líneas</label>
            <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>IVA</th><th></th></tr></thead>
                <tbody id="lines"></tbody>
              </table>
            </div>
            <?php if(!$locked): ?>
              <button type="button" class="btn btn-outline-primary btn-sm" id="btnAddLine">+ Añadir línea</button>
            <?php endif; ?>
          </div>

          <div class="col-12">
            <label class="form-label">Notas</label>
            <textarea class="form-control" name="notes" rows="3" <?= $locked?'disabled':'' ?>><?= h($d['notes']??'') ?></textarea>
            <?php if($locked): ?><input type="hidden" name="notes" value="<?= h($d['notes']??'') ?>"><?php endif; ?>
          </div>

          <div class="col-12">
            <div class="p-3 bg-light border rounded-3 d-flex gap-4 flex-wrap">
              <div><div class="small text-muted">Subtotal</div><div class="fw-semibold"><?= number_format((float)$d['subtotal'],2,',','.') ?> €</div></div>
              <div><div class="small text-muted">IVA</div><div class="fw-semibold"><?= number_format((float)$d['tax_total'],2,',','.') ?> €</div></div>
              <div><div class="small text-muted">Total</div><div class="fw-semibold"><?= number_format((float)$d['total'],2,',','.') ?> €</div></div>
            </div>
          </div>

          <?php if(!$locked): ?>
            <div class="col-12 d-flex gap-2"><button class="btn btn-primary">Guardar cambios</button></div>
          <?php endif; ?>
        </div>
      </form>
    </div></div>
  </div>

  <div class="col-lg-4">
    <div class="card shadow-sm"><div class="card-body">
      <h6 class="mb-2">Pagos / Entregas a cuenta</h6>
      <div class="p-3 bg-light border rounded-3 mb-3">
        <div class="d-flex justify-content-between"><span class="text-muted">Total pagado</span><b><?= number_format($paid_total,2,',','.') ?> €</b></div>
        <div class="d-flex justify-content-between"><span class="text-muted">Pendiente</span><b><?= number_format($pending,2,',','.') ?> €</b></div>
      </div>

      <?php if(!$locked): ?>
      <form method="post" class="mb-3">
        <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
        <input type="hidden" name="action" value="add_payment">
        <div class="mb-2">
          <label class="form-label">Fecha</label>
          <input class="form-control" type="date" name="paid_at" value="<?= h(date('Y-m-d')) ?>">
        </div>
        <div class="mb-2">
          <label class="form-label">Importe</label>
          <input class="form-control" name="amount" placeholder="Ej: 100,00" required>
        </div>
        <div class="mb-2">
          <label class="form-label">Nota</label>
          <input class="form-control" name="note" placeholder="Ej: entrega en efectivo">
        </div>
        <button class="btn btn-outline-primary w-100">Añadir pago</button>
      </form>
      <?php endif; ?>

      <div class="fw-semibold mb-2">Historial</div>
      <div class="table-responsive">
        <table class="table table-sm">
          <thead><tr><th>Fecha</th><th class="text-end">Importe</th></tr></thead>
          <tbody>
          <?php foreach($payments as $p): ?>
            <tr>
              <td><?= h($p['paid_at']) ?></td>
              <td class="text-end"><?= number_format((float)$p['amount'],2,',','.') ?> €</td>
            </tr>
          <?php endforeach; ?>
          <?php if(count($payments)===0): ?>
            <tr><td colspan="2" class="text-muted">Sin pagos todavía.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>

      <?php if($locked): ?>
        <div class="text-muted small">Si necesitas corregir una factura pagada, lo correcto en España es emitir una factura rectificativa.</div>
      <?php endif; ?>
    </div></div>
  </div>
</div>

<script>
const LOCKED = <?= json_encode($locked) ?>;

function addLine(desc='', qty='1', price='0.00', vat='21'){
  const tbody=document.getElementById('lines');
  const tr=document.createElement('tr');
  tr.innerHTML = `
    <td style="width:45%"><input class="form-control form-control-sm" name="desc[]" value="${desc.replaceAll('"','&quot;')}" ${LOCKED?'disabled':'required'}></td>
    <td style="width:12%"><input class="form-control form-control-sm text-end" name="qty[]" value="${qty}" ${LOCKED?'disabled':''}></td>
    <td style="width:14%"><input class="form-control form-control-sm text-end" name="price[]" value="${price}" ${LOCKED?'disabled':''}></td>
    <td style="width:14%">
      <select class="form-select form-select-sm" name="vat[]" ${LOCKED?'disabled':''}>
        <option value="21" ${vat=='21'?'selected':''}>21%</option>
        <option value="10" ${vat=='10'?'selected':''}>10%</option>
        <option value="4"  ${vat=='4'?'selected':''}>4%</option>
        <option value="0"  ${vat=='0'?'selected':''}>0%</option>
      </select>
    </td>
    <td style="width:10%" class="text-end">
      ${LOCKED ? '' : '<button type="button" class="btn btn-sm btn-outline-danger" onclick="this.closest(\'tr\').remove();">X</button>'}
    </td>
  `;
  tbody.appendChild(tr);
}
<?php foreach($lines as $ln): ?>
addLine(<?= json_encode($ln['description']) ?>, <?= json_encode((string)$ln['qty']) ?>, <?= json_encode(number_format((float)$ln['unit_price'],2,'.','')) ?>, <?= json_encode((string)$ln['vat_rate']) ?>);
<?php endforeach; ?>
<?php if(!$lines): ?>addLine('Servicio', '1', '0.00', '21');<?php endif; ?>

document.getElementById('btnAddLine')?.addEventListener('click', ()=>addLine());
</script>

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