<?php
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/MultiTenant/TenantManager.php';

// Require authentication
AuthManager::requireAuth();

$errors = [];
$success = '';

// Handle plan selection
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $planId = (int) ($_POST['plan_id'] ?? 0);
    $workspaceId = (int) ($_POST['workspace_id'] ?? 0);
    
    if ($planId && $workspaceId) {
        try {
            $pdo = getPDO();
            
            // Update workspace plan
            $stmt = $pdo->prepare("UPDATE companies SET plan_id = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$planId, $workspaceId]);
            
            // Update or create subscription
            $trialEndsAt = date('Y-m-d H:i:s', strtotime('+14 days'));
            $periodEnd = date('Y-m-d H:i:s', strtotime('+1 month'));
            
            // Check if subscription exists
            $stmt = $pdo->prepare("SELECT id FROM subscriptions WHERE company_id = ?");
            $stmt->execute([$workspaceId]);
            $subscription = $stmt->fetch();
            
            if ($subscription) {
                // Update existing subscription
                $stmt = $pdo->prepare("UPDATE subscriptions SET plan_id = ?, status = 'trial', billing_cycle = 'monthly', current_period_start = NOW(), current_period_end = ?, trial_ends_at = ?, updated_at = NOW() WHERE company_id = ?");
                $stmt->execute([$planId, $periodEnd, $trialEndsAt, $workspaceId]);
            } else {
                // Create new subscription
                $stmt = $pdo->prepare("INSERT INTO subscriptions (company_id, plan_id, status, billing_cycle, current_period_start, current_period_end, trial_ends_at, created_at, updated_at) VALUES (?, ?, 'trial', 'monthly', NOW(), ?, ?, NOW(), NOW())");
                $stmt->execute([$workspaceId, $planId, $periodEnd, $trialEndsAt]);
            }
            
            // Update session
            $_SESSION['current_company']['plan_id'] = $planId;
            
            header('Location: /index.php?success=plan_updated');
            exit;
            
        } catch (Exception $e) {
            $errors[] = 'Failed to update plan: ' . $e->getMessage();
        }
    } else {
        $errors[] = 'Invalid plan or workspace selection';
    }
}

// Get current workspace
$workspaceId = $_GET['workspace'] ?? $_SESSION['current_company_id'] ?? 1;
$pdo = getPDO();
$stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ?");
$stmt->execute([$workspaceId]);
$workspace = $stmt->fetch();

if (!$workspace) {
    header('Location: /index.php');
    exit;
}

// Get subscription plans
$subscriptionPlans = [];
try {
    $stmt = $pdo->query("SELECT * FROM subscription_plans WHERE is_active = 1 ORDER BY price_monthly ASC");
    $subscriptionPlans = $stmt->fetchAll();
} catch (PDOException $e) {
    // Default plans if table doesn't exist
    $subscriptionPlans = [
        [
            'id' => 1,
            'name' => 'Starter',
            'price_monthly' => 29,
            'price_yearly' => 290,
            'features' => json_encode(['Up to 5 clients', 'Up to 10 proposals/month', 'Basic support']),
            'description' => 'Perfect for individuals and small teams just getting started.'
        ],
        [
            'id' => 2,
            'name' => 'Professional',
            'price_monthly' => 79,
            'price_yearly' => 790,
            'features' => json_encode(['Up to 50 clients', 'Unlimited proposals', 'Priority support', 'Custom branding']),
            'description' => 'Ideal for growing businesses that need more features and support.'
        ],
        [
            'id' => 3,
            'name' => 'Enterprise',
            'price_monthly' => 199,
            'price_yearly' => 1990,
            'features' => json_encode(['Unlimited clients', 'Unlimited everything', '24/7 support', 'API access', 'Custom integrations']),
            'description' => 'For large organizations with advanced needs and custom requirements.'
        ]
    ];
}

$user = AuthManager::getCurrentUser();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Select Plan - Keelance</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        border: "hsl(var(--border))",
                        input: "hsl(var(--input))",
                        ring: "hsl(var(--ring))",
                        background: "hsl(var(--background))",
                        foreground: "hsl(var(--foreground))",
                        primary: {
                            DEFAULT: "hsl(var(--primary))",
                            foreground: "hsl(var(--primary-foreground))",
                        },
                        secondary: {
                            DEFAULT: "hsl(var(--secondary))",
                            foreground: "hsl(var(--secondary-foreground))",
                        },
                        destructive: {
                            DEFAULT: "hsl(var(--destructive))",
                            foreground: "hsl(var(--destructive-foreground))",
                        },
                        muted: {
                            DEFAULT: "hsl(var(--muted))",
                            foreground: "hsl(var(--muted-foreground))",
                        },
                        accent: {
                            DEFAULT: "hsl(var(--accent))",
                            foreground: "hsl(var(--accent-foreground))",
                        },
                        popover: {
                            DEFAULT: "hsl(var(--popover))",
                            foreground: "hsl(var(--popover-foreground))",
                        },
                        card: {
                            DEFAULT: "hsl(var(--card))",
                            foreground: "hsl(var(--card-foreground))",
                        },
                    },
                    borderRadius: {
                        lg: "var(--radius)",
                        md: "calc(var(--radius) - 2px)",
                        sm: "calc(var(--radius) - 4px)",
                    },
                }
            }
        }
    </script>
    <style>
        :root {
            --background: 0 0% 100%;
            --foreground: 222.2 84% 4.9%;
            --card: 0 0% 100%;
            --card-foreground: 222.2 84% 4.9%;
            --popover: 0 0% 100%;
            --popover-foreground: 222.2 84% 4.9%;
            --primary: 221.2 83.2% 53.3%;
            --primary-foreground: 210 40% 98%;
            --secondary: 210 40% 96%;
            --secondary-foreground: 222.2 84% 4.9%;
            --muted: 210 40% 96%;
            --muted-foreground: 215.4 16.3% 46.9%;
            --accent: 210 40% 96%;
            --accent-foreground: 222.2 84% 4.9%;
            --destructive: 0 84.2% 60.2%;
            --destructive-foreground: 210 40% 98%;
            --border: 214.3 31.8% 91.4%;
            --input: 214.3 31.8% 91.4%;
            --ring: 221.2 83.2% 53.3%;
            --radius: 0.5rem;
        }
    </style>
</head>
<body class="min-h-screen bg-background font-sans antialiased">
    <div class="min-h-screen flex flex-col">
        <!-- Navigation -->
        <header class="border-b border-border bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
            <div class="max-w-5xl mx-auto px-4 py-4">
                <div class="flex justify-between items-center">
                    <div class="text-xl font-bold tracking-tight text-foreground">Keelance</div>
                    <div class="flex items-center space-x-4">
                        <span class="text-sm text-muted-foreground">Welcome, <?= htmlspecialchars($user['name']) ?></span>
                        <a href="/index.php" class="text-sm text-primary underline-offset-4 hover:underline">← Dashboard</a>
                    </div>
                </div>
            </div>
        </header>

        <!-- Main Content -->
        <main class="flex-1">
            <div class="max-w-6xl mx-auto py-8 px-4">
                <!-- Header -->
                <div class="text-center space-y-4 mb-8">
                    <h1 class="text-3xl font-bold tracking-tight text-foreground">Choose Your Plan</h1>
                    <p class="text-muted-foreground max-w-2xl mx-auto">
                        Select the perfect plan for your workspace. Start with a 14-day free trial, no credit card required.
                    </p>
                    <div class="inline-flex items-center px-4 py-2 bg-secondary rounded-lg">
                        <span class="text-sm text-secondary-foreground">Current workspace: <?= htmlspecialchars($workspace['name']) ?></span>
                    </div>
                </div>

                <?php if (!empty($errors)): ?>
                    <div class="rounded-lg bg-destructive/15 p-4 mb-6 max-w-2xl mx-auto text-sm text-destructive">
                        <?php foreach ($errors as $error): ?>
                            <p><?= htmlspecialchars($error) ?></p>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>

                <!-- Plans Grid -->
                <form method="POST" class="space-y-8">
                    <input type="hidden" name="workspace_id" value="<?= $workspace['id'] ?>">
                    
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                        <?php foreach ($subscriptionPlans as $index => $plan): ?>
                            <div class="relative <?= $index === 1 ? 'ring-2 ring-primary' : '' ?>">
                                <?php if ($index === 1): ?>
                                    <div class="absolute -top-3 left-1/2 transform -translate-x-1/2 z-10">
                                        <span class="bg-primary text-primary-foreground px-3 py-1 rounded-full text-xs font-semibold">MOST POPULAR</span>
                                    </div>
                                <?php endif; ?>
                                
                                <div class="card border border-border bg-card text-card-foreground cursor-pointer hover:shadow-lg transition-all duration-300">
                                    <div class="p-8">
                                        <div class="text-center">
                                            <h3 class="text-xl font-semibold text-foreground"><?= htmlspecialchars($plan['name']) ?></h3>
                                            <p class="text-muted-foreground mt-2"><?= htmlspecialchars($plan['description'] ?? '') ?></p>
                                            
                                            <div class="mt-6">
                                                <span class="text-4xl font-bold text-foreground">$<?= number_format($plan['price_monthly'], 0) ?></span>
                                                <span class="text-muted-foreground">/month</span>
                                            </div>
                                            
                                            <div class="mt-2 text-sm text-muted-foreground">
                                                billed annually at $<?= number_format($plan['price_yearly'], 0) ?> (save 17%)
                                            </div>
                                        </div>
                                        
                                        <ul class="mt-8 space-y-4 text-sm text-muted-foreground">
                                            <?php 
                                            $features = json_decode($plan['features'], true) ?? [];
                                            foreach ($features as $feature): ?>
                                                <li class="flex items-start">
                                                    <span class="text-green-600 mr-2 mt-0.5">✓</span>
                                                    <span><?= htmlspecialchars($feature) ?></span>
                                                </li>
                                            <?php endforeach; ?>
                                        </ul>
                                        
                                        <div class="mt-8">
                                            <input type="radio" name="plan_id" value="<?= $plan['id'] ?>" class="sr-only peer" <?= $index === 1 ? 'checked' : ''; ?> id="plan_<?= $plan['id'] ?>">
                                            <label for="plan_<?= $plan['id'] ?>" class="block w-full py-3 px-4 rounded-lg text-center font-medium cursor-pointer transition-colors
                                                <?= $index === 1 
                                                    ? 'bg-primary text-primary-foreground' 
                                                    : 'bg-secondary text-secondary-foreground hover:bg-accent'; ?>">
                                                <?= $workspace['plan_id'] == $plan['id'] ? 'Current Plan' : 'Select Plan' ?>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Features Comparison -->
                    <div class="card border border-border bg-card text-card-foreground">
                        <div class="p-8">
                            <h2 class="text-xl font-semibold text-foreground mb-6">Feature Comparison</h2>
                            <div class="overflow-x-auto">
                                <table class="w-full">
                                    <thead>
                                        <tr class="border-b border-border">
                                            <th class="text-left py-3 px-4 font-medium text-foreground">Feature</th>
                                            <?php foreach ($subscriptionPlans as $plan): ?>
                                                <th class="text-center py-3 px-4 font-medium text-foreground"><?= htmlspecialchars($plan['name']) ?></th>
                                            <?php endforeach; ?>
                                        </tr>
                                    </thead>
                                    <tbody class="divide-y divide-border">
                                        <tr>
                                            <td class="py-3 px-4 text-muted-foreground">Clients</td>
                                            <td class="py-3 px-4 text-center text-foreground">Up to 5</td>
                                            <td class="py-3 px-4 text-center text-foreground">Up to 50</td>
                                            <td class="py-3 px-4 text-center text-foreground">Unlimited</td>
                                        </tr>
                                        <tr>
                                            <td class="py-3 px-4 text-muted-foreground">Proposals per month</td>
                                            <td class="py-3 px-4 text-center text-foreground">10</td>
                                            <td class="py-3 px-4 text-center text-foreground">Unlimited</td>
                                            <td class="py-3 px-4 text-center text-foreground">Unlimited</td>
                                        </tr>
                                        <tr>
                                            <td class="py-3 px-4 text-muted-foreground">Support</td>
                                            <td class="py-3 px-4 text-center text-foreground">Basic</td>
                                            <td class="py-3 px-4 text-center text-foreground">Priority</td>
                                            <td class="py-3 px-4 text-center text-foreground">24/7</td>
                                        </tr>
                                        <tr>
                                            <td class="py-3 px-4 text-muted-foreground">API Access</td>
                                            <td class="py-3 px-4 text-center text-destructive">✗</td>
                                            <td class="py-3 px-4 text-center text-destructive">✗</td>
                                            <td class="py-3 px-4 text-center text-green-600">✓</td>
                                        </tr>
                                        <tr>
                                            <td class="py-3 px-4 text-muted-foreground">Custom Integrations</td>
                                            <td class="py-3 px-4 text-center text-destructive">✗</td>
                                            <td class="py-3 px-4 text-center text-destructive">✗</td>
                                            <td class="py-3 px-4 text-center text-green-600">✓</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <!-- Submit Button -->
                    <div class="text-center space-y-3">
                        <button type="submit" class="inline-flex items-center justify-center whitespace-nowrap rounded-md text-lg font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 bg-primary text-primary-foreground shadow hover:bg-primary/90 h-10 px-8">
                            Update Plan
                        </button>
                        <p class="text-sm text-muted-foreground">
                            14-day free trial • Cancel anytime • No setup fees
                        </p>
                    </div>
                </form>
            </div>
        </main>

        <!-- Universal Footer -->
        <?php include __DIR__ . '/components/footer.php'; ?>
    </div>

    <script>
        // Handle plan selection
        document.addEventListener('DOMContentLoaded', function() {
            const planInputs = document.querySelectorAll('input[name="plan_id"]');
            planInputs.forEach(input => {
                input.addEventListener('change', function() {
                    // Update all labels
                    document.querySelectorAll('label[for^="plan_"]').forEach(label => {
                        if (!label.textContent.includes('Current Plan')) {
                            label.className = 'block w-full py-3 px-4 rounded-lg text-center font-medium cursor-pointer transition-colors bg-secondary text-secondary-foreground hover:bg-accent';
                            label.textContent = 'Select Plan';
                        }
                    });
                    
                    // Highlight selected plan
                    if (this.checked) {
                        const label = document.querySelector(`label[for="${this.id}"]`);
                        if (!label.textContent.includes('Current Plan')) {
                            label.className = 'block w-full py-3 px-4 rounded-lg text-center font-medium cursor-pointer transition-colors bg-primary text-primary-foreground';
                            label.textContent = 'Selected';
                        }
                    }
                });
            });
        });
    </script>
</body>
</html>
