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

$id=(int)($_GET['id']??0);
$pdo=db();
$doc=$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='quote'");
$doc->execute([$id]);
$d=$doc->fetch();
if(!$d){ http_response_code(404); echo "Documento no encontrado"; 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();

if($_SERVER['REQUEST_METHOD']==='POST'){
  csrf_check();
  $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('presupuestos/edit.php?id='.$id); }
  if(count($newLines)===0){ flash_set('danger','Añade al menos una línea.'); redirect('presupuestos/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]);
    $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([$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','Documento actualizado.');
    redirect('presupuestos/edit.php?id='.$id);
  }catch(Throwable $e){ $pdo->rollBack(); throw $e; }
}

$base = (isset($_SERVER['HTTPS'])?'https':'http').'://'.$_SERVER['HTTP_HOST'];
$pdf_url = $base . "/presupuestos/pdf.php?id=" . $id;
$mailto = "mailto:?subject=" . rawurlencode("Presupuesto " . $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"><?= h(doc_type_label($d['doc_type'])) ?> — IVA por línea</div>
  </div>
  <div class="d-flex gap-2 flex-wrap">
    <a class="btn btn-outline-primary" target="_blank" href="<?= url('presupuestos/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('presupuestos/list.php') ?>">Volver</a>
  </div>
</div>

<div class="card shadow-sm"><div class="card-body">
<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>
      <?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>
  </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']) ?>"></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']??'') ?>"></div>
  <div class="col-lg-3"><label class="form-label">Estado</label>
    <select class="form-select" name="status">
      <?php foreach(['draft','sent','accepted','cancelled'] as $s): ?>
        <option value="<?= $s ?>" <?= $s===$d['status']?'selected':'' ?>><?= $s ?></option>
      <?php endforeach; ?>
    </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</label><textarea class="form-control" name="notes" rows="3"><?= h($d['notes']??'') ?></textarea></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>

  <div class="col-12 d-flex gap-2"><button class="btn btn-primary">Guardar cambios</button></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>
<?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; ?>
</script>

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