<?php
/**
 * Seed a fresh tender ready for FM contract-terms entry.
 *
 *   - Goods tender, PRIVATE_CLIENT source
 *   - Priced (v1 approved → applied as bid amount)
 *   - Result recorded as WON
 *   - Stage advanced to AWARDED
 *   - NO contract terms yet, NO chain submitted
 *
 * When done, prints the URL the FM should open.
 * Log in as any Finance Manager user and land on that URL — the amber
 * "Contract terms needed" banner will be visible; click it to reach the form.
 */
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 (['ApprovalChain.php','Tenders.php','TenderPricing.php'] as $m) require_once ROOT . DS . 'app' . DS . 'models' . DS . $m;

$db = new DB();
$ac = new ApprovalChain();
$tm = new Tenders();
$pm = new TenderPricing();

// Actors (real users seeded in DB)
$uidCrm = 100; $unmCrm = 'CRM Test User';    $ugCrm  = 'CRM';
$uidPm  = 5;   $unmPm  = 'Project Manager Test';
$uidFm  = 3;   $unmFm  = 'Finance Manager Test'; $ugFm = 'Finance Manager';
$uidExe = 2;   $unmExe = 'Executive Test';    $ugExe = 'Executive';

$stamp  = date('YmdHis');
$title  = 'FM DEMO · Fibre-to-branch installation · 8 sites';

echo "Seeding demo tender...\n";

$fb = $db->insertUpdate(
    "INSERT INTO tender_tracker
        (tender_no, tender_title, tender_description, source_type, source_ref,
         buyer_name, project_type, tender_industry, region, district,
         date_received, deadline_date, deadline_time,
         estimated_value, currency, tender_stage, tender_status,
         created_by, created_by_name, created_on)
     VALUES
        (:tn, :tt, :td, 'PRIVATE_CLIENT', :sref,
         'Vodacom Tanzania', 'goods', 'Telecom', 'Dar es Salaam', 'Kinondoni',
         CURDATE(), DATE_ADD(CURDATE(), INTERVAL 21 DAY), '14:00:00',
         380000000, 'TZS', 'PREP', 'OPEN',
         :u, :un, NOW())",
    [
        ':tn'   => 'T-FMDEMO-' . $stamp,
        ':tt'   => $title,
        ':td'   => 'FTTx rollout across 8 Vodacom branches in Dar es Salaam — demo tender for FM contract-terms walkthrough.',
        ':sref' => 'RFP-VOD-2026-04',
        ':u'    => $uidCrm, ':un' => $unmCrm,
    ]
);
$tid = (int)($fb['last_id'] ?? 0);
if ($tid <= 0) { echo "FATAL: tender insert failed\n"; exit(1); }
echo "  Tender created: c0d=$tid · no=T-FMDEMO-$stamp\n";

// Walk stages up to OPENING
foreach (['SUBMISSION','FOLLOW_UP','OPENING'] as $stage) {
    $tm->advanceStage($tid, $stage, 'demo stage advance', $uidCrm, $unmCrm);
}

// Build a small pricing version so the bid amount is realistic
echo "  Building pricing v1 (2 sections × 3 lines)...\n";
$vid = $pm->createVersion($tid, null, $uidCrm, $unmCrm);
$s1  = $pm->addSection($vid, $tid, 'Site prep',   'Access + fencing per site', $uidCrm);
$s2  = $pm->addSection($vid, $tid, 'Fibre & equipment', 'ODF + splice + cabinets', $uidCrm);
$pm->addLine($s1, ['item_ref'=>'SP-01','description'=>'Perimeter fencing (8 sites)','qty'=>1600,'uom'=>'m',  'unit_cost'=>3500,   'markup_pct'=>25], $uidCrm);
$pm->addLine($s1, ['item_ref'=>'SP-02','description'=>'Site clearing','qty'=>8,'uom'=>'site','unit_cost'=>1500000,'markup_pct'=>30], $uidCrm);
$pm->addLine($s2, ['item_ref'=>'FE-01','description'=>'ODF 24-port','qty'=>8,'uom'=>'ea', 'unit_cost'=>4200000,'markup_pct'=>20], $uidCrm);
$pm->addLine($s2, ['item_ref'=>'FE-02','description'=>'Splice enclosure','qty'=>32,'uom'=>'ea','unit_cost'=>350000,'markup_pct'=>22], $uidCrm);
$pm->addLine($s2, ['item_ref'=>'FE-03','description'=>'Outdoor cabinet','qty'=>8,'uom'=>'ea','unit_cost'=>2800000,'markup_pct'=>18], $uidCrm);

// Walk pricing chain PM → FM → Exec
$res = $pm->submitForApproval($vid, $uidCrm, $unmCrm, $ugCrm);
$aidP = (int)$res['approval_id'];
$ac->approve(['approval_id'=>$aidP,'user_id'=>$uidPm, 'user_name'=>$unmPm,'user_group'=>'Project Manager','comment'=>'ok']);
$ac->approve(['approval_id'=>$aidP,'user_id'=>$uidFm, 'user_name'=>$unmFm,'user_group'=>$ugFm,'comment'=>'ok']);
$ac->approve(['approval_id'=>$aidP,'user_id'=>$uidExe,'user_name'=>$unmExe,'user_group'=>$ugExe,'comment'=>'ok']);
$pm->onPricingDecision($vid, 'APPROVED');
$pm->applyToTender($vid);
$v = $pm->findVersion($vid);
echo "  Pricing v1 approved · bid amount = TZS " . number_format((float)$v['sum_price']) . "\n";

// Result WON + advance to AWARDED — this fires the FM notification.
$tm->recordResult($tid, 'WON', date('Y-m-d'), '', (float)$v['sum_price'], '', 'Awarded to us · demo', $uidCrm, $unmCrm);
$tm->advanceStage($tid, 'AWARDED', 'Awarded — ready for FM contract terms', $uidCrm, $unmCrm);

echo "\n";
echo "=================================================================\n";
echo "  DEMO READY — log in as FM (username: whichever FM user you use)\n";
echo "  Open: http://localhost/rsflow.dspera/Tenders/view/$tid\n";
echo "  You'll see the amber 'Contract terms needed' banner.\n";
echo "  Click 'Enter contract terms' → land on the Contract signing tab.\n";
echo "  Fill the form → Save Terms → then Submit for FM Verification.\n";
echo "=================================================================\n";
