<?php
/**
 * Persistent Vodacom Tower PM sample — Slice 8S-10 · Services tender end-to-end.
 *
 * Creates a realistic Services tender so the CRM checklist form (Items tab) has
 * something meaningful to browse. Once created, this row is left alone — re-running
 * is a no-op if the sample already exists (matched on tender_no = 'DEMO-SVC-VODA-PM').
 *
 * What gets seeded:
 *   1. tender_tracker header (services, Vodacom Tanzania, 50 sites, PM programme)
 *   2. 4 tender_items lines (PM visit, callout retainer, spare pack, SLA)
 *   3. tender_service_spec — all 10 bid-time answers pre-filled with realistic values
 *   4. 1 DRAFT pricing version seeded from the items (default markup 22%)
 *
 * Prints the URL to open at the end.
 */
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';
$_SESSION = $_SESSION ?? [];
foreach (['Tenders.php','TenderItems.php','TenderPricing.php','TenderServiceSpec.php'] as $m) {
    require_once ROOT . DS . 'app' . DS . 'models' . DS . $m;
}

function h(string $t): void { echo "\n==== $t ====\n"; }
function p(string $t): void { echo "  $t\n"; }

$db  = new DB();
$tm  = new Tenders();
$ti  = new TenderItems();
$tp  = new TenderPricing();
$tss = new TenderServiceSpec();

$uid = 999; $unm = 'Demo Seeder';
$sampleTitle = 'DEMO-SVC · Vodacom Tower PM programme (50 sites · Coast, Dar, Morogoro)';

/* ── 0. Idempotency — skip if sample already present ─────────────────── */
$prior = $db->mySelect("SELECT c0d FROM tender_tracker WHERE tender_title = :ttl", [':ttl' => $sampleTitle]);
if (!empty($prior)) {
    $tenderId = (int)$prior[0]['c0d'];
    echo "\n=== ALREADY EXISTS ===\n";
    echo "Vodacom Tower PM sample tender already present (tender_id={$tenderId}).\n";
    echo "This script is persistent — re-run is a no-op so user data isn't wiped.\n";
    echo "Open in browser:\n";
    echo "  http://localhost/rsflow.dspera/Tenders/view/{$tenderId}\n";
    echo "\n";
    exit(0);
}

/* ── 1. Create the tender header ─────────────────────────────────────── */
h('1. Create Services tender · Vodacom Tower PM');
$customerRow = $db->mySelect("SELECT c0d, TRIM(CONCAT(IFNULL(fname,''),' ',IFNULL(lname,''))) buyer FROM customers WHERE deleted=0 LIMIT 1", []);
$customerId  = !empty($customerRow) ? (int)$customerRow[0]['c0d'] : 1;
$buyerName   = 'Vodacom Tanzania Ltd';

$tenderId = $tm->create([
    'source_type'        => 'PRIVATE_CLIENT',
    'source_ref'         => 'VOD-RFP-2026-PM-050',
    'source_url'         => 'https://vodacom.co.tz/procurement/rfp-2026-pm-050',
    'customer_id'        => $customerId,
    'buyer_name'         => $buyerName,
    'project_type'       => 'services',
    'tender_title'       => $sampleTitle,
    'tender_description' => "Preventive maintenance and reactive-callout service for 50 BTS tower sites across the Coast, Dar es Salaam and Morogoro regions.\n\nScope: quarterly PM visits on each site (gensets, ACs, UPS + battery banks), 24/7 emergency callouts within the response SLA, plus a client-supplied service pack of consumables per interval.\n\nDuration: 24 months from LPO. Pricing model is monthly retainer for PM + free-quota callouts, with per-callout fee beyond the quota.",
    'tender_industry'    => 'Telecom',
    'region'             => 'Dar es Salaam',
    'district'           => 'Kinondoni',
    'date_received'      => date('Y-m-d'),
    'deadline_date'      => date('Y-m-d', strtotime('+21 days')),
    'deadline_time'      => '15:00:00',
    'estimated_value'    => 720000000,
    'submission_method'  => 'e-Procurement portal (Vodacom SRM)',
    'tender_stage'       => 'PREP',
], $uid, $unm);
p("tender_id = $tenderId · buyer = $buyerName");

/* ── 2. Seed 4 tender-items lines ─────────────────────────────────────── */
h('2. Seed buyer-list items (PM visits, callout retainer, spare pack, SLA)');
$items = [
    ['item_ref' => 'PM-QTR-VISIT',    'description' => 'Quarterly PM visit (gen + AC + UPS)',            'qty' => 200, 'uom' => 'visit',    'spec_notes' => '50 sites × 4 quarters — full inspection + consumables replaced'],
    ['item_ref' => 'CALLOUT-RETAIN',  'description' => 'Callout retainer (12 free / month across fleet)', 'qty' => 24,  'uom' => 'month',    'spec_notes' => 'Beyond 12/month, per-callout fee applies. Emergency callouts 2× multiplier'],
    ['item_ref' => 'SPARE-PACK-Q',    'description' => 'Client-supplied consumables per PM visit',        'qty' => 200, 'uom' => 'pack',     'spec_notes' => 'Filters + oil + belts + battery cleaning agents'],
    ['item_ref' => 'SLA-24x7-OPS',    'description' => 'NOC + dispatch coverage (24×7 helpdesk)',         'qty' => 24,  'uom' => 'month',    'spec_notes' => 'SLA: EMR 2h · URG 8h · ROU 48h response'],
];
foreach ($items as $it) $ti->add($tenderId, $it, $uid, $unm);
p(count($items) . ' items seeded · default_kind = ' . TenderItems::defaultKindFor('services'));

/* ── 3. Seed tender_service_spec — the 10 bid-time answers ───────────── */
h('3. Seed tender_service_spec (10 CRM checklist answers)');
$equipment = [
    ['type' => 'GEN', 'size' => '20-40 kVA',  'count' => 30],
    ['type' => 'GEN', 'size' => '60-100 kVA', 'count' => 20],
    ['type' => 'AC',  'size' => '18000 BTU',  'count' => 100],
    ['type' => 'UPS', 'size' => '6 kVA',      'count' => 50],
];
$specId = $tss->save($tenderId, [
    'no_of_sites'                 => 50,
    'sites_notes'                 => '50 BTS towers across Coast (18) · Dar (24) · Morogoro (8)',
    'equipment_json'              => $equipment,
    'pm_cadence'                  => 'QUARTERLY',
    'pm_payment_structure'        => 'MONTHLY_RETAINER',
    'has_callouts'                => 1,
    'callout_payment_structure'   => 'FREE_QUOTA_PLUS_FEE',
    'callout_fee'                 => 350000,
    'emergency_multiplier'        => 2.00,
    'free_callouts_per_month'     => 12,
    'sla_emergency_hrs'           => 2,
    'sla_urgent_hrs'              => 8,
    'sla_routine_hrs'             => 48,
    'spare_policy'                => 'CLIENT',
    'spare_policy_notes'          => 'Vodacom supplies spare parts against a pre-agreed pack; consignment tools remain with us',
    'client_supplied_pack'        => 1,
    'service_pack_notes'          => "Per PM visit (per site):\n  · 1× oil + oil filter (gen)\n  · 1× air filter (gen)\n  · 1× fuel filter (gen)\n  · AC filter clean/replace\n  · UPS battery terminals cleaned + torqued",
    'invoicing_cadence'           => 'MONTHLY_RETAINER',
    'payment_terms_days'          => 45,
    'labour_rate_per_hr'          => 85000,
    'mileage_rate_per_km'         => 1500,
    'parts_markup_pct'            => 25.00,
    'part_replacement_sop_agreed' => 1,
    'part_replacement_notes'      => "For adhoc replacements outside the service pack:\n  1. FS captures fault photo + failed-part photo on site\n  2. FS raises quote via app (labour hrs + part cost)\n  3. PM approval required before dispatch\n  4. Client acknowledges via email; PC issues LPO to supplier\n  5. Target response for adhoc replacement: 48 hours",
    'general_notes'               => 'Contract expected to run 24 months. Monthly retainer covers PM + first 12 callouts across fleet; overage billed monthly. Emergency callouts (SLA 2h) bill at 2× the standard callout fee.',
], $uid, $unm);
p("service_spec_id = $specId");

/* ── 4. DRAFT pricing v1 seeded from items ───────────────────────────── */
h('4. Create pricing v1 (DRAFT) · seed from items');
$vid = $tp->createVersion($tenderId, null, $uid, $unm);
$tp->updateVersionHeader($vid, [
    'version_label'      => 'v1 · initial pricing pass',
    'vat_pct'            => 18.00,
    'contingency_pct'    => 3.00,
    'prelims_amount'     => 2000000,
    'default_markup_pct' => 22.00,
    'pricing_mode'       => 'PER_ITEM',
], $uid);
$seed = $tp->seedFromItems($vid, 0, $uid);
p("version $vid seeded · {$seed['added']} lines added");

/* Realistic unit costs on the seeded lines */
h('5. Set unit costs on seeded lines');
$secId = (int)$seed['section_id'];
$costsByRef = [
    'PM-QTR-VISIT'   => 850000,
    'CALLOUT-RETAIN' => 3200000,
    'SPARE-PACK-Q'   => 180000,
    'SLA-24x7-OPS'   => 1400000,
];
foreach ($tp->linesFor($secId) as $ln) {
    $cost = $costsByRef[$ln['item_ref']] ?? 0;
    if ($cost <= 0) continue;
    $tp->updateLine((int)$ln['c0d'], [
        'item_ref'    => $ln['item_ref'],
        'description' => $ln['description'],
        'qty'         => (float)$ln['qty'],
        'uom'         => $ln['uom'],
        'unit_cost'   => $cost,
        'markup_pct'  => 22.0,
        'notes'       => $ln['notes'] ?? '',
    ], $uid);
}
$vFinal = $tp->findVersion($vid);
p(sprintf("version totals · cost=%s · sell=%s · margin=%.1f%%",
    number_format((float)$vFinal['sum_cost']),
    number_format((float)$vFinal['sum_price']),
    (float)$vFinal['margin_pct']
));

echo "\n=== DONE ===\n";
echo "Open in browser:\n";
echo "  http://localhost/rsflow.dspera/Tenders/view/{$tenderId}\n";
echo "  http://localhost/rsflow.dspera/Tenders?type=services\n";
echo "\nSample is persistent — re-running this script is a no-op.\n\n";
