<?php
declare(strict_types=1);

// Requires TCPDF library in /vendor/tcpdf/
// Download TCPDF from official source and upload to vendor/tcpdf/

require __DIR__ . '/../db.php';
require __DIR__ . '/../helpers.php';
require __DIR__ . '/../upload.php';

require_once __DIR__ . '/../../vendor/tcpdf/tcpdf.php';

function generate_sale_contract(PDO $pdo, array $config, int $saleId, int $userId): int {
  $st = $pdo->prepare("
    SELECT s.*, v.id AS vehicle_id, v.brand, v.model, v.version, v.plate, v.vin, v.year, v.km,
           c.id AS customer_id, c.name AS customer_name, c.nif, c.address, c.postal_code, c.city
    FROM sales s
    JOIN vehicles v ON v.id=s.vehicle_id
    JOIN customers c ON c.id=s.customer_id
    WHERE s.id=?
  ");
  $st->execute([$saleId]);
  $d = $st->fetch();
  if (!$d) throw new RuntimeException('Sale not found');

  $pdf = new TCPDF('P','mm','A4',true,'UTF-8',false);
  $pdf->SetCreator('BlockSpark Automotive DMS');
  $pdf->SetAuthor('BlockSpark Automotive');
  $pdf->SetTitle('Contrato de Compra e Venda');
  $pdf->SetMargins(15,15,15);
  $pdf->AddPage();

  $html = '
  <h2>CONTRATO DE COMPRA E VENDA - VIATURA USADA</h2>
  <p><b>Vendedor:</b> BlockSpark Automotive</p>
  <p><b>Comprador:</b> '.e($d['customer_name']).' (NIF: '.e((string)$d['nif']).')</p>
  <p><b>Morada:</b> '.e(trim((string)$d['address'].' '.(string)$d['postal_code'].' '.(string)$d['city'])).'</p>
  <hr>
  <h3>Viatura</h3>
  <ul>
    <li><b>Marca/Modelo:</b> '.e(trim($d['brand'].' '.$d['model'].' '.$d['version'])).'</li>
    <li><b>Matrícula:</b> '.e((string)$d['plate']).'</li>
    <li><b>VIN:</b> '.e((string)$d['vin']).'</li>
    <li><b>Ano/KM:</b> '.e((string)$d['year']).' / '.e((string)$d['km']).'</li>
  </ul>
  <h3>Condições</h3>
  <p><b>Preço:</b> '.number_format((float)$d['sale_price'],2,',','.').' €</p>
  <p><b>Data:</b> '.e((string)$d['sale_date']).'</p>
  <p>O comprador declara ter inspecionado a viatura. Mantém-se a garantia legal aplicável e/ou garantia contratada.</p>
  <br><br>
  <table width="100%" cellpadding="10">
    <tr><td width="50%"><b>Vendedor</b><br><br>________________________</td>
        <td width="50%"><b>Comprador</b><br><br>________________________</td></tr>
  </table>
  ';

  $pdf->writeHTML($html, true, false, true, false, '');

  $vehicleId = (int)$d['vehicle_id'];
  $dir = vehicle_pdfs_dir($config, $vehicleId);
  ensure_dir($dir);

  $stored = 'contrato_venda_sale_'.$saleId.'_'.bin2hex(random_bytes(6)).'.pdf';
  $abs = rtrim($dir,'/').'/'.$stored;
  $pdf->Output($abs, 'F');

  $sha = hash_file('sha256', $abs);

  $st2 = $pdo->prepare("INSERT INTO generated_pdfs (pdf_type,vehicle_id,customer_id,sale_id,title,stored_filename,sha256,created_by) VALUES ('contrato_venda',?,?,?,?,?,?,?)");
  $st2->execute([$vehicleId,(int)$d['customer_id'],$saleId,'Contrato de Venda - '.(string)$d['plate'],$stored,$sha,$userId]);

  return (int)$pdo->lastInsertId();
}
