<?php
session_start();
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../src/helpers.php';
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/Billing/SubscriptionManager.php';
require_once __DIR__ . '/../src/SuperAdmin/PlatformSettings.php';

// Currency handling
$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 planHasTrial(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;
}

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

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

$billingCycle = ($_GET['cycle'] ?? 'monthly') === 'yearly' ? 'yearly' : 'monthly';
$subscriptionPlans = SubscriptionManager::getPlans();
$preselectedPlan = (int) ($_GET['plan'] ?? 0);
$monthlyToggleUrl = buildCycleUrl('monthly', $_GET);
$yearlyToggleUrl = buildCycleUrl('yearly', $_GET);
$usdUrl = buildCurrencyUrl('USD', $_GET);
$inrUrl = buildCurrencyUrl('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>Choose Your 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>
    <div class="funnel-shell">
        <header class="funnel-header">
            <div class="funnel-header__inner">
                <a class="funnel-header__brand" href="/">
                    <img src="/assets/Keelance-Logo Light.svg" alt="Keelance" class="funnel-header__logo theme-logo--dark">
                    <img src="/assets/KeelanceLogo.png" alt="Keelance" class="funnel-header__logo theme-logo--light">
                </a>
                <div class="funnel-header__actions">
                    <span class="funnel-subtle">Already have an account?</span>
                    <a href="/login.php" class="btn-secondary btn-sm">Sign in</a>
                </div>
            </div>
        </header>

        <main class="funnel-main">
            <div class="page-narrow">
                <?php 
                // Show trial banner only if trial is enabled
                $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): ?>
                <!-- Trial Banner -->
                <div class="status-banner success" style="text-align: center;">
                    <div style="font-weight: 600;"><?= htmlspecialchars($trialBannerText) ?></div>
                    <div style="margin-top: 4px; font-size: 12px; color: var(--text-secondary);">No credit card required. Cancel anytime.</div>
                </div>
                <?php endif; ?>

                <!-- Header -->
                <div class="funnel-hero">
                    <h1 class="funnel-title">Choose Your Plan</h1>
                    <p class="funnel-subtitle">Pick the plan that grows with your agency. Start in minutes.</p>

                    <div style="margin-top: 14px; display: flex; justify-content: center; flex-wrap: wrap; gap: 12px;">
                        <div class="row" style="justify-content: center; flex-wrap: wrap;">
                            <span class="funnel-subtle">Billing cycle</span>
                            <div class="segmented">
                                <a href="<?= htmlspecialchars($monthlyToggleUrl) ?>" class="segmented__item <?= $billingCycle === 'monthly' ? 'segmented__item--active' : '' ?>">Monthly</a>
                                <a href="<?= htmlspecialchars($yearlyToggleUrl) ?>" class="segmented__item <?= $billingCycle === 'yearly' ? 'segmented__item--active' : '' ?>">Yearly</a>
                            </div>
                        </div>

                        <div class="row" style="justify-content: center; flex-wrap: wrap;">
                            <span class="funnel-subtle">Currency</span>
                            <div class="segmented">
                                <a href="<?= htmlspecialchars($usdUrl) ?>" class="segmented__item <?= $selectedCurrency === 'USD' ? 'segmented__item--active' : '' ?>">$ USD</a>
                                <a href="<?= htmlspecialchars($inrUrl) ?>" class="segmented__item <?= $selectedCurrency === 'INR' ? 'segmented__item--active' : '' ?>">₹ INR</a>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Plans Grid -->
                <div class="plans-grid">
                    <?php foreach ($subscriptionPlans as $index => $plan): ?>
                        <?php
                            // 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'];
                            }
                            
                            $cyclePrice = $billingCycle === 'yearly' ? $yearlyPrice : $monthlyPrice;
                            $cycleLabel = $billingCycle === 'yearly' ? 'year' : 'month';
                            $secondaryLabel = $billingCycle === 'yearly'
                                ? sprintf('%s%0.2f/mo when billed annually', $currencySymbol, $yearlyPrice / 12)
                                : sprintf('%s%0.2f/year when billed monthly', $currencySymbol, $yearlyPrice);
                            $isHighlighted = !empty($plan['is_popular']) || !empty($plan['highlight']);
                        ?>
                        <section class="card plan-card">
                            <?php if ($isHighlighted): ?>
                                <div class="status-chip" style="align-self: flex-start;">Most popular</div>
                            <?php endif; ?>

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

                            <div>
                                <div class="plan-card__price">
                                    <span class="plan-card__price-value"><?= $currencySymbol ?><?= number_format($cyclePrice, 2) ?></span>
                                    <span class="plan-card__price-label">/<?= htmlspecialchars($cycleLabel) ?></span>
                                </div>
                                <div class="plan-card__meta"><?= htmlspecialchars($secondaryLabel) ?></div>
                            </div>

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

                            <?php $thisPlanHasTrial = planHasTrial((int)$plan['id'], $trialEnabled, $trialDays, $trialApplyTo, $trialPlanId); ?>
                            <div>
                                <a href="/signup.php?plan=<?= $plan['id'] ?>&cycle=<?= $billingCycle ?>&currency=<?= $selectedCurrency ?>" 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>

                <!-- Direct Links Info -->
                <div style="margin-top: 18px; text-align: center;">
                    <p class="funnel-subtle">
                        Want to share a specific plan? Use these direct links:
                    </p>
                    <div class="row" style="justify-content: center; flex-wrap: wrap; margin-top: 10px;">
                        <?php foreach ($subscriptionPlans as $plan): ?>
                            <a href="/signup.php?plan=<?= $plan['id'] ?>&cycle=<?= $billingCycle ?>" class="btn-secondary btn-sm">
                                <?= htmlspecialchars($plan['name']) ?>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </main>

        <!-- Global Footer -->
        <?php include __DIR__ . '/footer.php'; ?>
    </div>
</body>
</html>
