<?php
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/docs.php';
require_once __DIR__ . '/pdf_engine.php';

function eur_pdf(float $n): string { return number_format($n, 2, ',', '.') . " €"; }

function company_block(array $co): array {
  $lines = [];
  $lines[] = trim((string)($co['company_name'] ?? 'TU EMPRESA'));
  if (!empty($co['nif_cif'])) $lines[] = "NIF/CIF: ".$co['nif_cif'];
  if (!empty($co['address'])) $lines[] = $co['address'];
  $extra=[];
  if (!empty($co['phone'])) $extra[] = "Tel: ".$co['phone'];
  if (!empty($co['email'])) $extra[] = "Email: ".$co['email'];
  if ($extra) $lines[] = implode(" · ", $extra);
  if (!empty($co['iban'])) $lines[] = "IBAN: ".$co['iban'];
  return $lines;
}

function render_document_pdf(int $doc_id){
  ensure_part2_tables();
  ensure_schema_safe();
  $pdo=db();

  $co = get_company();
  $logo_jpeg = null;
  if (!empty($co['logo_path'])) {
    $abs = $_SERVER['DOCUMENT_ROOT'] . $co['logo_path'];
    $logo_jpeg = pdf_load_jpeg($abs, 'Im1');
  }

  $doc=$pdo->prepare("SELECT d.*, c.nombre, c.apellidos, c.direccion, c.nif_cif, c.postal_code, c.localidad, c.provincia
                      FROM documents d JOIN clients c ON c.id=d.client_id WHERE d.id=?");
  $doc->execute([$doc_id]);
  $d=$doc->fetch();
  if(!$d){ http_response_code(404); exit('Documento no encontrado'); }

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

  $y=800; $c="";

  if ($logo_jpeg) {
    $targetW = 120.0;
    $ratio = $logo_jpeg['h'] / max(1, $logo_jpeg['w']);
    $targetH = $targetW * $ratio;
    $x = 40.0;
    $yImg = 842 - 40 - $targetH;
    $c .= pdf_image_do('Im1', $x, $yImg, $targetW, $targetH);
  }

  $coLines = company_block($co);
  $yy = 800;
  foreach($coLines as $ln){ $c .= pdf_text(320, $yy, $ln, 10); $yy -= 12; }

  $title = doc_type_label($d['doc_type'])." ".$d['doc_code'];
  if (!empty($d['is_rectificativa'])) $title = "Factura rectificativa ".$d['doc_code'];
  $c .= pdf_text(40,$y,$title,16); $y-=26;

  if (!empty($d['is_rectificativa']) && !empty($d['rectifies_invoice_id'])) {
    // mostrar referencia a la original
    $orig=$pdo->prepare("SELECT doc_code FROM documents WHERE id=?");
    $orig->execute([(int)$d['rectifies_invoice_id']]);
    $o=$orig->fetch();
    if($o && !empty($o['doc_code'])){
      $c .= pdf_text(40,$y,"Rectifica a: ".$o['doc_code'],10); $y-=16;
    }
  }

  $cliente = trim(($d['nombre']??'')." ".($d['apellidos']??''));
  $c .= pdf_text(40,$y,"Cliente: ".$cliente,11); $y-=14;
  if(!empty($d['nif_cif'])){ $c .= pdf_text(40,$y,"NIF/CIF: ".$d['nif_cif'],10); $y-=14; }

  $addrParts=[];
  if(!empty($d['direccion'])) $addrParts[] = $d['direccion'];
  $cpLoc = trim(($d['postal_code']??'')." ".($d['localidad']??''));
  if($cpLoc) $addrParts[] = $cpLoc;
  if(!empty($d['provincia'])) $addrParts[] = $d['provincia'];
  if($addrParts){ $c .= pdf_text(40,$y,"Dirección: ".implode(", ", $addrParts),10); $y-=18; }

  $c .= pdf_text(40,$y,"Fecha: ".$d['issue_date'],10);
  if(!empty($d['due_date'])) $c .= pdf_text(200,$y,"Venc.: ".$d['due_date'],10);
  $y-=16;

  $c .= pdf_line(40,$y,555,$y); $y-=16;
  $c .= pdf_text(40,$y,"Concepto",10);
  $c .= pdf_text(330,$y,"Cant.",10);
  $c .= pdf_text(380,$y,"Precio",10);
  $c .= pdf_text(445,$y,"IVA",10);
  $c .= pdf_text(500,$y,"Total",10);
  $y-=10; $c .= pdf_line(40,$y,555,$y); $y-=14;

  foreach($lines as $ln){
    $desc=(string)($ln['description']??'');
    $qty=(float)($ln['qty']??1);
    $unit=(float)($ln['unit_price']??0);
    $vat=(int)($ln['vat_rate']??21);
    $tot=(float)($ln['line_total']??0);

    $c .= pdf_text(40,$y,$desc,10);
    $c .= pdf_text(330,$y,rtrim(rtrim(number_format($qty,3,',','.'),'0'),','),10);
    $c .= pdf_text(380,$y,eur_pdf($unit),10);
    $c .= pdf_text(445,$y,$vat.'%',10);
    $c .= pdf_text(500,$y,eur_pdf($tot),10);
    $y-=12;
    if($y < 140) break;
  }

  $y-=10; $c .= pdf_line(340,$y,555,$y); $y-=14;
  $c .= pdf_text(370,$y,"Subtotal:",10);
  $c .= pdf_text(500,$y,eur_pdf((float)$d['subtotal']),10); $y-=12;
  $c .= pdf_text(370,$y,"IVA:",10);
  $c .= pdf_text(500,$y,eur_pdf((float)$d['tax_total']),10); $y-=12;
  $c .= pdf_text(370,$y,"TOTAL:",11);
  $c .= pdf_text(500,$y,eur_pdf((float)$d['total']),11);

  if (!empty($co['footer_note'])) $c .= pdf_text(40, 40, (string)$co['footer_note'], 9);

  $pdf = pdf_build_onepage($c, $logo_jpeg);
  header('Content-Type: application/pdf');
  header('Content-Disposition: inline; filename="'.$d['doc_code'].'.pdf"');
  echo $pdf;
  exit;
}
