<?php
/**
 * Slice 8Z-t · VAT exemption certificate gate on tax_treatment ≠ TAXABLE.
 * Snapshots contract terms + bond, mutates, asserts, cleans up.
 */
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'] 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;
$tm  = new Tenders();
$bm  = new TenderContractBonds();

$snapshot = $db->mySelect("SELECT tax_treatment FROM tender_contract_terms WHERE tender_id = :t", [':t' => $tid]);
$originalTt = !empty($snapshot) ? (string)$snapshot[0]['tax_treatment'] : '';
$hasTermsRow = !empty($snapshot);

if (!$hasTermsRow) {
    echo "\nNote: tender {$tid} has no contract terms row yet — inserting a stub to exercise the check.\n";
    $db->insertUpdate(
        "INSERT INTO tender_contract_terms (tender_id, contract_value, tax_treatment) VALUES (:t, 100000000, :tt)",
        [':t' => $tid, ':tt' => 'TAXABLE']
    );
}

/* ── 1. TAXABLE → cert not required ────────────────────────────────── */
h('1. TAXABLE → VAT cert NOT in missing list');
$db->insertUpdate("UPDATE tender_contract_terms SET tax_treatment = 'TAXABLE' WHERE tender_id = :t", [':t' => $tid]);
$missing = $tm->contractCompletenessMissing($tid);
$vatMissing = false;
foreach ($missing as $lbl) if (strpos((string)$lbl, 'VAT exemption certificate') === 0) { $vatMissing = true; break; }
ok(!$vatMissing, 'no "VAT exemption certificate" entry when TAXABLE');

/* ── 2. EXEMPT + no cert → cert appears in missing ─────────────────── */
h('2. EXEMPT + no VAT cert → cert IS in missing list');
$db->insertUpdate("UPDATE tender_contract_terms SET tax_treatment = 'EXEMPT' WHERE tender_id = :t", [':t' => $tid]);
$missing = $tm->contractCompletenessMissing($tid);
$vatMissing = false;
foreach ($missing as $lbl) if (strpos((string)$lbl, 'VAT exemption certificate') === 0) { $vatMissing = true; break; }
ok($vatMissing, 'missing includes VAT exemption certificate when EXEMPT');

/* ── 3. Add a VAT_EXEMPTION_CERT bond in PENDING → still missing ─── */
h('3. EXEMPT + PENDING VAT cert → still missing (must be RECEIVED)');
$bondRes = $bm->save($tid, [
    'bond_type'    => 'VAT_EXEMPTION_CERT',
    'status'       => 'PENDING',
    'reference_no' => 'TRA-VE-SMOKE-001',
    'issuer'       => 'Tanzania Revenue Authority',
], 999, 'Smoke Test');
ok($bondRes['ok'] === true, 'PENDING VAT cert saved');
$bondId = (int)($bondRes['id'] ?? 0);
$missing = $tm->contractCompletenessMissing($tid);
$vatMissing = false;
foreach ($missing as $lbl) if (strpos((string)$lbl, 'VAT exemption certificate') === 0) { $vatMissing = true; break; }
ok($vatMissing, 'PENDING VAT cert does NOT clear the gate (only RECEIVED does)');

/* ── 4. Flip to RECEIVED → cert clears the gate ───────────────────── */
h('4. EXEMPT + RECEIVED VAT cert → cert clears from missing list');
$bm->save($tid, ['c0d' => $bondId, 'bond_type' => 'VAT_EXEMPTION_CERT', 'status' => 'RECEIVED'], 999, 'Smoke Test');
$missing = $tm->contractCompletenessMissing($tid);
$vatMissing = false;
foreach ($missing as $lbl) if (strpos((string)$lbl, 'VAT exemption certificate') === 0) { $vatMissing = true; break; }
ok(!$vatMissing, 'RECEIVED VAT cert clears the gate');

/* ── 5. Also appears in per-item checklist ────────────────────────── */
h('5. Checklist item annotated with section_key = tax');
$db->insertUpdate("UPDATE tender_contract_bonds SET status = 'PENDING' WHERE c0d = :id", [':id' => $bondId]);
$checklist = $tm->contractCompletenessChecklist($tid);
$found = null;
foreach ($checklist as $ci) if (strpos((string)$ci['label'], 'VAT exemption certificate') === 0) { $found = $ci; break; }
ok($found !== null, 'checklist contains VAT cert item');
ok(!empty($found) && (string)$found['section_key'] === 'tax', "section_key = 'tax'");
ok(!empty($found) && empty($found['ok']), 'ok = false while status != RECEIVED');

/* ── 6. Cleanup ───────────────────────────────────────────────────── */
$db->insertUpdate("DELETE FROM tender_contract_bonds WHERE c0d = :id", [':id' => $bondId]);
$db->insertUpdate("UPDATE tender_contract_terms SET tax_treatment = :tt WHERE tender_id = :t", [':t' => $tid, ':tt' => $originalTt]);
if (!$hasTermsRow) $db->insertUpdate("DELETE FROM tender_contract_terms WHERE tender_id = :t", [':t' => $tid]);

echo "\n=== DONE (state restored) ===\n";
