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

$client_id=(int)($_GET['client_id']??0);
$clients=db()->query("SELECT id,nombre,apellidos FROM clients ORDER BY nombre ASC")->fetchAll();

if($_SERVER['REQUEST_METHOD']==='POST'){
  csrf_check();
  $client_id=(int)($_POST['client_id']??0);
  $issue_date=$_POST['issue_date']??date('Y-m-d');
  $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']??[];
  $lines=[];
  for($i=0;$i<count($desc);$i++){ $d=trim($desc[$i]??''); if($d==='') continue;
    $lines[]=['description'=>$d,'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/new.php'); }
  if(count($lines)===0){ flash_set('danger','Añade al menos una línea.'); redirect('facturas/new.php?client_id='.$client_id); }

  $seq=next_doc_code('invoice'); $calc=calc_totals($lines);
  $pdo=db(); $pdo->beginTransaction();
  try{
    $pdo->prepare("INSERT INTO documents(doc_type,series_prefix,series_number,doc_code,client_id,issue_date,due_date,status,notes,subtotal,tax_total,total)
                  VALUES('invoice',?,?,?,?,?,?,?,?,?,?,?)")
        ->execute([$seq['prefix'],$seq['number'],$seq['code'],$client_id,$issue_date,$due_date?:null,$status,$notes?:null,$calc['subtotal'],$calc['tax_total'],$calc['total']]);
    $doc_id=(int)$pdo->lastInsertId();
    $lin=$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){ $lin->execute([$doc_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 creada.');
    redirect('facturas/edit.php?id='.$doc_id);
  }catch(Throwable $e){ $pdo->rollBack(); throw $e; }
}
?>
<div class="card shadow-sm"><div class="card-body">
  <div class="d-flex justify-content-between align-items-center">
    <h5 class="mb-0">Nueva factura</h5>
    <a class="btn btn-outline-secondary" href="<?= url('facturas/list.php') ?>">Volver</a>
  </div><hr>
  <form method="post">
    <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
    <div class="row g-3">
      <div class="col-lg-6">
        <label class="form-label">Cliente</label>
        <select class="form-select" name="client_id" required>
          <option value="">-- Selecciona --</option>
          <?php foreach($clients as $c): $cid=(int)$c['id']; ?>
            <option value="<?= $cid ?>" <?= $cid===$client_id?'selected':'' ?>><?= h(trim($c['nombre'].' '.$c['apellidos'])) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-lg-3"><label class="form-label">Fecha</label><input class="form-control" type="date" name="issue_date" value="<?= h(date('Y-m-d')) ?>"></div>
      <div class="col-lg-3"><label class="form-label">Vencimiento (opcional)</label><input class="form-control" type="date" name="due_date"></div>
      <div class="col-lg-3">
        <label class="form-label">Estado</label>
        <select class="form-select" name="status">
          <option value="draft">draft</option><option value="sent">sent</option><option value="paid">paid</option><option value="cancelled">cancelled</option>
        </select>
      </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>
        <button type="button" class="btn btn-outline-primary btn-sm" id="btnAddLine">+ Añadir línea</button>
      </div>
      <div class="col-12"><label class="form-label">Notas (opcional)</label><textarea class="form-control" name="notes" rows="3"></textarea></div>
      <div class="col-12 d-flex gap-2"><button class="btn btn-primary">Guardar</button><a class="btn btn-outline-secondary" href="<?= url('facturas/list.php') ?>">Cancelar</a></div>
    </div>
  </form>
</div></div>
<script>
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;')}" required></td>
    <td style="width:12%"><input class="form-control form-control-sm text-end" name="qty[]" value="${qty}"></td>
    <td style="width:14%"><input class="form-control form-control-sm text-end" name="price[]" value="${price}"></td>
    <td style="width:14%">
      <select class="form-select form-select-sm" name="vat[]">
        <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"><button type="button" class="btn btn-sm btn-outline-danger" onclick="this.closest('tr').remove();">X</button></td>
  `;
  tbody.appendChild(tr);
}
document.getElementById('btnAddLine')?.addEventListener('click', ()=>addLine());
</script>
<script>addLine('Servicio / producto','1','0.00','21');</script>
<?php require_once __DIR__ . '/../inc/footer.php'; ?>
