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

// The addPhoto/stashPhoto path uses move_uploaded_file() which requires an actual
// uploaded file. We can't fake that from CLI, so this smoke test exercises just
// the read-side helpers by inserting rows directly (simulating what stashPhoto
// would have produced) and verifying the model reads them back correctly.
$pdo = new PDO('mysql:host=localhost;dbname=rookpmgt_rsflow;charset=utf8mb4', 'root', '');

// Cleanup any previous
$pdo->exec("DELETE FROM pm_service_photos WHERE pm_service_id IN (SELECT c0d FROM pm_services WHERE pm_no LIKE 'PM-9999-%')");
$pdo->exec("DELETE FROM callout_photos WHERE callout_id IN (SELECT c0d FROM callouts WHERE callout_no LIKE 'CO-9999-%')");
$pdo->exec("DELETE FROM pm_services WHERE pm_no LIKE 'PM-9999-%'");
$pdo->exec("DELETE FROM callouts WHERE callout_no LIKE 'CO-9999-%'");
$pdo->exec("DELETE FROM callouts WHERE contract_id IN (SELECT c0d FROM service_contracts WHERE customer_name='SMOKE-S7')");
$pdo->exec("DELETE FROM service_contract_pm_schedule WHERE contract_id IN (SELECT c0d FROM service_contracts WHERE customer_name='SMOKE-S7')");
$pdo->exec("DELETE FROM service_contract_assets WHERE contract_id IN (SELECT c0d FROM service_contracts WHERE customer_name='SMOKE-S7')");
$pdo->exec("DELETE FROM service_contract_sites WHERE contract_id IN (SELECT c0d FROM service_contracts WHERE customer_name='SMOKE-S7')");
$pdo->exec("DELETE FROM service_contracts WHERE customer_name='SMOKE-S7'");
$pdo->exec("DELETE FROM pm_template_items WHERE template_id IN (SELECT c0d FROM pm_templates WHERE code='SMOKE_S7')");
$pdo->exec("DELETE FROM pm_templates WHERE code='SMOKE_S7'");

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

$tpl = new PmTemplates();
$tid = $tpl->saveHeader(['code'=>'SMOKE_S7','name'=>'S7 Smoke','asset_type_id'=>$genId,'scope'=>'ASSET','cadence_type'=>'MONTHS','cadence_value'=>3,'is_active'=>1], 0);

$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-S7', 'customer_id'=>1,
    'contract_value'=>5000000, 'currency'=>'TZS', 'monthly_retainer'=>400000,
    'spare_policy'=>'COMPANY', 'invoice_cadence'=>'MONTHLY_RETAINER',
], 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-S7','size_value'=>60,'size_unit'=>'kVA','is_active'=>1]);
$sc->activate($cid, 0);

$ps = new PmServices();
$pmId = $ps->spawn($aid, $tid, null, date('Y-m-d'));

// Directly insert a photo row (simulating stashPhoto having succeeded)
$pdo->exec("INSERT INTO pm_service_photos
    (pm_service_id, file_path, original_name, mime, size_bytes, kind, caption, uploaded_by, uploaded_by_name)
    VALUES ($pmId, 'attachments/pm-photos/$pmId/fake.jpg', 'fake.jpg', 'image/jpeg', 12345, 'RESOLUTION', 'smoke test caption', 0, 'smoke')");
$photoId = (int)$pdo->lastInsertId();

// Test photosFor
$photos = $ps->photosFor($pmId);
echo 'PM photos: ' . count($photos) . ' (expect 1)' . PHP_EOL;
foreach ($photos as $ph) echo '  id=' . $ph['c0d'] . ' kind=' . $ph['kind'] . ' size=' . $ph['size_bytes'] . ' name=' . $ph['original_name'] . PHP_EOL;

// Test kind filter
$resPhotos = $ps->photosFor($pmId, 'RESOLUTION');
echo 'PM photos filter=RESOLUTION: ' . count($resPhotos) . ' (expect 1)' . PHP_EOL;
$sitePhotos = $ps->photosFor($pmId, 'SITE');
echo 'PM photos filter=SITE: ' . count($sitePhotos) . ' (expect 0)' . PHP_EOL;

// Test findPhoto
$found = $ps->findPhoto($photoId);
echo 'findPhoto returned: ' . (!empty($found) ? 'OK · path=' . $found['file_path'] : 'MISSING') . PHP_EOL;

// Test removePhoto (physical file doesn't exist so unlink is a no-op)
$ps->removePhoto($photoId);
$after = $ps->photosFor($pmId);
echo 'After remove: ' . count($after) . ' (expect 0)' . PHP_EOL;

// Callout side
$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'=>'Test','is_emergency'=>0,
], 0, 'smoke');

$pdo->exec("INSERT INTO callout_photos
    (callout_id, file_path, original_name, mime, size_bytes, kind, caption, uploaded_by, uploaded_by_name)
    VALUES ($coId, 'attachments/callout-photos/$coId/site.jpg', 'site.jpg', 'image/jpeg', 54321, 'SITE', 'site view', 0, 'smoke'),
           ($coId, 'attachments/callout-photos/$coId/resolution.jpg', 'resolution.jpg', 'image/jpeg', 67890, 'RESOLUTION', 'after fix', 0, 'smoke')");

$coPhotos = $co->photosFor($coId);
echo 'Callout photos: ' . count($coPhotos) . ' (expect 2)' . PHP_EOL;
foreach ($coPhotos as $ph) echo '  id=' . $ph['c0d'] . ' kind=' . $ph['kind'] . ' name=' . $ph['original_name'] . PHP_EOL;

// Filter test
$siteOnly = $co->photosFor($coId, 'SITE');
echo 'Callout photos filter=SITE: ' . count($siteOnly) . ' (expect 1)' . PHP_EOL;

// Test finding photo path save (direct DB insert since we can't run move_uploaded_file)
$itemId = (int)$pdo->query("SELECT c0d FROM pm_template_items WHERE template_id=$tid LIMIT 1")->fetchColumn();
if ($itemId > 0) {
    // Simulate what saveFindingPhoto does: insert a finding row with photo path
    $pdo->exec("INSERT INTO pm_service_findings (pm_service_id, template_item_id, result_photo_path)
                VALUES ($pmId, $itemId, 'attachments/pm-findings/$pmId/finding.jpg')");
    $findings = $ps->findingsFor($pmId);
    $foundFinding = false;
    foreach ($findings as $f) if ($f['result_photo_path'] === "attachments/pm-findings/$pmId/finding.jpg") { $foundFinding = true; break; }
    echo 'Finding with photo path saved: ' . ($foundFinding ? 'OK' : 'MISSING') . PHP_EOL;
}

// Cleanup
$pdo->exec("DELETE FROM pm_service_photos WHERE pm_service_id=$pmId");
$pdo->exec("DELETE FROM callout_photos WHERE callout_id=$coId");
$pdo->exec("DELETE FROM pm_service_findings WHERE pm_service_id=$pmId");
$pdo->exec("DELETE FROM pm_services WHERE c0d=$pmId");
$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");
$pdo->exec("DELETE FROM pm_template_items WHERE template_id=$tid");
$pdo->exec("DELETE FROM pm_templates WHERE c0d=$tid");
echo PHP_EOL . 'Cleanup done.' . PHP_EOL;
