<?php

function normalizeChallengeType(?string $columnType, ?array $rules = null): string
{
    $rulesType = is_array($rules) ? ($rules['challenge_type'] ?? null) : null;
    $type = $columnType ?: $rulesType ?: 'two_step';
    if ($type === 'instant') {
        return 'instant_funding';
    }

    return $type;
}

function isInstantFundingChallenge(?string $challengeType, ?array $rules = null): bool
{
    return normalizeChallengeType($challengeType, $rules) === 'instant_funding';
}

function isFundedStage(?string $lifecycleState, ?string $currentStage = null): bool
{
    if ($lifecycleState === 'funded_active') {
        return true;
    }

    return $currentStage === 'funded';
}

function isActiveChallengePhase(?string $challengeType, ?string $lifecycleState, ?string $currentStage = null, ?array $rules = null): bool
{
    if (isInstantFundingChallenge($challengeType, $rules)) {
        return false;
    }

    if (isFundedStage($lifecycleState, $currentStage)) {
        return false;
    }

    return true;
}

function resolvePropFirmDisplayLabel(?string $lifecycleState, ?string $challengeType, ?string $currentStage = null, ?array $rules = null): string
{
    if (isInstantFundingChallenge($challengeType, $rules)) {
        return 'Instant Funding';
    }

    if (isFundedStage($lifecycleState, $currentStage)) {
        return 'Funded';
    }

    $stage = $currentStage;
    if (!$stage && $lifecycleState) {
        if (str_starts_with($lifecycleState, 'phase_3')) {
            $stage = 'phase_3';
        } elseif (str_starts_with($lifecycleState, 'phase_2')) {
            $stage = 'phase_2';
        } else {
            $stage = 'phase_1';
        }
    }

    return match ($stage) {
        'phase_2' => 'Phase 2',
        'phase_3' => 'Phase 3',
        default => 'Phase 1',
    };
}

function getBreachReasonGroups(bool $isChallengePhase): array
{
    $mandatory = [
        'OVERALL_DRAWDOWN' => 'Overall Drawdown',
        'DAILY_LOSS_LIMIT' => 'Daily Loss Limit',
    ];

    if ($isChallengePhase) {
        $mandatory['PROFIT_TARGET'] = 'Profit Target';
    }

    $optional = [
        'CONSISTENCY_SCORE' => 'Consistency Score',
        'PROFIT_SPLIT' => 'Profit Split',
        'RULE_VIOLATION' => 'Rule Violation',
        'NEWS_TRADING_RESTRICTION' => 'News Trading Restriction',
        'MANUAL_TRADING_ERROR' => 'Manual Trading Error',
        'OTHER' => 'Other',
    ];

    return ['mandatory' => $mandatory, 'optional' => $optional];
}

function renderBreachReasonSelect(string $selectId, string $hiddenId, bool $isChallengePhase, ?string $otherInputId = null): string
{
    $groups = getBreachReasonGroups($isChallengePhase);
    $onChange = 'handleBreachReasonChange('
        . json_encode($selectId) . ','
        . json_encode($hiddenId)
        . ($otherInputId ? ',' . json_encode($otherInputId) : '')
        . ')';

    $html = '<select id="' . htmlspecialchars($selectId) . '" onchange="' . htmlspecialchars($onChange) . '">';
    $html .= '<option value="">Select reason...</option>';
    $html .= '<optgroup label="Mandatory">';
    foreach ($groups['mandatory'] as $value => $label) {
        $html .= '<option value="' . htmlspecialchars($value) . '">' . htmlspecialchars($label) . '</option>';
    }
    $html .= '</optgroup><optgroup label="Optional">';
    foreach ($groups['optional'] as $value => $label) {
        $html .= '<option value="' . htmlspecialchars($value) . '">' . htmlspecialchars($label) . '</option>';
    }
    $html .= '</optgroup></select>';

    if ($otherInputId) {
        $html .= '<input type="text" id="' . htmlspecialchars($otherInputId) . '" class="breach-other-input" placeholder="Specify reason..." style="display:none;margin-top:.35rem;width:100%;max-width:280px;height:2rem;padding:0 .5rem;background:var(--background);border:1px solid var(--border);border-radius:var(--radius-sm);color:var(--foreground);font-size:.78rem;font-family:inherit" oninput="' . htmlspecialchars($onChange) . '">';
    }

    return $html;
}
