<?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 authentication and admin access
AuthManager::requireAuth();

// Check if user is admin (you might want to add an is_admin field to users table)
$user = AuthManager::getCurrentUser();
// For now, let's assume user ID 1 is admin
if ($user['id'] != 1) {
    header('Location: /index.php');
    exit;
}

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

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add_plan') {
        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $priceMonthly = (float) ($_POST['price_monthly'] ?? 0);
        $priceYearly = (float) ($_POST['price_yearly'] ?? 0);
        $features = $_POST['features'] ?? [];
        $isActive = isset($_POST['is_active']);
        
        if (empty($name)) $errors[] = "Plan name is required";
        if ($priceMonthly < 0) $errors[] = "Monthly price must be positive";
        if ($priceYearly < 0) $errors[] = "Yearly price must be positive";
        
        if (empty($errors)) {
            try {
                $pdo = getPDO();
                $stmt = $pdo->prepare("INSERT INTO subscription_plans (name, description, price_monthly, price_yearly, features, is_active, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");
                $stmt->execute([$name, $description, $priceMonthly, $priceYearly, json_encode($features), $isActive]);
                $success = "Plan added successfully!";
            } catch (Exception $e) {
                $errors[] = "Failed to add plan: " . $e->getMessage();
            }
        }
    } elseif ($action === 'update_plan') {
        $planId = (int) ($_POST['plan_id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $priceMonthly = (float) ($_POST['price_monthly'] ?? 0);
        $priceYearly = (float) ($_POST['price_yearly'] ?? 0);
        $features = $_POST['features'] ?? [];
        $isActive = isset($_POST['is_active']);
        
        if (empty($name)) $errors[] = "Plan name is required";
        if ($priceMonthly < 0) $errors[] = "Monthly price must be positive";
        if ($priceYearly < 0) $errors[] = "Yearly price must be positive";
        
        if (empty($errors)) {
            try {
                $pdo = getPDO();
                $stmt = $pdo->prepare("UPDATE subscription_plans SET name = ?, description = ?, price_monthly = ?, price_yearly = ?, features = ?, is_active = ? WHERE id = ?");
                $stmt->execute([$name, $description, $priceMonthly, $priceYearly, json_encode($features), $isActive, $planId]);
                $success = "Plan updated successfully!";
            } catch (Exception $e) {
                $errors[] = "Failed to update plan: " . $e->getMessage();
            }
        }
    } elseif ($action === 'delete_plan') {
        $planId = (int) ($_POST['plan_id'] ?? 0);
        try {
            $pdo = getPDO();
            $stmt = $pdo->prepare("DELETE FROM subscription_plans WHERE id = ?");
            $stmt->execute([$planId]);
            $success = "Plan deleted successfully!";
        } catch (Exception $e) {
            $errors[] = "Failed to delete plan: " . $e->getMessage();
        }
    }
}

// Get all plans
$plans = [];
try {
    $pdo = getPDO();
    $stmt = $pdo->query("SELECT * FROM subscription_plans ORDER BY price_monthly ASC");
    $plans = $stmt->fetchAll();
} catch (PDOException $e) {
    // Default plans if table doesn't exist
    $plans = [
        [
            'id' => 1,
            'name' => 'Starter',
            'description' => 'Perfect for individuals and small teams',
            'price_monthly' => 29,
            'price_yearly' => 290,
            'features' => json_encode(['Up to 5 clients', 'Up to 10 proposals/month', 'Basic support']),
            'is_active' => 1
        ],
        [
            'id' => 2,
            'name' => 'Professional',
            'description' => 'Ideal for growing businesses',
            'price_monthly' => 79,
            'price_yearly' => 790,
            'features' => json_encode(['Up to 50 clients', 'Unlimited proposals', 'Priority support', 'Custom branding']),
            'is_active' => 1
        ],
        [
            'id' => 3,
            'name' => 'Enterprise',
            'description' => 'For large organizations',
            'price_monthly' => 199,
            'price_yearly' => 1990,
            'features' => json_encode(['Unlimited clients', 'Unlimited everything', '24/7 support', 'API access', 'Custom integrations']),
            'is_active' => 1
        ]
    ];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Plans - Admin - 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 Admin</div>
                    <div class="flex items-center space-x-4">
                        <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="space-y-4 mb-8">
                    <h1 class="text-3xl font-bold tracking-tight text-foreground">Manage Subscription Plans</h1>
                    <p class="text-muted-foreground">
                        Create, edit, and manage subscription plans for your users.
                    </p>
                </div>

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

                <?php if ($success): ?>
                    <div class="rounded-lg bg-primary/15 p-4 mb-6 text-sm text-primary">
                        <p><?= htmlspecialchars($success) ?></p>
                    </div>
                <?php endif; ?>

                <!-- Add New Plan -->
                <div class="card border border-border bg-card text-card-foreground shadow-sm mb-8">
                    <div class="p-6">
                        <h2 class="text-xl font-semibold text-foreground mb-4">Add New Plan</h2>
                        <form method="POST" class="space-y-4">
                            <input type="hidden" name="action" value="add_plan">
                            
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div class="space-y-2">
                                    <label for="name" class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Plan Name</label>
                                    <input type="text" id="name" name="name" required
                                           class="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
                                           placeholder="Starter">
                                </div>
                                
                                <div class="space-y-2">
                                    <label for="price_monthly" class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Monthly Price ($)</label>
                                    <input type="number" id="price_monthly" name="price_monthly" step="0.01" required
                                           class="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
                                           placeholder="29">
                                </div>
                                
                                <div class="space-y-2">
                                    <label for="price_yearly" class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Yearly Price ($)</label>
                                    <input type="number" id="price_yearly" name="price_yearly" step="0.01" required
                                           class="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
                                           placeholder="290">
                                </div>
                                
                                <div class="space-y-2">
                                    <label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 flex items-center space-x-2">
                                        <input type="checkbox" name="is_active" checked class="peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground">
                                        <span>Active</span>
                                    </label>
                                </div>
                            </div>
                            
                            <div class="space-y-2">
                                <label for="description" class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Description</label>
                                <textarea id="description" name="description" rows="2"
                                          class="flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
                                          placeholder="Perfect for individuals and small teams"></textarea>
                            </div>
                            
                            <div class="space-y-2">
                                <label for="features" class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Features (one per line)</label>
                                <textarea id="features" name="features" rows="4"
                                          class="flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
                                          placeholder="Up to 5 clients&#10;Up to 10 proposals/month&#10;Basic support"></textarea>
                            </div>
                            
                            <button type="submit" class="inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm 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-9 px-4 py-2">
                                Add Plan
                            </button>
                        </form>
                    </div>
                </div>

                <!-- Existing Plans -->
                <div class="card border border-border bg-card text-card-foreground shadow-sm">
                    <div class="p-6">
                        <h2 class="text-xl font-semibold text-foreground mb-4">Existing Plans</h2>
                        
                        <?php if (empty($plans)): ?>
                            <p class="text-muted-foreground">No plans found.</p>
                        <?php else: ?>
                            <div class="space-y-4">
                                <?php foreach ($plans as $plan): ?>
                                    <div class="border border-border rounded-lg p-4">
                                        <form method="POST" class="space-y-4">
                                            <input type="hidden" name="action" value="update_plan">
                                            <input type="hidden" name="plan_id" value="<?= $plan['id'] ?>">
                                            
                                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                                <div class="space-y-2">
                                                    <label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Plan Name</label>
                                                    <input type="text" name="name" required
                                                           class="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
                                                           value="<?= htmlspecialchars($plan['name']) ?>">
                                                </div>
                                                
                                                <div class="space-y-2">
                                                    <label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Monthly Price ($)</label>
                                                    <input type="number" name="price_monthly" step="0.01" required
                                                           class="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
                                                           value="<?= $plan['price_monthly'] ?>">
                                                </div>
                                                
                                                <div class="space-y-2">
                                                    <label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Yearly Price ($)</label>
                                                    <input type="number" name="price_yearly" step="0.01" required
                                                           class="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
                                                           value="<?= $plan['price_yearly'] ?>">
                                                </div>
                                                
                                                <div class="space-y-2">
                                                    <label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 flex items-center space-x-2">
                                                        <input type="checkbox" name="is_active" <?= $plan['is_active'] ? 'checked' : '' ?> class="peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground">
                                                        <span>Active</span>
                                                    </label>
                                                </div>
                                            </div>
                                            
                                            <div class="space-y-2">
                                                <label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Description</label>
                                                <textarea name="description" rows="2"
                                                          class="flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"><?= htmlspecialchars($plan['description'] ?? '') ?></textarea>
                                            </div>
                                            
                                            <div class="space-y-2">
                                                <label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Features (one per line)</label>
                                                <textarea name="features" rows="4"
                                                          class="flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"><?= htmlspecialchars(implode("\n", json_decode($plan['features'] ?? '[]', true) ?? [])) ?></textarea>
                                            </div>
                                            
                                            <div class="flex space-x-2">
                                                <button type="submit" class="inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm 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-9 px-4 py-2">
                                                    Update Plan
                                                </button>
                                                
                                                <button type="submit" onclick="return confirm('Are you sure you want to delete this plan?')" formaction="/admin/manage-plans.php" class="inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 bg-destructive text-destructive-foreground shadow hover:bg-destructive/90 h-9 px-4 py-2">
                                                    Delete
                                                </button>
                                            </div>
                                        </form>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </main>

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