<?php
/**
 * Live, end-to-end, construct-verify-revert proof of the dashboard.php
 * resolve_trade_id passed_phase fix. Uses "Phase Test 5K - Attempt 1"
 * (user 278d5983-...) — one of the three real drifted accounts named in
 * the task (lifecycle_state='phase_2_active', current_stage stuck at
 * 'phase_1').
 *
 * Clones a real draft trade as a template, attaches the clone to the
 * test account, POSTs account_status=passed_phase through the REAL
 * /dashboard resolve_trade_id handler (real router, real session), then
 * confirms lifecycle_state became 'phase_2_complete' — NOT the
 * 'phase_1_complete' the OLD (current_stage-trusting) code would have
 * written (already independently confirmed via read-only trace). Fully
 * reverts trading_accounts/challenge_accounts and deletes every
 * synthetic row afterward, verified via direct re-query.
 */
require_once __DIR__ . '/../config/config.php';

$pdo = new PDO(
    "mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=utf8mb4",
    DB_USER, DB_PASS,
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
);

$accountId = 'd207ae67-78fb-4951-8e1c-403b699d618a'; // Phase Test 5K - Attempt 1
$userId = '278d5983-d646-494f-a130-b22f7c321867';
$templateTradeId = '06360fd6-1faf-4eef-a6c2-009589452c64';

function uuid(): string {
    $data = random_bytes(16);
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

// ── 1. Snapshot original state ──────────────────────────────────────────
$snapTa = $pdo->prepare("SELECT * FROM trading_accounts WHERE id = ?");
$snapTa->execute([$accountId]);
$origTa = $snapTa->fetch();

$snapCa = $pdo->prepare("SELECT * FROM challenge_accounts WHERE account_id = ?");
$snapCa->execute([$accountId]);
$origCa = $snapCa->fetch();

$snapEvents = $pdo->prepare("SELECT COUNT(*) FROM lifecycle_events WHERE account_id = ?");
$snapEvents->execute([$accountId]);
$origEventCount = (int)$snapEvents->fetchColumn();

echo "Original trading_accounts.lifecycle_state: {$origTa['lifecycle_state']}\n";
echo "Original challenge_accounts.current_stage: {$origCa['current_stage']}\n";
echo "Original challenge_accounts.lifecycle_state: {$origCa['lifecycle_state']}\n";
echo "Original lifecycle_events count for this account: {$origEventCount}\n\n";

// ── 2. Clone a real draft trade as a template, repoint to the test account ──
$templateStmt = $pdo->prepare("SELECT * FROM trades WHERE id = ?");
$templateStmt->execute([$templateTradeId]);
$template = $templateStmt->fetch();
if (!$template) {
    throw new RuntimeException("Template trade not found");
}

$newTradeId = uuid();
$newLifecycleId = uuid();

$pdo->prepare("
    INSERT INTO checklist_results (id, trade_lifecycle_id, user_id, strategy_version_id, items_ticked, items_required, ticked_pct, status)
    VALUES (:id, :tlid, :uid, :svid, '[]', '[]', 100, 'completed')
")->execute([':id' => uuid(), ':tlid' => $newLifecycleId, ':uid' => $userId, ':svid' => $template['strategy_version_id']]);

$newRow = $template;
$newRow['id'] = $newTradeId;
$newRow['trade_lifecycle_id'] = $newLifecycleId;
$newRow['account_id'] = $accountId;
$newRow['user_id'] = $userId;
$newRow['status'] = 'open';
$newRow['closed_at'] = null;
$newRow['challenge_pnl'] = null;
$newRow['excess_pnl'] = null;
$newRow['broker_pnl'] = null;
$newRow['is_validation'] = 0;
$newRow['deleted_at'] = null;
$newRow['mt5_comment_hash'] = null; // unique index — template's value would collide

$cols = array_keys($newRow);
$placeholders = array_map(fn($c) => ':' . $c, $cols);
$sql = "INSERT INTO trades (" . implode(',', $cols) . ") VALUES (" . implode(',', $placeholders) . ")";
$params = [];
foreach ($newRow as $k => $v) { $params[':' . $k] = $v; }
$pdo->prepare($sql)->execute($params);

echo "Synthetic open trade created: {$newTradeId}\n\n";

// ── 3. Real HTTP POST through the actual /dashboard resolve_trade_id handler ──
$base = 'http://localhost:8080/traderalign';
$cookieJar = tempnam(sys_get_temp_dir(), 'zzcookie4');

$ch = curl_init("{$base}/public/_zz_test_autologin.php?uid=" . urlencode($userId));
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_COOKIEJAR => $cookieJar, CURLOPT_COOKIEFILE => $cookieJar]);
curl_exec($ch);
curl_close($ch);

$postFields = http_build_query([
    'resolve_trade_id' => $newTradeId,
    'outcome' => 'won',
    'actual_entry_price' => $template['entry_price'] ?? $template['actual_entry_price'] ?? 1.1000,
    'actual_exit_price' => $template['tp_price'] ?? 1.1050,
    'actual_sl_price' => $template['sl_price'] ?? 1.0950,
    'actual_pnl' => 10,
    'actual_lots' => $template['lots_per_position'] ?? 0.1,
    'account_status' => 'passed_phase',
]);

$ch = curl_init("{$base}/dashboard");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_COOKIEJAR => $cookieJar,
    CURLOPT_COOKIEFILE => $cookieJar,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $postFields,
]);
$resp = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
@unlink($cookieJar);

echo "POST /dashboard (resolve_trade_id, account_status=passed_phase) => HTTP {$code}\n";
if (stripos($resp, 'Warning:') !== false || stripos($resp, 'Fatal error') !== false) {
    echo "!!! PHP ERROR DETECTED IN RESPONSE\n";
    echo substr($resp, 0, 2000) . "\n";
}
echo "\n";

// ── 4. Confirm the fix took effect ──────────────────────────────────────
$afterTa = $pdo->prepare("SELECT lifecycle_state FROM trading_accounts WHERE id = ?");
$afterTa->execute([$accountId]);
$afterTaState = $afterTa->fetchColumn();

$afterCa = $pdo->prepare("SELECT lifecycle_state, passed_at FROM challenge_accounts WHERE account_id = ?");
$afterCa->execute([$accountId]);
$afterCaRow = $afterCa->fetch();

$afterEvents = $pdo->prepare("SELECT event_type FROM lifecycle_events WHERE account_id = ? ORDER BY occurred_at DESC LIMIT 1");
$afterEvents->execute([$accountId]);
$latestEventType = $afterEvents->fetchColumn();

echo "AFTER: trading_accounts.lifecycle_state = {$afterTaState}\n";
echo "AFTER: challenge_accounts.lifecycle_state = {$afterCaRow['lifecycle_state']}\n";
echo "AFTER: challenge_accounts.passed_at = {$afterCaRow['passed_at']}\n";
echo "AFTER: newest lifecycle_events.event_type = {$latestEventType}\n\n";

if ($afterTaState === 'phase_2_complete') {
    echo "PASS — correctly wrote 'phase_2_complete' (derived from lifecycle_state='phase_2_active'), NOT 'phase_1_complete' (which the OLD current_stage-trusting code would have written).\n\n";
} else {
    echo "!!! UNEXPECTED RESULT — expected 'phase_2_complete', got '{$afterTaState}'\n\n";
}

// ── 5. Revert everything ────────────────────────────────────────────────
$pdo->prepare("DELETE FROM trades WHERE id = ?")->execute([$newTradeId]);
$pdo->prepare("DELETE FROM checklist_results WHERE trade_lifecycle_id = ?")->execute([$newLifecycleId]);
$pdo->prepare("DELETE FROM lifecycle_events WHERE account_id = ? AND occurred_at > (NOW() - INTERVAL 5 MINUTE)")->execute([$accountId]);

$restoreTa = $pdo->prepare("
    UPDATE trading_accounts SET lifecycle_state = :ls, updated_at = :ua WHERE id = :id
");
$restoreTa->execute([':ls' => $origTa['lifecycle_state'], ':ua' => $origTa['updated_at'], ':id' => $accountId]);

$restoreCa = $pdo->prepare("
    UPDATE challenge_accounts SET lifecycle_state = :ls, passed_at = :pa, updated_at = :ua WHERE account_id = :id
");
$restoreCa->execute([':ls' => $origCa['lifecycle_state'], ':pa' => $origCa['passed_at'], ':ua' => $origCa['updated_at'], ':id' => $accountId]);

// ── 6. Verify revert ─────────────────────────────────────────────────────
$finalTa = $pdo->prepare("SELECT lifecycle_state FROM trading_accounts WHERE id = ?");
$finalTa->execute([$accountId]);
$finalTaState = $finalTa->fetchColumn();

$finalCa = $pdo->prepare("SELECT lifecycle_state, passed_at FROM challenge_accounts WHERE account_id = ?");
$finalCa->execute([$accountId]);
$finalCaRow = $finalCa->fetch();

$finalEvents = $pdo->prepare("SELECT COUNT(*) FROM lifecycle_events WHERE account_id = ?");
$finalEvents->execute([$accountId]);
$finalEventCount = (int)$finalEvents->fetchColumn();

$finalTradeCheck = $pdo->prepare("SELECT COUNT(*) FROM trades WHERE id = ?");
$finalTradeCheck->execute([$newTradeId]);
$tradeStillExists = (int)$finalTradeCheck->fetchColumn();

echo "REVERTED: trading_accounts.lifecycle_state = {$finalTaState} (matches original: " . ($finalTaState === $origTa['lifecycle_state'] ? 'YES' : 'NO — MISMATCH') . ")\n";
echo "REVERTED: challenge_accounts.lifecycle_state = {$finalCaRow['lifecycle_state']} (matches original: " . ($finalCaRow['lifecycle_state'] === $origCa['lifecycle_state'] ? 'YES' : 'NO — MISMATCH') . ")\n";
echo "REVERTED: challenge_accounts.passed_at matches original: " . ($finalCaRow['passed_at'] == $origCa['passed_at'] ? 'YES' : 'NO — MISMATCH (' . var_export($finalCaRow['passed_at'], true) . ' vs ' . var_export($origCa['passed_at'], true) . ')') . "\n";
echo "REVERTED: lifecycle_events count back to original ({$origEventCount}): " . ($finalEventCount === $origEventCount ? 'YES' : "NO — now {$finalEventCount}") . "\n";
echo "REVERTED: synthetic trade deleted: " . ($tradeStillExists === 0 ? 'YES' : 'NO — STILL EXISTS') . "\n";
