<?php
/**
 * Slice 8S-10 · Dry-run the Services Walkthrough Manual PDF for tender 400.
 * Writes to scripts/output/services_walkthrough_400.pdf so we can open it locally.
 */
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', dirname(__DIR__));
require_once ROOT . DS . 'config' . DS . 'config.php';
require_once ROOT . DS . 'core' . DS . 'Application.php';
require_once ROOT . DS . 'core' . DS . 'Model.php';
require_once ROOT . DS . 'core' . DS . 'DB.php';
foreach (['Tenders.php','TenderItems.php','TenderPricing.php','TenderServiceSpec.php','PricingVersionOverheads.php','ServicesWalkthroughManual.php'] as $m) {
    require_once ROOT . DS . 'app' . DS . 'models' . DS . $m;
}

$db  = new DB();
$tid = 400;

$t = (new Tenders())->find($tid);
if (!$t) { echo "✗ tender {$tid} not found\n"; exit(1); }

$tss   = new TenderServiceSpec();
$spec  = $tss->forTender($tid);
$equip = $tss->decodedEquipment($spec);
$items = (new TenderItems())->listFor($tid);

$tp = new TenderPricing();
$vers = $db->mySelect("SELECT * FROM tender_pricing_versions WHERE tender_id = :t ORDER BY c0d DESC LIMIT 1", [':t' => $tid]);
$version = !empty($vers) ? $vers[0] : null;
$sections = []; $lines = []; $overheads = [];
if ($version) {
    $sections = $tp->sectionsFor((int)$version['c0d']);
    foreach ($sections as $s) $lines[(int)$s['c0d']] = $tp->linesFor((int)$s['c0d']);
    $overheads = (new PricingVersionOverheads())->listFor((int)$version['c0d']);
}

$pdf = ServicesWalkthroughManual::build([
    'tender'    => $t,
    'spec'      => $spec,
    'equipment' => $equip,
    'items'     => $items,
    'version'   => $version,
    'sections'  => $sections,
    'lines'     => $lines,
    'overheads' => $overheads,
]);

$outDir = ROOT . DS . 'scripts' . DS . 'output';
if (!is_dir($outDir)) mkdir($outDir, 0777, true);
$out = $outDir . DS . 'services_walkthrough_400.pdf';
file_put_contents($out, $pdf);
echo "✓ PDF built · " . strlen($pdf) . " bytes · " . $out . "\n";
