<?php
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', dirname(__DIR__));
if (!defined('DB_HOST'))     define('DB_HOST', 'localhost');
if (!defined('DB_NAME'))     define('DB_NAME', 'rookpmgt_rsflow');
if (!defined('DB_USER'))     define('DB_USER', 'root');
if (!defined('DB_PASSWORD')) define('DB_PASSWORD', '');
if (!defined('DB_PASS'))     define('DB_PASS', '');
require_once ROOT . '/core/DB.php';
require_once ROOT . '/core/Model.php';
require_once ROOT . '/core/FPDF.php';
require_once ROOT . '/app/models/AssetTypes.php';
require_once ROOT . '/app/models/SpareParts.php';
require_once ROOT . '/app/models/PmTemplates.php';
require_once ROOT . '/app/models/ServiceContracts.php';
require_once ROOT . '/app/models/Callouts.php';
require_once ROOT . '/app/models/PmServices.php';
require_once ROOT . '/app/models/RsPdfReport.php';
require_once ROOT . '/app/models/ServiceReports.php';

$pdo = new PDO('mysql:host=localhost;dbname=rookpmgt_rsflow;charset=utf8mb4', 'root', '');
// Clean prior
$pdo->exec("DELETE FROM callout_parts_used WHERE callout_id IN (SELECT c0d FROM callouts WHERE contract_id IN (SELECT c0d FROM service_contracts WHERE customer_name='SMOKE-S8'))");
$pdo->exec("DELETE FROM callouts WHERE contract_id IN (SELECT c0d FROM service_contracts WHERE customer_name='SMOKE-S8')");
$pdo->exec("DELETE FROM pm_service_findings WHERE pm_service_id IN (SELECT c0d FROM pm_services WHERE contract_id IN (SELECT c0d FROM service_contracts WHERE customer_name='SMOKE-S8'))");
$pdo->exec("DELETE FROM pm_services WHERE contract_id IN (SELECT c0d FROM service_contracts WHERE customer_name='SMOKE-S8')");
$pdo->exec("DELETE FROM service_contract_pm_schedule WHERE contract_id IN (SELECT c0d FROM service_contracts WHERE customer_name='SMOKE-S8')");
$pdo->exec("DELETE FROM service_contract_assets WHERE contract_id IN (SELECT c0d FROM service_contracts WHERE customer_name='SMOKE-S8')");
$pdo->exec("DELETE FROM service_contract_sites WHERE contract_id IN (SELECT c0d FROM service_contracts WHERE customer_name='SMOKE-S8')");
$pdo->exec("DELETE FROM service_contracts WHERE customer_name='SMOKE-S8'");
$pdo->exec("DELETE FROM pm_template_items WHERE template_id IN (SELECT c0d FROM pm_templates WHERE code='SMOKE_S8')");
$pdo->exec("DELETE FROM pm_templates WHERE code='SMOKE_S8'");
$pdo->exec("DELETE FROM spare_parts WHERE sku='SMOKE-S8-OIL'");

$types = (new AssetTypes())->all(true);
$genId = 0; foreach ($types as $t) if ($t['code']==='GEN') { $genId=(int)$t['c0d']; break; }

// Seed spare
$parts = new SpareParts();
$partId = $parts->save(['sku'=>'SMOKE-S8-OIL','name'=>'15W40 Oil 5L','uom'=>'L','asset_type_id'=>$genId,'unit_cost'=>25000,'default_markup_pct'=>25,'is_active'=>1], 0);

// Seed template
$tpl = new PmTemplates();
$tid = $tpl->saveHeader(['code'=>'SMOKE_S8','name'=>'S8 Smoke','asset_type_id'=>$genId,'scope'=>'ASSET','cadence_type'=>'MONTHS','cadence_value'=>3,'is_active'=>1], 0);
$tpl->saveItem(['template_id'=>$tid,'sort_order'=>1,'section'=>'Engine','task'=>'Oil check','input_type'=>'CHECK','is_required'=>0]);

// Contract + site + asset
$proj = $pdo->query('SELECT c0d FROM c_projects WHERE deleted=0 ORDER BY c0d DESC LIMIT 1')->fetch(PDO::FETCH_ASSOC);
$sc = new ServiceContracts();
$cid = $sc->saveHeader([
    'project_id'=>(int)$proj['c0d'], 'customer_name'=>'SMOKE-S8', 'customer_id'=>1,
    'contract_value'=>12000000, 'currency'=>'TZS', 'monthly_retainer'=>500000,
    'spare_policy'=>'COMPANY', 'invoice_cadence'=>'CONSUMPTION',
    'labour_rate_per_hr'=>50000, 'callout_fee'=>150000, 'emergency_multiplier'=>2,
    'parts_markup_pct'=>25, 'mileage_rate_per_km'=>1500, 'free_callouts_per_month'=>1,
], 0, 'smoke');
$sid = $sc->saveSite(['contract_id'=>$cid,'name'=>'Kariakoo Branch','region'=>'Dar','is_active'=>1]);
$aid = $sc->saveAsset(['contract_id'=>$cid,'site_id'=>$sid,'asset_type_id'=>$genId,'asset_no'=>'GEN-S8','size_value'=>75,'size_unit'=>'kVA','is_active'=>1]);
$sc->activate($cid, 0);

// Seed 2 callouts (one emergency), current month
$catRow = $pdo->query("SELECT c0d FROM callout_categories WHERE code='URGENT'")->fetch(PDO::FETCH_ASSOC);
$catId = (int)$catRow['c0d'];
$co = new Callouts();
$year = (int)date('Y'); $mo = (int)date('n');
$mid = sprintf('%04d-%02d-10 08:00:00', $year, $mo);
$mid2 = sprintf('%04d-%02d-20 08:00:00', $year, $mo);

$coId1 = $co->saveIntake(['contract_id'=>$cid,'category_id'=>$catId,'site_id'=>$sid,'asset_id'=>$aid,'reported_by_name'=>'Client A','reported_at'=>$mid,'description'=>'Genset noise','is_emergency'=>0], 0, 'smoke');
$co->dispatch($coId1, 0, 'FS Musa');
$co->arrive($coId1);
$co->resolve($coId1, ['resolution_description'=>'Adjusted valve','labour_hrs'=>1.5,'mileage_km'=>12]);
$pdo->exec("UPDATE callouts SET resolved_at='$mid' WHERE c0d=$coId1");

$coId2 = $co->saveIntake(['contract_id'=>$cid,'category_id'=>$catId,'site_id'=>$sid,'asset_id'=>$aid,'reported_by_name'=>'Client B','reported_at'=>$mid2,'description'=>'Fuel pump failure','is_emergency'=>1], 0, 'smoke');
$co->dispatch($coId2, 0, 'FS Ali');
$co->arrive($coId2);
$co->resolve($coId2, ['resolution_description'=>'Replaced fuel pump','labour_hrs'=>3.0,'mileage_km'=>18]);
$co->addPart($coId2, ['part_id'=>$partId,'qty'=>5,'source'=>'STOCK']);
$pdo->exec("UPDATE callouts SET resolved_at='$mid2' WHERE c0d=$coId2");

// Seed 1 finished PM
$ps = new PmServices();
$pmId = $ps->spawn($aid, $tid, null, $mid);
$ps->start($pmId, ['ppe_confirmed'=>1], 0, 'FS Musa');
$ps->finish($pmId, 'All OK', 0, 'FS Musa');
$pdo->exec("UPDATE pm_services SET finished_at='$mid' WHERE c0d=$pmId");

// Build the report
$report = new ServiceReports();
$pdf = $report->build($cid, $year, $mo);
$outPath = ROOT . '/scripts/smoke_s8_report.pdf';
$pdf->Output('F', $outPath);

// Verify PDF file exists and starts with %PDF
$size = filesize($outPath);
$fp = fopen($outPath, 'rb'); $header = fread($fp, 5); fclose($fp);
echo 'PDF generated: ' . $outPath . PHP_EOL;
echo '  size: ' . number_format($size) . ' bytes' . PHP_EOL;
echo '  header: ' . $header . ' (expected %PDF-)' . PHP_EOL;
echo '  status: ' . ($header === '%PDF-' ? 'VALID PDF' : 'BAD HEADER') . PHP_EOL;

// Cleanup
$pdo->exec("DELETE FROM callout_parts_used WHERE callout_id IN ($coId1, $coId2)");
$pdo->exec("DELETE FROM callouts WHERE c0d IN ($coId1, $coId2)");
$pdo->exec("DELETE FROM pm_services WHERE c0d=$pmId");
$pdo->exec("DELETE FROM service_contract_pm_schedule WHERE contract_id=$cid");
$pdo->exec("DELETE FROM service_contract_assets WHERE contract_id=$cid");
$pdo->exec("DELETE FROM service_contract_sites WHERE contract_id=$cid");
$pdo->exec("DELETE FROM service_contracts WHERE c0d=$cid");
$pdo->exec("DELETE FROM pm_template_items WHERE template_id=$tid");
$pdo->exec("DELETE FROM pm_templates WHERE c0d=$tid");
$pdo->exec("DELETE FROM spare_parts WHERE c0d=$partId");
// Keep the PDF for you to inspect — comment out unlink if you want to see it
// unlink($outPath);
echo PHP_EOL . 'Cleanup done (PDF preserved for inspection).' . PHP_EOL;
