<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../config/config.php';

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: ../login.php");
    exit();
}

$success_msg = '';
$error_msg = '';

// =========================================================
// UPDATE EXISTING PLAN
// =========================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_plan'])) {
    $plan_id = intval($_POST['plan_id']);
    $plan_name = trim($_POST['plan_name']);
    $duration_days = intval($_POST['duration_days']);
    $price = floatval($_POST['price']);
    $features = trim($_POST['features']);
    $status = $_POST['status'] === 'active' ? 'active' : 'inactive';
    $is_popular = isset($_POST['is_popular']) ? 1 : 0;

    if ($is_popular) {
        $pdo->query("UPDATE subscription_plans SET is_popular = 0");
    }

    if (!empty($plan_name) && $price >= 0 && $duration_days > 0) {
        $stmt = $pdo->prepare("UPDATE subscription_plans SET plan_name=?, duration_days=?, price=?, features=?, status=?, is_popular=? WHERE id=?");
        if ($stmt->execute([$plan_name, $duration_days, $price, $features, $status, $is_popular, $plan_id])) {
            $success_msg = "Subscription plan updated successfully.";
        } else {
            $error_msg = "Database error: Failed to update plan.";
        }
    } else {
        $error_msg = "Action blocked: Invalid data provided.";
    }
}

// FETCH ALL PLANS
$stmt = $pdo->query("SELECT * FROM subscription_plans ORDER BY duration_days ASC");
$plans = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Count stats
$total_plans = count($plans);
$active_plans = 0;
$popular_plans = 0;
foreach ($plans as $p) {
    if ($p['status'] === 'active') $active_plans++;
    if ($p['is_popular']) $popular_plans++;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Subscription Plans</title>
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/css/output.css?v=<?php echo time(); ?>">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;900&display=swap" rel="stylesheet">
    <style> 
        body { font-family: 'Inter', sans-serif; } 
        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }
        .dark ::-webkit-scrollbar-thumb { background: #334155; }
        .plan-card {
            transition: all 0.25s ease;
        }
        .plan-card:hover {
            transform: translateY(-4px);
        }
    </style>
    <script>
        if (localStorage.getItem('fpp_theme') === 'dark') {
            document.documentElement.classList.add('dark');
        } else {
            document.documentElement.classList.remove('dark');
        }
    </script>
</head>
<body class="bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-gray-200 antialiased min-h-screen flex flex-col md:flex-row transition-colors duration-300">

    <?php include __DIR__ . '/includes/admin-sidebar.php'; ?>

    <main class="flex-1 p-4 sm:p-6 md:p-8 overflow-x-hidden flex flex-col gap-6">
        
        <!-- ========== HEADER ========== -->
        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div>
                <div class="inline-flex items-center space-x-2 bg-purple-500/10 border border-purple-500/20 px-3 py-1 rounded-full text-[10px] font-bold tracking-widest uppercase text-purple-400 mb-2">
                    <span class="w-1.5 h-1.5 rounded-full bg-purple-400 animate-pulse"></span>
                    <span>Revenue Control</span>
                </div>
                <h2 class="text-2xl sm:text-3xl font-extrabold text-slate-900 dark:text-white tracking-wide">Subscription Plans</h2>
                <p class="text-xs text-slate-500 dark:text-gray-400 mt-0.5">Configure pricing matrix, durations, and features.</p>
            </div>
            <a href="plan-add.php" class="bg-purple-600 hover:bg-purple-700 text-white font-bold px-5 py-2.5 rounded-xl text-xs tracking-wider uppercase transition shadow-lg shadow-purple-600/20 flex items-center gap-2">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                Add New Plan
            </a>
        </div>

        <!-- ========== MESSAGES ========== -->
        <?php if(!empty($success_msg)): ?>
            <div class="bg-emerald-50 border-emerald-200 text-emerald-700 dark:bg-emerald-500/10 dark:border-emerald-500/30 dark:text-emerald-400 border rounded-xl p-3 flex items-center gap-2 shadow-sm text-sm font-medium">
                <span>✅</span> <?php echo $success_msg; ?>
            </div>
        <?php endif; ?>
        <?php if(!empty($error_msg)): ?>
            <div class="bg-rose-50 border-rose-200 text-rose-700 dark:bg-rose-500/10 dark:border-rose-500/30 dark:text-rose-400 border rounded-xl p-3 flex items-center gap-2 shadow-sm text-sm font-medium">
                <span>❌</span> <?php echo $error_msg; ?>
            </div>
        <?php endif; ?>

        <!-- ========== STATS CARDS ========== -->
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Total Plans</span>
                <span class="text-2xl font-extrabold text-slate-900 dark:text-white mt-1 block"><?php echo $total_plans; ?></span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Active</span>
                <span class="text-2xl font-extrabold text-emerald-600 dark:text-emerald-500 mt-1 block"><?php echo $active_plans; ?></span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Popular Highlighted</span>
                <span class="text-2xl font-extrabold text-amber-600 dark:text-amber-500 mt-1 block"><?php echo $popular_plans; ?></span>
            </div>
        </div>

        <!-- ========== PLANS GRID ========== -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 pb-6">
            <?php foreach ($plans as $plan): 
                $is_active = $plan['status'] === 'active';
                $is_popular = $plan['is_popular'];
            ?>
                <div class="plan-card bg-white dark:bg-slate-900 border rounded-2xl p-5 sm:p-6 shadow-sm transition-colors duration-300 <?php echo $is_popular ? 'border-purple-400 dark:border-purple-500 shadow-[0_0_30px_rgba(168,85,247,0.08)]' : 'border-slate-200 dark:border-slate-800'; ?> relative">
                    
                    <?php if ($is_popular): ?>
                        <div class="absolute -top-3 left-1/2 transform -translate-x-1/2 bg-gradient-to-r from-purple-500 to-indigo-500 text-white font-black text-[9px] tracking-widest uppercase px-3 py-1 rounded-full shadow-lg shadow-purple-500/25 z-10">
                            🔥 Most Popular
                        </div>
                    <?php endif; ?>

                    <form action="plan-management.php" method="POST" class="space-y-4">
                        <input type="hidden" name="plan_id" value="<?php echo $plan['id']; ?>">

                        <!-- Plan Name & Price -->
                        <div>
                            <label class="block text-[10px] text-slate-500 dark:text-gray-400 tracking-wider uppercase font-bold mb-1">Plan Name</label>
                            <input type="text" name="plan_name" value="<?php echo htmlspecialchars($plan['plan_name']); ?>" required class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-2.5 text-slate-900 dark:text-white font-bold focus:outline-none focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 text-sm transition-all">
                        </div>

                        <div class="grid grid-cols-2 gap-3">
                            <div>
                                <label class="block text-[10px] text-slate-500 dark:text-gray-400 tracking-wider uppercase font-bold mb-1">Price ($)</label>
                                <input type="number" step="0.01" name="price" value="<?php echo $plan['price']; ?>" required class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-2.5 text-slate-900 dark:text-emerald-400 font-black focus:outline-none focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 text-sm transition-all">
                            </div>
                            <div>
                                <label class="block text-[10px] text-slate-500 dark:text-gray-400 tracking-wider uppercase font-bold mb-1">Days</label>
                                <input type="number" name="duration_days" value="<?php echo $plan['duration_days']; ?>" required class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-2.5 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 text-sm transition-all">
                            </div>
                        </div>

                        <!-- Features -->
                        <div>
                            <div class="flex justify-between items-center mb-1">
                                <label class="block text-[10px] text-slate-500 dark:text-gray-400 tracking-wider uppercase font-bold">Features</label>
                                <span class="text-[8px] font-mono text-slate-400 dark:text-gray-500">One per line</span>
                            </div>
                            <textarea name="features" rows="4" class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-2.5 text-slate-900 dark:text-slate-300 focus:outline-none focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 text-xs leading-relaxed transition-all resize-y"><?php echo htmlspecialchars($plan['features']); ?></textarea>
                        </div>

                        <!-- Status & Popular Toggle -->
                        <div class="flex items-center justify-between bg-slate-50 dark:bg-slate-950 p-3 rounded-xl border border-slate-200 dark:border-slate-800">
                            <label class="flex items-center gap-2 cursor-pointer">
                                <input type="checkbox" name="is_popular" value="1" <?php echo $is_popular ? 'checked' : ''; ?> class="w-4 h-4 text-purple-500 rounded border-slate-300 dark:border-slate-600 focus:ring-purple-500 focus:ring-2">
                                <span class="text-[10px] font-bold text-slate-500 dark:text-gray-400 uppercase tracking-wider">Highlight</span>
                            </label>
                            
                            <select name="status" class="bg-transparent text-[10px] font-bold uppercase tracking-wider text-slate-500 dark:text-gray-400 focus:outline-none cursor-pointer">
                                <option value="active" <?php echo ($is_active) ? 'selected' : ''; ?> class="text-emerald-500">🟢 Active</option>
                                <option value="inactive" <?php echo (!$is_active) ? 'selected' : ''; ?> class="text-rose-500">🔴 Hidden</option>
                            </select>
                        </div>

                        <button type="submit" name="update_plan" class="w-full bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 text-white font-bold py-3 rounded-xl transition shadow-lg shadow-purple-600/20 text-[10px] tracking-widest uppercase mt-2">
                            💾 Save Changes
                        </button>
                    </form>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- ========== EMPTY STATE ========== -->
        <?php if (empty($plans)): ?>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-12 text-center shadow-sm">
                <span class="text-4xl block mb-4">📦</span>
                <h3 class="text-lg font-bold text-slate-900 dark:text-white">No Plans Created</h3>
                <p class="text-sm text-slate-500 dark:text-gray-400 mt-1">Get started by adding your first subscription plan.</p>
                <a href="plan-add.php" class="inline-block mt-4 bg-purple-600 hover:bg-purple-700 text-white font-bold px-6 py-3 rounded-xl text-xs tracking-wider uppercase transition shadow-lg shadow-purple-600/20">Add Plan</a>
            </div>
        <?php endif; ?>

    </main>
</body>
</html>