<?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/SpareParts.php';
require_once ROOT . '/app/models/ServiceContracts.php';
require_once ROOT . '/app/models/Callouts.php';

$pdo = new PDO('mysql:host=localhost;dbname=rookpmgt_rsflow;charset=utf8mb4', 'root', '');
$pdo->exec("DELETE FROM sales_items WHERE sale_id IN (SELECT c0d FROM sales WHERE customer_name='SMOKE-S5' AND deleted = 0)");
$pdo->exec("DELETE FROM sales WHERE customer_name='SMOKE-S5'");
$pdo->exec("DELETE FROM callout_parts_used WHERE callout_id IN (SELECT c0d FROM callouts WHERE contract_id IN (SELECT c0d FROM service_contracts WHERE customer_name='SMOKE-S5'))");
$pdo->exec("DELETE FROM callouts WHERE contract_id IN (SELECT c0d FROM service_contracts WHERE customer_name='SMOKE-S5')");
$pdo->exec("DELETE FROM service_contract_pm_schedule WHERE contract_id IN (SELECT c0d FROM service_contracts WHERE customer_name='SMOKE-S5')");
$pdo->exec("DELETE FROM service_contract_assets WHERE contract_id IN (SELECT c0d FROM service_contracts WHERE customer_name='SMOKE-S5')");
$pdo->exec("DELETE FROM service_contract_sites WHERE contract_id IN (SELECT c0d FROM service_contracts WHERE customer_name='SMOKE-S5')");
$pdo->exec("DELETE FROM service_contracts WHERE customer_name='SMOKE-S5'");
$pdo->exec("DELETE FROM spare_parts WHERE sku='SMOKE-OIL-15W40'");

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

$parts  = new SpareParts();
$partId = $parts->save(['sku'=>'SMOKE-OIL-15W40','name'=>'15W40 Diesel Oil 5L','uom'=>'L','category'=>'oil','asset_type_id'=>$genId,'unit_cost'=>25000,'default_markup_pct'=>25,'is_active'=>1], 0);
echo 'Part id=' . $partId . PHP_EOL;

$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-S5', 'customer_id'=>1,
    'contract_value'=>12000000, 'currency'=>'TZS', 'monthly_retainer'=>800000,
    'spare_policy'=>'COMPANY', 'invoice_cadence'=>'CONSUMPTION', 'payment_terms_days'=>30,
    'labour_rate_per_hr'=>50000, 'callout_fee'=>150000, 'emergency_multiplier'=>2,
    'parts_markup_pct'=>25, 'mileage_rate_per_km'=>1500, 'free_callouts_per_month'=>2,
], 0, 'smoke');
$siteId  = $sc->saveSite(['contract_id'=>$cid,'name'=>'Head Office','region'=>'Dar','is_active'=>1]);
$assetId = $sc->saveAsset(['contract_id'=>$cid,'site_id'=>$siteId,'asset_type_id'=>$genId,'asset_no'=>'GEN-S5','size_value'=>75,'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();
$year   = (int)date('Y');
$mo     = (int)date('n');
$midMonth = sprintf('%04d-%02d-15 08:00:00', $year, $mo);
for ($n = 1; $n <= 3; $n++) {
    $isEmerg = ($n === 3);
    $coId = $co->saveIntake([
        'contract_id'=>$cid, 'category_id'=>$catId, 'site_id'=>$siteId, 'asset_id'=>$assetId,
        'reported_by_name'=>'Client '.$n, 'reported_at'=>$midMonth,
        'description'=>'Test callout '.$n, 'is_emergency'=>$isEmerg ? 1 : 0
    ], 0, 'smoke');
    $co->dispatch($coId, 0, 'FS Test');
    $co->arrive($coId);
    $co->resolve($coId, ['resolution_description'=>'Fixed','labour_hrs'=>2,'mileage_km'=>15]);
    if ($n >= 2) $co->addPart($coId, ['part_id'=>$partId, 'qty'=>5, 'source'=>'STOCK']);
    $pdo->exec("UPDATE callouts SET resolved_at = '$midMonth' WHERE c0d=$coId");
    echo '  Callout '.$n.' (emerg='.(int)$isEmerg.') id='.$coId.' resolved.'.PHP_EOL;
}

$calc = $sc->calcConsumption($cid, $year, $mo);
echo PHP_EOL . '--- Consumption preview ---' . PHP_EOL;
echo 'Period: '.$calc['period'].' · Callouts: '.$calc['callout_count'].' · Currency: '.$calc['currency'].PHP_EOL;
foreach ($calc['lines'] as $i => $l) echo '  ['.($i+1).'] '.$l['description'].' | qty='.$l['qty'].' '.$l['unit'].' × '.number_format((float)$l['unit_price']).' = '.number_format((float)$l['line_total']).PHP_EOL;
echo 'Subtotal: '.number_format($calc['subtotal']).PHP_EOL;

$r = $sc->draftConsumptionInvoice($cid, $year, $mo, 0, 'smoke');
echo PHP_EOL . 'draftConsumptionInvoice ok='.($r['ok']?'true':'false').' sale_id='.($r['sale_id'] ?? 0).' lines='.($r['lines'] ?? 0).' subtotal='.number_format((float)($r['subtotal'] ?? 0)).PHP_EOL;

$sale = $pdo->query('SELECT * FROM sales WHERE c0d='.(int)$r['sale_id'])->fetch(PDO::FETCH_ASSOC);
echo 'Sale row: source='.$sale['source_module'].' status='.$sale['invoice_workflow_status'].' due='.$sale['due_date'].' total='.number_format((float)$sale['total']).PHP_EOL;

$r2 = $sc->draftConsumptionInvoice($cid, $year, $mo, 0, 'smoke');
echo 'Rerun: ok='.($r2['ok']?'true':'false').' msg='.($r2['msg'] ?? '-').PHP_EOL;

// Cleanup
$pdo->exec('DELETE FROM sales_items WHERE sale_id='.(int)$r['sale_id']);
$pdo->exec('DELETE FROM sales WHERE c0d='.(int)$r['sale_id']);
$pdo->exec('DELETE FROM callout_parts_used WHERE callout_id IN (SELECT c0d FROM callouts WHERE contract_id='.$cid.')');
$pdo->exec('DELETE FROM callouts WHERE contract_id='.$cid);
$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);
$pdo->exec('DELETE FROM spare_parts WHERE c0d='.$partId);
echo PHP_EOL . 'Cleanup done.' . PHP_EOL;
