<?php
/**
 * Rewind tender #109 to Awarded state so CRM can drive the Handover-to-FM flow end-to-end:
 *   - tender_stage → AWARDED  (from EXECUTION)
 *   - tender_status  stays WON (result stays)
 *   - clear tender_contract_signing  (so signing checklist step reverts to undone)
 *   - clear fin_approvals for TENDER_CONTRACT  (so terms are editable and Submit for FM verify is unlocked)
 *   - clear all four seat assignments   (so CRM has to pick FM again, then FM Acc+Proc, then Exec PM)
 *   - clear c_projects.tender_id link back if it was created (so the checklist starts fresh)
 */
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';

$db = new DB();
$tid = 109;

echo "== Rewinding tender #{$tid} to Awarded ==\n";

$before = $db->mySelect("SELECT tender_stage, tender_status, linked_project_id FROM tender_tracker WHERE c0d = :id", [':id' => $tid]);
if (empty($before)) { echo "Tender not found.\n"; exit(1); }
$b = $before[0];
echo "  before: stage={$b['tender_stage']} · status={$b['tender_status']} · linked_project_id={$b['linked_project_id']}\n";

// 1. Roll stage back to AWARDED
$db->insertUpdate("UPDATE tender_tracker SET tender_stage = 'AWARDED', linked_project_id = 0 WHERE c0d = :id", [':id' => $tid]);
echo "  ✓ stage → AWARDED · unlinked from project\n";

// 2. Drop the signing row so the checklist step reverts
$db->insertUpdate("DELETE FROM tender_contract_signing WHERE tender_id = :t", [':t' => $tid]);
echo "  ✓ dropped tender_contract_signing rows\n";

// 3. Drop any TENDER_CONTRACT approval so terms unlock and Submit becomes possible again
$db->insertUpdate("DELETE FROM fin_approvals     WHERE entity_type = 'TENDER_CONTRACT' AND entity_id = :t", [':t' => $tid]);
$db->insertUpdate("DELETE FROM fin_approval_log  WHERE approval_id NOT IN (SELECT c0d FROM fin_approvals)", []);
echo "  ✓ cleared TENDER_CONTRACT approval + orphaned log rows\n";

// 4. Clear the four seat assignments + any unlock flag on the terms row
$db->insertUpdate(
    "UPDATE tender_contract_terms
        SET assigned_fm_user_id = NULL,
            assigned_accountant_user_id = NULL,
            assigned_procurement_user_id = NULL,
            assigned_pm_user_id = NULL,
            terms_unlock_active = 0
      WHERE tender_id = :t",
    [':t' => $tid]
);
echo "  ✓ cleared four seat assignments + unlock flag\n";

// 5. Verify
$after = $db->mySelect("SELECT tender_stage, tender_status, linked_project_id FROM tender_tracker WHERE c0d = :id", [':id' => $tid]);
$signCount = (int)$db->mySelect("SELECT COUNT(*) n FROM tender_contract_signing WHERE tender_id = :t", [':t' => $tid])[0]['n'];
$apprCount = (int)$db->mySelect("SELECT COUNT(*) n FROM fin_approvals WHERE entity_type='TENDER_CONTRACT' AND entity_id = :t", [':t' => $tid])[0]['n'];
$termsRow  = $db->mySelect("SELECT assigned_fm_user_id, assigned_accountant_user_id, assigned_procurement_user_id, assigned_pm_user_id FROM tender_contract_terms WHERE tender_id = :t", [':t' => $tid]);

echo "\n== After ==\n";
echo "  stage={$after[0]['tender_stage']} · status={$after[0]['tender_status']} · linked_project_id={$after[0]['linked_project_id']}\n";
echo "  signing rows: $signCount · approval rows: $apprCount\n";
echo "  seats: ";
if (!empty($termsRow)) {
    $t = $termsRow[0];
    echo "fm=" . ($t['assigned_fm_user_id'] ?? 'null')
       . " · acc=" . ($t['assigned_accountant_user_id'] ?? 'null')
       . " · proc=" . ($t['assigned_procurement_user_id'] ?? 'null')
       . " · pm=" . ($t['assigned_pm_user_id'] ?? 'null') . "\n";
} else {
    echo "(no contract_terms row yet — will be created when CRM first saves terms)\n";
}
echo "\n== Ready ==\n";
echo "  http://localhost/rsflow.dspera/Tenders/view/{$tid}#tab-contract\n";
echo "  Log in as CRM to assign FM · then FM assigns Acc + Proc · then Exec assigns PM\n";
