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

function eur(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();
  $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="";

  // Logo (solo JPG) arriba izquierda
  if ($logo_jpeg) {
    // dibujamos en el contenido: 120px ancho
    $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);
  }

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

  $c .= pdf_text(40,$y,doc_type_label($d['doc_type'])." ".$d['doc_code'],16); $y-=26;

  // Datos cliente
  $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($unit),10);
    $c .= pdf_text(445,$y,$vat.'%',10);
    $c .= pdf_text(500,$y,eur($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((float)$d['subtotal']),10); $y-=12;
  $c .= pdf_text(370,$y,"IVA:",10);
  $c .= pdf_text(500,$y,eur((float)$d['tax_total']),10); $y-=12;
  $c .= pdf_text(370,$y,"TOTAL:",11);
  $c .= pdf_text(500,$y,eur((float)$d['total']),11);

  // Pie
  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;
}
