<?php
declare(strict_types=1);

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../src/helpers.php';
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/../src/Billing/SubscriptionManager.php';
require_once __DIR__ . '/../src/SuperAdmin/PlatformSettings.php';
require_once __DIR__ . '/../src/secure_workspace.php';

AuthManager::requireAuth();

$user = AuthManager::getCurrentUser();
$workspaceParam = $_GET['workspace'] ?? null;

// Currency handling - use workspace preference if available
$selectedCurrency = $_GET['currency'] ?? $_SESSION['currency'] ?? $_COOKIE['currency'] ?? 'USD';
if (!in_array($selectedCurrency, ['USD', 'INR'])) {
    $selectedCurrency = 'USD';
}
$_SESSION['currency'] = $selectedCurrency;
setcookie('currency', $selectedCurrency, time() + 86400 * 365, '/');

$currencySymbol = $selectedCurrency === 'INR' ? '₹' : '$';
$isIndia = $selectedCurrency === 'INR';

// Get trial settings
$trialEnabled = PlatformSettings::get('trial_enabled', true);
$trialDays = (int) PlatformSettings::get('trial_days', 14);
$trialApplyTo = PlatformSettings::get('trial_apply_to', 'all');
$trialPlanId = (int) PlatformSettings::get('trial_plan_id', 1);

// Helper function to check if trial applies to a plan
function planHasTrialWP(int $planId, bool $trialEnabled, int $trialDays, string $trialApplyTo, int $trialPlanId): bool {
    if (!$trialEnabled || $trialDays <= 0) {
        return false;
    }
    if ($trialApplyTo === 'all') {
        return true;
    }
    return $planId === $trialPlanId;
}

$billingCycle = ($_GET['cycle'] ?? 'monthly') === 'yearly' ? 'yearly' : 'monthly';
$plans = SubscriptionManager::getPlans();
$preselectedPlan = (int) ($_GET['plan_id'] ?? 0);

function cycleUrl(string $cycle, array $query): string {
    $query['cycle'] = $cycle;
    return '/workspace-plans.php' . ($query ? '?' . http_build_query($query) : '');
}

function currencyUrl(string $currency, array $query): string {
    $query['currency'] = $currency;
    return '/workspace-plans.php' . ($query ? '?' . http_build_query($query) : '');
}

$monthlyUrl = cycleUrl('monthly', $_GET);
$yearlyUrl = cycleUrl('yearly', $_GET);
$usdUrl = currencyUrl('USD', $_GET);
$inrUrl = currencyUrl('INR', $_GET);
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Select Workspace Plan · Keelance</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
    <script>
        (function() {
            var saved = localStorage.getItem('theme') || 'dark';
            document.documentElement.setAttribute('data-theme', saved);
        })();
    </script>
</head>
<body class="app-shell workspace-plans-page">
<?php require_once __DIR__ . '/navigation.php'; renderNavigationNew('Workspace plans', 'dark'); ?>

<div class="app-shell__content">
<div class="main-container">
    <?php
    require_once __DIR__ . '/components/headers/page-header.php';
    $workspaceQuery = $workspaceParam ? '?workspace=' . urlencode((string) $workspaceParam) : '';
    renderPageHeader(
        breadcrumbs: [
            ['label' => 'Home', 'url' => '/index.php', 'icon' => 'M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6'],
        ],
        currentPage: 'Workspace plans',
        actions: [],
        workspaceQuery: $workspaceQuery
    );
    ?>

    <main>
        <div class="dash-container">
            <?php
            $anyPlanHasTrial = $trialEnabled && $trialDays > 0;
            $trialBannerText = $trialApplyTo === 'all'
                ? "Start your {$trialDays}-day free trial on any plan!"
                : "Start your {$trialDays}-day free trial!";
            ?>

            <?php if ($anyPlanHasTrial): ?>
                <div class="dash-section">
                    <div class="status-banner success" style="text-align: center;">
                        <div style="font-weight: 600;">🎉 <?= h($trialBannerText) ?></div>
                        <div style="margin-top: 4px; font-size: 12px; color: var(--text-secondary);">No credit card required. Cancel anytime.</div>
                    </div>
                </div>
            <?php endif; ?>

            <div class="dash-section">
                <div class="funnel-hero" style="margin-bottom: 0;">
                    <p class="section-title" style="margin: 0 0 8px;">New workspace</p>
                    <h1 class="funnel-title">Choose a plan for your new workspace</h1>
                    <p class="funnel-subtitle">Pick a plan that fits this workspace. You can change or upgrade later from billing.</p>
                </div>
            </div>

            <div class="dash-section">
                <div class="row" style="justify-content: center; flex-wrap: wrap;">
                    <span class="funnel-subtle">Billing cycle</span>
                    <div class="segmented">
                        <a href="<?= h($monthlyUrl) ?>" class="segmented__item <?= $billingCycle === 'monthly' ? 'segmented__item--active' : '' ?>">Monthly</a>
                        <a href="<?= h($yearlyUrl) ?>" class="segmented__item <?= $billingCycle === 'yearly' ? 'segmented__item--active' : '' ?>">Yearly</a>
                    </div>

                    <span class="funnel-subtle" style="margin-left: 12px;">Currency</span>
                    <div class="segmented">
                        <a href="<?= h($usdUrl) ?>" class="segmented__item <?= $selectedCurrency === 'USD' ? 'segmented__item--active' : '' ?>">$ USD</a>
                        <a href="<?= h($inrUrl) ?>" class="segmented__item <?= $selectedCurrency === 'INR' ? 'segmented__item--active' : '' ?>">₹ INR</a>
                    </div>
                </div>
            </div>

            <?php if (empty($plans)): ?>
                <div class="dash-section">
                    <div class="alert" style="text-align: center;">No plans are available right now. Please contact support.</div>
                </div>
            <?php else: ?>
                <div class="dash-section">
                    <div class="plans-grid">
                        <?php foreach ($plans as $index => $plan): ?>
                        <?php
                        $isPopular = !empty($plan['is_popular']) || !empty($plan['highlight']) || $index === 1;
                        
                        // Get prices based on currency
                        if ($selectedCurrency === 'INR') {
                            $monthlyPrice = $plan['price_monthly_inr'] ?? $plan['price_monthly'] * 83;
                            $yearlyPrice = $plan['price_yearly_inr'] ?? $plan['price_yearly'] * 83;
                        } else {
                            $monthlyPrice = $plan['price_monthly'];
                            $yearlyPrice = $plan['price_yearly'];
                        }
                        
                        $planPrice = $billingCycle === 'yearly' ? $yearlyPrice : $monthlyPrice;
                        $secondaryLabel = $billingCycle === 'yearly'
                            ? sprintf('%s%0.2f/mo when billed annually', $currencySymbol, $yearlyPrice / 12)
                            : sprintf('%s%0.2f/year when billed monthly', $currencySymbol, $yearlyPrice);
                        $workspaceQuery = $workspaceParam ? '&workspace=' . urlencode((string) $workspaceParam) : '';
                        $continueUrl = '/create-workspace.php?plan_id=' . $plan['id'] . '&cycle=' . $billingCycle . '&currency=' . $selectedCurrency . $workspaceQuery;
                        ?>
                        <section class="card plan-card">
                            <?php if ($isPopular): ?>
                                <div class="status-chip" style="align-self: flex-start;">Most popular</div>
                            <?php endif; ?>

                            <div class="plan-card__header">
                                <h3 class="plan-card__name"><?= h($plan['name']) ?></h3>
                                <?php if (!empty($plan['description'])): ?>
                                    <p class="plan-card__desc"><?= h($plan['description']) ?></p>
                                <?php endif; ?>
                            </div>

                            <div>
                                <div class="plan-card__price">
                                    <span class="plan-card__price-value"><?= $currencySymbol ?><?= number_format((float) $planPrice, 2) ?></span>
                                    <span class="plan-card__price-label">/<?= $billingCycle === 'yearly' ? 'year' : 'month' ?></span>
                                </div>
                                <div class="plan-card__meta"><?= h($secondaryLabel) ?></div>
                            </div>

                            <ul class="plan-card__features">
                                <?php foreach (($plan['features'] ?? []) as $feature): ?>
                                    <li class="plan-card__feature"><?= h($feature) ?></li>
                                <?php endforeach; ?>
                            </ul>

                            <?php $thisPlanHasTrial = planHasTrialWP((int)$plan['id'], $trialEnabled, $trialDays, $trialApplyTo, $trialPlanId); ?>
                            <div>
                                <a href="<?= h($continueUrl) ?>" class="btn-primary btn-block">
                                    <?php if ($thisPlanHasTrial): ?>
                                        Start <?= (int) $trialDays ?>-day free trial
                                    <?php else: ?>
                                        Get started
                                    <?php endif; ?>
                                </a>
                                <?php if ($thisPlanHasTrial): ?>
                                    <p class="checkout-hint" style="text-align: center;">No credit card required</p>
                                <?php endif; ?>
                            </div>
                        </section>
                    <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </main>
</div>
</div>

<?php include __DIR__ . '/footer.php'; ?>

</body>
</html>
