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

/**
 * PDF layout (A4) with:
 * - Logo top-left (no overlap)
 * - Company block under logo (left column)
 * - Client block top-right (right column) + document number
 * - Stable table below
 */

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

function safe_trunc(string $s, int $maxChars): string {
  if (function_exists('mb_strlen') && function_exists('mb_substr')) {
    if (mb_strlen($s, 'UTF-8') <= $maxChars) return $s;
    return mb_substr($s, 0, max(0,$maxChars-3), 'UTF-8').'...';
  }
  $b = pdf_to_winansi($s);
  if (strlen($b) <= $maxChars) return $s;
  $b2 = substr($b, 0, max(0,$maxChars-3));
  if (function_exists('iconv')) {
    $u = @iconv('Windows-1252', 'UTF-8//IGNORE', $b2);
    if ($u !== false) return $u.'...';
  }
  return substr($s, 0, max(0,$maxChars-3)).'...';
}

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

function client_lines(array $d): array {
  $lines=[];
  $cliente = trim(($d['nombre']??'')." ".($d['apellidos']??''));
  if($cliente) $lines[]=$cliente;
  if(!empty($d['nif_cif'])) $lines[]="NIF/CIF: ".$d['nif_cif'];

  $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) $lines[] = implode(", ", $addrParts);

  return $lines;
}

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

  $img = null;
  if (!empty($co['logo_path'])) {
    $abs = $_SERVER['DOCUMENT_ROOT'] . $co['logo_path'];
    $img = pdf_load_image_any($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();

  // Page constants (points)
  $LEFT = 40;
  $RIGHT = 555;
  $TOP_Y = 812;   // text baseline near top
  $TOP_MARGIN = 32;

  $COL_GAP = 25;
  $COL_W = (595 - 2*$LEFT - $COL_GAP); // remaining width
  $LEFT_COL_X = $LEFT;
  $RIGHT_COL_X = $LEFT + ($COL_W/2) + ($COL_GAP/2);
  $RIGHT_COL_X = (int)$RIGHT_COL_X;

  $c = "";

  // --- Logo (top-left), sized to max 120w x 55h
  $logoBottomY = 0;
  if ($img) {
    $maxW = 120.0; $maxH = 55.0;
    $ratio = $img['h'] / max(1, $img['w']);
    $w = $maxW; $h = $w * $ratio;
    if ($h > $maxH) { $h = $maxH; $w = $h / $ratio; }
    $x = $LEFT_COL_X;
    $y = 842 - $TOP_MARGIN - $h;  // bottom y of logo
    $logoBottomY = $y;
    $c .= pdf_image_do('Im1', $x, $y, $w, $h);
  }

  // --- Company block UNDER logo (left column)
  $companyStartY = ($logoBottomY > 0) ? ($logoBottomY - 14) : ($TOP_Y - 10);
  $coLines = company_lines($co);
  $yy = $companyStartY;
  foreach($coLines as $i=>$ln){
    $size = ($i===0)?12:9;
    $c .= pdf_text($LEFT_COL_X, $yy, $ln, $size);
    $yy -= ($i===0)?14:11;
  }

  // --- Right column: Document label/code + Client block
  $docTitle = doc_type_label($d['doc_type'])." ".$d['doc_code'];
  if (!empty($d['is_rectificativa'])) $docTitle = "Factura rectificativa ".$d['doc_code'];

  $ry = $TOP_Y;
  $c .= pdf_text($RIGHT_COL_X, $ry, $docTitle, 14); $ry -= 18;

  if(!empty($d['issue_date'])) { $c .= pdf_text($RIGHT_COL_X, $ry, "Fecha: ".$d['issue_date'], 9); }
  if(!empty($d['due_date']))   { $c .= pdf_text($RIGHT_COL_X+170, $ry, "Venc.: ".$d['due_date'], 9); }
  $ry -= 14;

  $c .= pdf_text($RIGHT_COL_X, $ry, "Cliente:", 10); $ry -= 12;
  $cl = client_lines($d);
  foreach($cl as $i=>$ln){
    $c .= pdf_text($RIGHT_COL_X, $ry, safe_trunc($ln, 65), 9);
    $ry -= 11;
  }

  // --- Separator line under header blocks
  $headerBottom = min($yy, $ry) - 10;
  if ($headerBottom < 650) $headerBottom = 650; // keep a decent space before table
  $c .= pdf_line($LEFT, $headerBottom, $RIGHT, $headerBottom);

  // --- Table
  $y = $headerBottom - 22;

  // Columns
  $xDesc = $LEFT;
  $xQty  = 360;
  $xUnit = 410;
  $xVat  = 470;
  $xTot  = 510;

  $c .= pdf_text($xDesc, $y, "Concepto", 10);
  $c .= pdf_text($xQty,  $y, "Cant.", 10);
  $c .= pdf_text($xUnit, $y, "Precio", 10);
  $c .= pdf_text($xVat,  $y, "IVA", 10);
  $c .= pdf_text($xTot,  $y, "Total", 10);

  $y -= 10;
  $c .= pdf_line($LEFT, $y, $RIGHT, $y);
  $y -= 16;

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

    $c .= pdf_text($xDesc, $y, $desc, 10);
    $c .= pdf_text($xQty,  $y, number_format($qty,2,',','.'), 10);
    $c .= pdf_text($xUnit, $y, eur_pdf($unit), 10);
    $c .= pdf_text($xVat,  $y, $vat.'%', 10);
    $c .= pdf_text($xTot,  $y, eur_pdf($tot), 10);

    $y -= 14;
    if ($y < 170) break;
  }

  // Totals (right aligned box)
  $y -= 6;
  $c .= pdf_line(360, $y, $RIGHT, $y);
  $y -= 16;

  $c .= pdf_text(380, $y, "Subtotal:", 10);
  $c .= pdf_text($xTot, $y, eur_pdf((float)$d['subtotal']), 10); $y -= 13;

  $c .= pdf_text(380, $y, "IVA:", 10);
  $c .= pdf_text($xTot, $y, eur_pdf((float)$d['tax_total']), 10); $y -= 13;

  $c .= pdf_text(380, $y, "TOTAL:", 11);
  $c .= pdf_text($xTot, $y, eur_pdf((float)$d['total']), 11);

  // Footer note
  if (!empty($co['footer_note'])) {
    $c .= pdf_text($LEFT, 45, safe_trunc((string)$co['footer_note'], 110), 9);
  } else {
    $c .= pdf_text($LEFT, 45, "Gracias por su confianza", 9);
  }

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