<?php
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', dirname(__DIR__));
if (!defined('DB_HOST'))     define('DB_HOST', 'localhost');
if (!defined('DB_NAME'))     define('DB_NAME', 'rookpmgt_rsflow');
if (!defined('DB_USER'))     define('DB_USER', 'root');
if (!defined('DB_PASSWORD')) define('DB_PASSWORD', '');
if (!defined('DB_PASS'))     define('DB_PASS', '');
require_once ROOT . '/core/DB.php';
require_once ROOT . '/core/Model.php';
require_once ROOT . '/app/models/AssetTypes.php';
require_once ROOT . '/app/models/ServiceContracts.php';
require_once ROOT . '/app/models/Callouts.php';
require_once ROOT . '/app/models/Lpos.php';

$pdo = new PDO('mysql:host=localhost;dbname=rookpmgt_rsflow;charset=utf8mb4', 'root', '');
// Clean prior state
$pdo->exec("DELETE FROM lpos WHERE requested_by_name = 'SMOKE-S6' OR purpose LIKE 'Adhoc spare · Callout SMOKE-S6-%'");
$pdo->exec("DELETE FROM callouts WHERE contract_id IN (SELECT c0d FROM service_contracts WHERE customer_name='SMOKE-S6')");
$pdo->exec("DELETE FROM service_contract_pm_schedule WHERE contract_id IN (SELECT c0d FROM service_contracts WHERE customer_name='SMOKE-S6')");
$pdo->exec("DELETE FROM service_contract_assets WHERE contract_id IN (SELECT c0d FROM service_contracts WHERE customer_name='SMOKE-S6')");
$pdo->exec("DELETE FROM service_contract_sites WHERE contract_id IN (SELECT c0d FROM service_contracts WHERE customer_name='SMOKE-S6')");
$pdo->exec("DELETE FROM service_contracts WHERE customer_name='SMOKE-S6'");

$types = (new AssetTypes())->all(true);
$genId = 0; foreach ($types as $t) if ($t['code']==='GEN') { $genId=(int)$t['c0d']; break; }

$proj = $pdo->query('SELECT c0d FROM c_projects WHERE deleted=0 ORDER BY c0d DESC LIMIT 1')->fetch(PDO::FETCH_ASSOC);
$sc = new ServiceContracts();
$cid = $sc->saveHeader([
    'project_id'=>(int)$proj['c0d'], 'customer_name'=>'SMOKE-S6', 'customer_id'=>1,
    'contract_value'=>5000000, 'currency'=>'TZS', 'monthly_retainer'=>400000,
    'spare_policy'=>'COMPANY', 'invoice_cadence'=>'MONTHLY_RETAINER', 'payment_terms_days'=>30,
], 0, 'smoke');
$sid = $sc->saveSite(['contract_id'=>$cid,'name'=>'Kariakoo Branch','is_active'=>1]);
$aid = $sc->saveAsset(['contract_id'=>$cid,'site_id'=>$sid,'asset_type_id'=>$genId,'asset_no'=>'GEN-S6','size_value'=>60,'size_unit'=>'kVA','is_active'=>1]);
$sc->activate($cid, 0);
echo 'Contract ' . $cid . ' active.' . PHP_EOL;

$catRow = $pdo->query("SELECT c0d FROM callout_categories WHERE code='URGENT'")->fetch(PDO::FETCH_ASSOC);
$catId  = (int)$catRow['c0d'];
$co     = new Callouts();
$coId   = $co->saveIntake([
    'contract_id'=>$cid,'category_id'=>$catId,'site_id'=>$sid,'asset_id'=>$aid,
    'reported_by_name'=>'Client','reported_at'=>date('Y-m-d H:i:s'),
    'description'=>'Genset shut down suddenly','is_emergency'=>1,
], 0, 'smoke');
$co->dispatch($coId, 0, 'FS Musa');
$co->arrive($coId);
$row = $co->find($coId);
echo 'Callout ' . $row['callout_no'] . ' on site.' . PHP_EOL;

// Now simulate the FS raising a cash request
$purpose = 'Adhoc spare · Callout ' . $row['callout_no']
    . ' · ' . ($row['site_name'] ?? '(no site)')
    . ($row['asset_no'] ? ' · ' . $row['asset_no'] : '')
    . ' · Fuel pump replacement';
$r = (new Lpos())->create([
    'lpo_type'      => 'IMPREST',
    'amount'        => 450000,
    'currency'      => 'TZS',
    'purpose'       => $purpose,
    'project_id'    => (int)$proj['c0d'],
    'source_module' => 'services',
    'payee_type'    => 'employee',
    'payee_name'    => 'SMOKE-S6',
], 0, 'SMOKE-S6');
echo 'Cash request LPO: ok=' . ($r['ok']?'true':'false') . ' lpo_no=' . ($r['lpo_no'] ?? '-') . ' id=' . ($r['id'] ?? 0) . PHP_EOL;

if (!empty($r['ok'])) {
    $lpo = $pdo->query('SELECT lpo_no, lpo_type, amount, currency, purpose, source_module, cash_out_status FROM lpos WHERE c0d=' . (int)$r['id'])->fetch(PDO::FETCH_ASSOC);
    echo 'Verified LPO row:' . PHP_EOL;
    echo '  lpo_no=' . $lpo['lpo_no'] . ' · type=' . $lpo['lpo_type'] . ' · amount=' . number_format((float)$lpo['amount']) . ' ' . $lpo['currency'] . ' · status=' . $lpo['cash_out_status'] . PHP_EOL;
    echo '  source_module=' . $lpo['source_module'] . PHP_EOL;
    echo '  purpose=' . $lpo['purpose'] . PHP_EOL;
}

// Cleanup
$pdo->exec('DELETE FROM lpos WHERE c0d=' . (int)($r['id'] ?? 0));
$pdo->exec('DELETE FROM callouts WHERE c0d=' . $coId);
$pdo->exec('DELETE FROM service_contract_pm_schedule WHERE contract_id=' . $cid);
$pdo->exec('DELETE FROM service_contract_assets WHERE contract_id=' . $cid);
$pdo->exec('DELETE FROM service_contract_sites WHERE contract_id=' . $cid);
$pdo->exec('DELETE FROM service_contracts WHERE c0d=' . $cid);
echo PHP_EOL . 'Cleanup done.' . PHP_EOL;
