<?php
/**
 * Slice 8S-10 · Add realistic services overheads to the Vodacom Tower PM sample tender.
 *
 * Idempotent — skips any overhead line whose label already exists on the DRAFT
 * pricing version. Safe to re-run.
 *
 * Adds 4 categories a Services bid typically needs:
 *   MANPOWER   · FS crew retainer (2 techs × 24 months)
 *   EQUIPMENT  · FS vehicles (2 pickups) + toolbox + diagnostics
 *   TRANSPORT  · Fuel float + mileage across 50 sites
 *   OTHER      · Consumables outside client spare-pack (rags, cleaners, PPE, spares buffer)
 *   ADMIN_OVERHEAD · PM + NOC + admin allocation
 */
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','TenderPricing.php','PricingVersionOverheads.php'] as $m) {
    require_once ROOT . DS . 'app' . DS . 'models' . DS . $m;
}

$db  = new DB();
$pvo = new PricingVersionOverheads();
$tp  = new TenderPricing();

$row = $db->mySelect("SELECT c0d FROM tender_tracker WHERE tender_title LIKE 'DEMO-SVC · Vodacom%'", []);
if (empty($row)) { echo "✗ Vodacom sample tender not found — run seed_demo_services_tender.php first.\n"; exit(1); }
$tenderId = (int)$row[0]['c0d'];

$vRow = $db->mySelect("SELECT c0d FROM tender_pricing_versions WHERE tender_id = :t AND status = 'DRAFT' ORDER BY c0d DESC LIMIT 1", [':t' => $tenderId]);
if (empty($vRow)) { echo "✗ No DRAFT pricing version for tender {$tenderId}.\n"; exit(1); }
$versionId = (int)$vRow[0]['c0d'];

echo "Tender {$tenderId} · pricing version {$versionId}\n";

/* 24-month contract; each amount below is TOTAL over the contract period. */
$overheads = [
    ['category' => 'MANPOWER',       'label' => 'FS crew retainer (2 technicians × 24 months)', 'amount' => 33600000, 'display_mode' => 'DISTRIBUTED',   'notes' => '700,000 TZS/tech/month × 2 techs × 24 months'],
    ['category' => 'EQUIPMENT',      'label' => 'FS vehicles (2× pickup) + fuel',              'amount' => 24000000, 'display_mode' => 'DISTRIBUTED',   'notes' => 'Lease 500,000/veh/month × 2 × 24 months'],
    ['category' => 'EQUIPMENT',      'label' => 'Toolbox + diagnostic gear (2 kits)',          'amount' =>  4800000, 'display_mode' => 'PRELIMS_LINE',  'notes' => 'One-off allocation — multimeters, torque wrenches, IR thermometer, oil analysers'],
    ['category' => 'TRANSPORT',      'label' => 'Site travel float (fuel + tolls)',            'amount' =>  8640000, 'display_mode' => 'DISTRIBUTED',   'notes' => '~360,000/month across 50 sites × 24 months'],
    ['category' => 'OTHER',          'label' => 'Adhoc consumables outside client spare-pack', 'amount' =>  3600000, 'display_mode' => 'INTERNAL_ONLY', 'notes' => 'Rags, cleaners, PPE, small-parts buffer (150,000/month)'],
    ['category' => 'ADMIN_OVERHEAD', 'label' => 'PM + NOC + admin allocation',                 'amount' =>  7200000, 'display_mode' => 'INTERNAL_ONLY', 'notes' => 'PM 15% + NOC coverage + admin — 300,000/month × 24 months'],
];

$existingLabels = array_map(fn($r) => strtolower((string)$r['label']), $pvo->listFor($versionId));
$added = 0; $skipped = 0;

foreach ($overheads as $oh) {
    if (in_array(strtolower($oh['label']), $existingLabels, true)) {
        echo "  · skip (exists) · {$oh['label']}\n";
        $skipped++;
        continue;
    }
    $res = $pvo->add($versionId, $tenderId, $oh, 999, 'Demo Seeder');
    if ($res['ok']) {
        echo "  ✓ added · {$oh['category']} · {$oh['label']} · " . number_format((float)$oh['amount']) . " TZS\n";
        $added++;
    } else {
        echo "  ✗ failed · {$oh['label']} · " . ($res['msg'] ?? '') . "\n";
    }
}

/* Roll up so version.sum_overhead / sum_cost / sum_price reflect the new overheads */
if ($added > 0) {
    $tp->rollupVersion($versionId);
    echo "  → rolled up version totals\n";
}

$vAfter = $db->mySelect("SELECT sum_cost, sum_overhead, sum_price, margin_pct FROM tender_pricing_versions WHERE c0d = :v", [':v' => $versionId]);
if (!empty($vAfter)) {
    $v = $vAfter[0];
    printf("\nVersion totals: cost=%s · overhead=%s · sell=%s · margin=%.1f%%\n",
        number_format((float)$v['sum_cost']),
        number_format((float)$v['sum_overhead']),
        number_format((float)$v['sum_price']),
        (float)$v['margin_pct']);
}
echo "\nAdded {$added}, skipped {$skipped}. Open: http://localhost/rsflow.dspera/Tenders/view/{$tenderId}#tab-pricing\n";
