<?php
/**
 * Seed a realistic demo GOODS tender end-to-end so we can click through the whole flow:
 *   - Details tab (title, source, industry, region, description)
 *   - 6 tender items (buyer's spec)
 *   - 1 DRAFT pricing version seeded FROM those items (default markup 22%)
 *
 * Idempotent: re-running purges the previous 'DEMO-GOODS-*' rows first.
 * 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'] 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"; }
function ok(bool $c, string $m): void { echo ($c ? "  ✓ " : "  ✗ ") . $m . "\n"; }

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

$uid = 999; $unm = 'Demo Seeder';

/* ── 0. Purge prior DEMO-GOODS tenders ─────────────────────────────── */
h('0. Purge prior demo goods tenders');
$prior = $db->mySelect("SELECT c0d FROM tender_tracker WHERE tender_title LIKE 'DEMO-GOODS%'", []) ?: [];
foreach ($prior as $r) {
    $tid = (int)$r['c0d'];
    $db->insertUpdate("DELETE FROM tender_pricing_lines    WHERE tender_id = :t", [':t' => $tid]);
    $db->insertUpdate("DELETE FROM tender_pricing_sections WHERE tender_id = :t", [':t' => $tid]);
    $db->insertUpdate("DELETE FROM tender_pricing_versions WHERE tender_id = :t", [':t' => $tid]);
    $db->insertUpdate("DELETE FROM tender_items            WHERE tender_id = :t", [':t' => $tid]);
    $db->insertUpdate("DELETE FROM tender_tracker          WHERE c0d = :t",       [':t' => $tid]);
}
p("purged " . count($prior) . " prior demo tenders");

/* ── 1. Create the tender header ───────────────────────────────────── */
h('1. Create tender header · project_type = goods');
$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   = !empty($customerRow) ? (string)$customerRow[0]['buyer'] : 'TTCL Ltd';

$tenderId = $tm->create([
    'source_type'        => 'PRIVATE_CLIENT',
    'source_ref'         => 'RFP-2026-DEMO-01',
    'source_url'         => 'https://ttcl.co.tz/procurement/rfp-2026-demo-01',
    'customer_id'        => $customerId,
    'buyer_name'         => $buyerName,
    'project_type'       => 'goods',
    'tender_title'       => 'DEMO-GOODS · Supply of core-network switching equipment (8 sites)',
    'tender_description' => "Supply, deliver and commission core switching gear across 8 branch sites in Dar es Salaam, Arusha and Mwanza.\n\nAll items must ship with vendor warranty (min 24 months) and be OEM-authorised.\nDelivery to sites within 45 days of LPO.",
    'tender_industry'    => 'Telecom',
    'region'             => 'Dar es Salaam',
    'district'           => 'Ilala',
    'date_received'      => date('Y-m-d'),
    'deadline_date'      => date('Y-m-d', strtotime('+14 days')),
    'deadline_time'      => '15:00:00',
    'estimated_value'    => 45000000,
    'submission_method'  => 'Sealed envelope, hand-delivered',
    'tender_stage'       => 'PREP',
], $uid, $unm);
p("tender_id = $tenderId · buyer = $buyerName");

/* ── 2. Seed 6 tender items (the buyer's list) ─────────────────────── */
h('2. Seed 6 buyer-list items');
$items = [
    ['item_ref' => 'CORE-SW-48P', 'description' => 'Managed Layer-3 core switch, 48× 1GbE + 4× 10GbE SFP+ uplinks', 'qty' => 8,   'uom' => 'ea',    'spec_notes' => 'Cisco Catalyst 9300 series or equivalent · rack-mount 1U · stackable'],
    ['item_ref' => 'CORE-SW-24P', 'description' => 'Managed Layer-2 access switch, 24× 1GbE PoE+ + 2× SFP uplinks',  'qty' => 16,  'uom' => 'ea',    'spec_notes' => 'PoE+ budget ≥ 370W · fanless preferred'],
    ['item_ref' => 'SFP-10G-LR',  'description' => '10GBASE-LR SFP+ transceiver, LC single-mode, 10km reach',        'qty' => 32,  'uom' => 'ea',    'spec_notes' => 'OEM-branded · not third-party compatible'],
    ['item_ref' => 'RACK-42U',    'description' => '42U server rack, 800×1000mm, glass front door, fully assembled', 'qty' => 8,   'uom' => 'ea',    'spec_notes' => 'Includes PDU + cable management arms'],
    ['item_ref' => 'CABLE-CAT6A', 'description' => 'CAT6A U/FTP LSZH cable, 305m box, blue',                         'qty' => 20,  'uom' => 'box',   'spec_notes' => 'Verified to 500 MHz · 10GBASE-T capable'],
    ['item_ref' => 'INSTALL-SVC', 'description' => 'On-site install, config, commissioning + KT (per site)',         'qty' => 8,   'uom' => 'site',  'spec_notes' => 'Includes SoW sign-off + 30-day warranty support'],
];
foreach ($items as $it) $ti->add($tenderId, $it, $uid, $unm);
p("6 items seeded · default_kind = " . TenderItems::defaultKindFor('goods'));

/* ── 3. Create a DRAFT pricing version + seed from items ───────────── */
h('3. 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'    => 2.00,
    'prelims_amount'     => 500000,
    'default_markup_pct' => 22.00,
    'pricing_mode'       => 'PER_ITEM',
], $uid);
$seed = $tp->seedFromItems($vid, 0, $uid);
p("version $vid seeded · {$seed['added']} lines added, {$seed['skipped']} skipped");

/* Fill in realistic unit costs on the seeded lines so the pricing tab shows real totals */
h('4. Set unit costs on seeded lines');
$secId = (int)$seed['section_id'];
$costsByRef = [
    'CORE-SW-48P' => 2100000,
    'CORE-SW-24P' =>  980000,
    'SFP-10G-LR'  =>  145000,
    'RACK-42U'    =>  620000,
    'CABLE-CAT6A' =>  380000,
    'INSTALL-SVC' =>  340000,
];
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']
));

/* ── URL ───────────────────────────────────────────────────────────── */
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=goods\n";
echo "\n";
