<?php
/**
 * Slice 8Z-q · Smoke test for the FM verification enhancements.
 *
 *   1. TenderContractBonds — CRUD + expiry chip
 *   2. TenderFmVerificationAttachments — mandatoryCheck() sanity
 *   3. contractCompletenessMissing — bubbles the FM-attach missing rows
 *   4. saveContractTerms + reload — the 3 new columns survive
 *
 * Runs against tender 400 (Vodacom Tower PM sample).
 */
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','TenderContractBonds.php','TenderFmVerificationAttachments.php'] as $m) {
    require_once ROOT . DS . 'app' . DS . 'models' . DS . $m;
}

function ok(bool $c, string $m): void { echo ($c ? "  ✓ " : "  ✗ ") . $m . "\n"; }
function h(string $t): void { echo "\n==== $t ====\n"; }

$db  = new DB();
$tid = 400;
$bm  = new TenderContractBonds();
$fm  = new TenderFmVerificationAttachments();
$tm  = new Tenders();

// Baseline check
$t = $tm->find($tid);
if (!$t) { echo "✗ tender {$tid} not found\n"; exit(1); }

/* ── 1 · Bonds CRUD round-trip ────────────────────────────────────── */
h('1. Bonds CRUD round-trip');

$before = $bm->listFor($tid);
$res = $bm->save($tid, [
    'bond_type'      => 'PERFORMANCE_BOND',
    'status'         => 'PENDING',
    'reference_no'   => 'SMOKE-TEST-001',
    'issuer'         => 'CRDB Bank',
    'amount'         => 45000000,
    'currency'       => 'TZS',
    'received_date'  => date('Y-m-d'),
    'validity_until' => date('Y-m-d', strtotime('+15 days')),  // → DUE_SOON chip
    'remarks'        => 'Smoke test bond',
], 999, 'Smoke Test');
ok($res['ok'] === true,                  'save returned ok');
$bondId = (int)($res['id'] ?? 0);
ok($bondId > 0,                          "insert produced id ({$bondId})");

$after = $bm->listFor($tid);
ok(count($after) === count($before) + 1, 'listFor grew by 1');

$found = $bm->find($bondId);
ok($found !== null,                                          'find() returns the row');
ok((string)$found['reference_no'] === 'SMOKE-TEST-001',      'reference_no persisted');
ok((float)$found['amount'] === 45000000.0,                   'amount persisted');

$expiry = $bm->withExpiry([$found]);
ok(($expiry[0]['expiry_chip'] ?? '') === 'DUE_SOON',         'DUE_SOON expiry chip (< 30 days)');

$upd = $bm->save($tid, ['c0d' => $bondId, 'bond_type' => 'PERFORMANCE_BOND', 'status' => 'RECEIVED'], 999, 'Smoke Test');
ok($upd['ok'] === true,                                      'update returned ok');
$after2 = $bm->find($bondId);
ok((string)$after2['status'] === 'RECEIVED',                 'status flipped to RECEIVED');

/* ── 2 · FM attachments mandatoryCheck ────────────────────────────── */
h('2. FM verification attachments — mandatoryCheck');
$chk = $fm->mandatoryCheck($tid);
ok(is_array($chk),                                           'result shape OK');
ok($chk['ok'] === false,                                     'ok=false while mandatory-3 missing');
ok(count($chk['missing']) === 3,                             '3 missing subtypes');
ok(in_array('COVER_MEMO', $chk['missing'], true),           'COVER_MEMO in missing set');
ok(in_array('CASH_FLOW', $chk['missing'], true),            'CASH_FLOW in missing set');
ok(in_array('PROFITABILITY_MODEL', $chk['missing'], true),  'PROFITABILITY_MODEL in missing set');

/* ── 3 · contractCompletenessMissing bubbles FM-attach ─────────────── */
h('3. Tenders::contractCompletenessMissing includes FM-attach labels');
$missing = $tm->contractCompletenessMissing($tid);
$fmLabelsPresent = 0;
foreach ($missing as $lbl) if (strpos($lbl, 'FM attachment:') === 0) $fmLabelsPresent++;
ok($fmLabelsPresent >= 3,                                    "≥3 'FM attachment:' labels in missing (got {$fmLabelsPresent})");

/* ── 4 · saveContractTerms writes the 3 new columns ──────────────── */
h('4. Contract terms — 3 new columns round-trip');
// Guard: tender must be WON with contract_terms row to test saveContractTerms.
// For the smoke test we just check that the model exposes the columns
// (a full save round-trip is out of scope here as the sample tender is not Won).
$colChk = $db->mySelect("SHOW COLUMNS FROM tender_contract_terms WHERE Field IN ('payment_net_days','pg_validity_months','advance_conditions')", []);
ok(count($colChk) === 3,                                     '3 new columns present in schema');

/* ── 5 · Cleanup ──────────────────────────────────────────────────── */
h('5. Cleanup smoke test bond');
$rm = $bm->remove($bondId, 999);
ok($rm['ok'] === true,                                       'remove returned ok');
$stillThere = $bm->find($bondId);
ok($stillThere === null,                                     'row is soft-deleted (find returns null)');

echo "\n=== DONE ===\n";
