<?php

declare(strict_types=1);

require_once __DIR__ . '/../../src/db.php';
require_once __DIR__ . '/../../src/SuperAdmin/SuperAdminAuth.php';
require_once __DIR__ . '/../../src/SuperAdmin/PlanManager.php';
require_once __DIR__ . '/navigation.php';

SuperAdminAuth::requirePermission('plans_view');

$admin = SuperAdminAuth::getCurrentAdmin();
$canManage = SuperAdminAuth::hasPermission('plans_manage');

$message = '';
$error = '';

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $canManage) {
    $action = $_POST['action'] ?? '';

    if ($action === 'create') {
        $data = [
            'name' => trim($_POST['name'] ?? ''),
            'description' => trim($_POST['description'] ?? ''),
            'price_monthly' => (float)($_POST['price_usd'] ?? 0),
            'price_yearly' => (float)($_POST['yearly_price_usd'] ?? 0),
            'price_monthly_inr' => (float)($_POST['price_inr'] ?? 0),
            'price_yearly_inr' => (float)($_POST['yearly_price_inr'] ?? 0),
            'trial_days' => (int)($_POST['trial_days'] ?? 0),
            'is_popular' => isset($_POST['is_popular']) ? 1 : 0,
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
            'sort_order' => (int)($_POST['sort_order'] ?? 0),
            'limits' => [
                'users' => (int)($_POST['limit_users'] ?? 3),
                'clients' => (int)($_POST['limit_clients'] ?? 10),
                'templates' => (int)($_POST['limit_templates'] ?? 5),
                'storage_mb' => (int)($_POST['limit_storage'] ?? 100),
                'proposals_per_month' => (int)($_POST['limit_proposals'] ?? 10),
                'contracts_per_month' => (int)($_POST['limit_contracts'] ?? 10),
                'invoices_per_month' => (int)($_POST['limit_invoices'] ?? 10),
            ],
            'features' => array_filter(array_map('trim', explode("\n", $_POST['features'] ?? ''))),
        ];

        if (empty($data['name'])) {
            $error = 'Plan name is required.';
        } else {
            $planId = PlanManager::createPlan($data);
            if ($planId) {
                SuperAdminAuth::logActivity($admin['id'], 'create_plan', 'plan', $planId, ['name' => $data['name']]);
                $message = 'Plan created successfully.';
            } else {
                $error = 'Failed to create plan.';
            }
        }
    } elseif ($action === 'update') {
        $planId = (int)($_POST['plan_id'] ?? 0);
        $data = [
            'name' => trim($_POST['name'] ?? ''),
            'description' => trim($_POST['description'] ?? ''),
            'price_monthly' => (float)($_POST['price_usd'] ?? 0),
            'price_yearly' => (float)($_POST['yearly_price_usd'] ?? 0),
            'price_monthly_inr' => (float)($_POST['price_inr'] ?? 0),
            'price_yearly_inr' => (float)($_POST['yearly_price_inr'] ?? 0),
            'trial_days' => (int)($_POST['trial_days'] ?? 0),
            'is_popular' => isset($_POST['is_popular']) ? 1 : 0,
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
            'sort_order' => (int)($_POST['sort_order'] ?? 0),
            'limits' => json_encode([
                'users' => (int)($_POST['limit_users'] ?? 3),
                'clients' => (int)($_POST['limit_clients'] ?? 10),
                'templates' => (int)($_POST['limit_templates'] ?? 5),
                'storage_mb' => (int)($_POST['limit_storage'] ?? 100),
                'proposals_per_month' => (int)($_POST['limit_proposals'] ?? 10),
                'contracts_per_month' => (int)($_POST['limit_contracts'] ?? 10),
                'invoices_per_month' => (int)($_POST['limit_invoices'] ?? 10),
            ]),
            'features' => json_encode(array_filter(array_map('trim', explode("\n", $_POST['features'] ?? '')))),
        ];

        if (PlanManager::updatePlan($planId, $data)) {
            SuperAdminAuth::logActivity($admin['id'], 'update_plan', 'plan', $planId, ['name' => $data['name']]);
            $message = 'Plan updated successfully.';
        } else {
            $error = 'Failed to update plan.';
        }
    } elseif ($action === 'delete') {
        $planId = (int)($_POST['plan_id'] ?? 0);
        if (PlanManager::deletePlan($planId)) {
            SuperAdminAuth::logActivity($admin['id'], 'delete_plan', 'plan', $planId);
            $message = 'Plan deactivated successfully.';
        } else {
            $error = 'Failed to deactivate plan.';
        }
    }
}

$plans = PlanManager::getAllPlans();
$limitLabels = PlanManager::getLimitLabels();
$editingPlan = null;
if (isset($_GET['edit'])) {
    $editingPlan = PlanManager::getPlan((int)$_GET['edit']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Plans · Keelance Admin</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-slate-100 min-h-screen">
    <div class="min-h-screen flex flex-col">
        <?php renderAdminNavigation(); ?>

        <main class="flex-1">
            <div class="max-w-6xl mx-auto px-4 py-6 space-y-6">
                <div class="flex items-center justify-between gap-3">
                    <div>
                        <h1 class="text-2xl font-bold text-slate-900 tracking-tight">Subscription Plans</h1>
                        <p class="text-slate-500 mt-1 text-sm">Manage pricing, limits and features for each workspace plan.</p>
                    </div>
                    <?php if ($canManage): ?>
                        <button onclick="showCreateModal()" class="inline-flex items-center gap-1.5 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors">
                            <span class="text-base leading-none">＋</span>
                            <span>Create Plan</span>
                        </button>
                    <?php endif; ?>
                </div>

                <?php if ($message): ?>
                    <div class="bg-emerald-50 border border-emerald-200 rounded-lg p-4">
                        <p class="text-sm text-emerald-700"><?= htmlspecialchars($message) ?></p>
                    </div>
                <?php endif; ?>

                <?php if ($error): ?>
                    <div class="bg-red-50 border border-red-200 rounded-lg p-4">
                        <p class="text-sm text-red-700"><?= htmlspecialchars($error) ?></p>
                    </div>
                <?php endif; ?>

                <!-- Plans Grid -->
                <div class="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
                    <?php foreach ($plans as $plan): 
                        $limits = json_decode($plan['limits'] ?? '{}', true) ?: [];
                        $features = json_decode($plan['features'] ?? '[]', true) ?: [];
                    ?>
                        <div class="bg-white border border-slate-200 shadow-sm rounded-xl overflow-hidden <?= !$plan['is_active'] ? 'opacity-60' : '' ?>">
                            <div class="p-6 border-b border-slate-100">
                                <div class="flex items-center justify-between mb-2">
                                    <h3 class="text-lg font-semibold text-slate-900"><?= htmlspecialchars($plan['name']) ?></h3>
                                    <?php if ($plan['is_popular']): ?>
                                        <span class="px-2 py-0.5 bg-blue-100 text-blue-700 text-xs rounded-full border border-blue-200">Popular</span>
                                    <?php endif; ?>
                                </div>
                                <p class="text-slate-500 text-sm"><?= htmlspecialchars($plan['description'] ?? '') ?></p>
                                
                                <div class="mt-4 grid grid-cols-2 gap-4">
                                    <div>
                                        <p class="text-xs text-slate-500">Monthly (USD)</p>
                                        <p class="text-xl font-bold text-slate-900">$<?= number_format((float)($plan['price_monthly'] ?? 0), 2) ?></p>
                                    </div>
                                    <div>
                                        <p class="text-xs text-slate-500">Monthly (INR)</p>
                                        <p class="text-xl font-bold text-slate-900">₹<?= number_format((float)($plan['price_monthly_inr'] ?? 0), 0) ?></p>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="p-6 border-b border-slate-100 bg-slate-50/40">
                                <p class="text-sm font-medium text-slate-800 mb-3">Limits</p>
                                <div class="grid grid-cols-2 gap-2 text-sm">
                                    <?php foreach ($limitLabels as $key => $label): ?>
                                        <div class="flex justify-between">
                                            <span class="text-slate-500"><?= $label ?>:</span>
                                            <span class="text-slate-800"><?= ($limits[$key] ?? 0) == -1 ? '∞' : ($limits[$key] ?? 0) ?></span>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            
                            <?php if ($canManage): ?>
                                <div class="p-4 bg-white flex gap-2 border-t border-slate-100">
                                    <a href="?edit=<?= $plan['id'] ?>" class="flex-1 text-center py-2 text-xs rounded-full border border-blue-200 text-blue-700 bg-white hover:bg-blue-50 transition-colors">
                                        Edit
                                    </a>
                                    <form method="POST" class="flex-1" onsubmit="return confirm('Deactivate this plan?')">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="plan_id" value="<?= $plan['id'] ?>">
                                        <button type="submit" class="w-full py-2 text-xs rounded-full border border-red-300 text-red-700 bg-white hover:bg-red-50 transition-colors">
                                            Deactivate
                                        </button>
                                    </form>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </main>

        <?php renderAdminFooter(); ?>
    </div>

    <!-- Create/Edit Modal -->
    <div id="planModal" class="fixed inset-0 bg-black/40 <?= $editingPlan ? 'flex' : 'hidden' ?> items-center justify-center z-50 overflow-y-auto">
        <div class="bg-white border border-slate-200 shadow-xl rounded-xl p-6 w-full max-w-2xl mx-4 my-8">
            <h3 class="text-lg font-semibold mb-4 text-slate-900"><?= $editingPlan ? 'Edit Plan' : 'Create Plan' ?></h3>
            <form method="POST" class="space-y-4">
                <input type="hidden" name="action" value="<?= $editingPlan ? 'update' : 'create' ?>">
                <?php if ($editingPlan): ?>
                    <input type="hidden" name="plan_id" value="<?= $editingPlan['id'] ?>">
                <?php endif; ?>

                <div class="grid md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm text-slate-600 mb-2">Plan Name *</label>
                        <input type="text" name="name" required value="<?= htmlspecialchars($editingPlan['name'] ?? '') ?>"
                               class="w-full px-4 py-2 bg-white border border-slate-300 rounded-lg text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    <div>
                        <label class="block text-sm text-slate-600 mb-2">Sort Order</label>
                        <input type="number" name="sort_order" value="<?= $editingPlan['sort_order'] ?? 0 ?>"
                               class="w-full px-4 py-2 bg-white border border-slate-300 rounded-lg text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                </div>

                <div>
                    <label class="block text-sm text-slate-600 mb-2">Description</label>
                    <textarea name="description" rows="2" class="w-full px-4 py-2 bg-white border border-slate-300 rounded-lg text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500"><?= htmlspecialchars($editingPlan['description'] ?? '') ?></textarea>
                </div>

                <div class="grid md:grid-cols-4 gap-4">
                    <div>
                        <label class="block text-sm text-slate-600 mb-2">Monthly USD</label>
                        <input type="number" step="0.01" name="price_usd" value="<?= $editingPlan['monthly_price'] ?? 0 ?>"
                               class="w-full px-4 py-2 bg-white border border-slate-300 rounded-lg text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    <div>
                        <label class="block text-sm text-slate-600 mb-2">Monthly INR</label>
                        <input type="number" step="0.01" name="price_inr" value="<?= $editingPlan['limits']['price_inr'] ?? 0 ?>"
                               class="w-full px-4 py-2 bg-white border border-slate-300 rounded-lg text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    <div>
                        <label class="block text-sm text-slate-600 mb-2">Yearly USD</label>
                        <input type="number" step="0.01" name="yearly_price_usd" value="<?= $editingPlan['yearly_price'] ?? 0 ?>"
                               class="w-full px-4 py-2 bg-white border border-slate-300 rounded-lg text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    <div>
                        <label class="block text-sm text-slate-600 mb-2">Yearly INR</label>
                        <input type="number" step="0.01" name="yearly_price_inr" value="<?= $editingPlan['limits']['yearly_price_inr'] ?? 0 ?>"
                               class="w-full px-4 py-2 bg-white border border-slate-300 rounded-lg text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                </div>

                <?php
                $limits = [];
                if ($editingPlan && isset($editingPlan['limits']) && is_array($editingPlan['limits'])) {
                    $limits = $editingPlan['limits'];
                }
                ?>
                <div class="border-t border-slate-200 pt-4 mt-2">
                    <p class="text-sm font-medium text-slate-800 mb-3">Limits (-1 for unlimited)</p>
                    <div class="grid md:grid-cols-4 gap-4">
                        <?php foreach ($limitLabels as $key => $label): ?>
                            <div>
                                <label class="block text-xs text-slate-600 mb-1"><?= $label ?></label>
                                <input type="number" name="limit_<?= str_replace('_per_month', '', str_replace('_mb', '', $key)) ?>"
                                       value="<?= $limits[$key] ?? 0 ?>"
                                       class="w-full px-3 py-2 bg-white border border-slate-300 rounded-lg text-slate-900 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div>
                    <label class="block text-sm text-slate-600 mb-2">Features (one per line)</label>
                    <textarea name="features" rows="4" class="w-full px-4 py-2 bg-white border border-slate-300 rounded-lg text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500"><?= htmlspecialchars(implode("\n", $editingPlan['features'] ?? [])) ?></textarea>
                </div>

                <div class="flex gap-4">
                    <label class="flex items-center gap-2">
                        <input type="checkbox" name="is_popular" <?= ($editingPlan['is_popular'] ?? false) ? 'checked' : '' ?>
                               class="w-4 h-4 rounded bg-white border-slate-300 text-blue-600 focus:ring-blue-500">
                        <span class="text-sm text-slate-700">Popular</span>
                    </label>
                    <label class="flex items-center gap-2">
                        <input type="checkbox" name="is_active" <?= ($editingPlan['is_active'] ?? true) ? 'checked' : '' ?>
                               class="w-4 h-4 rounded bg-white border-slate-300 text-blue-600 focus:ring-blue-500">
                        <span class="text-sm text-slate-700">Active</span>
                    </label>
                    <div class="flex-1">
                        <label class="block text-xs text-slate-600 mb-1">Trial Days</label>
                        <input type="number" name="trial_days" value="<?= $editingPlan['trial_days'] ?? 0 ?>"
                               class="w-24 px-3 py-1 bg-white border border-slate-300 rounded-lg text-slate-900 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                </div>

                <div class="flex gap-3 pt-4">
                    <a href="/admin/plans.php" class="flex-1 text-center px-4 py-2 bg-slate-50 hover:bg-slate-100 border border-slate-200 text-slate-700 rounded-lg transition-colors">
                        Cancel
                    </a>
                    <button type="submit" class="flex-1 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
                        <?= $editingPlan ? 'Update Plan' : 'Create Plan' ?>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function showCreateModal() {
            var modal = document.getElementById('planModal');
            if (!modal) return;
            modal.classList.remove('hidden');
            modal.classList.add('flex');
        }
    </script>
</body>
</html>
