<?php
/**
 * Admin - Plans Management
 */
require_once '../config.php';
$admin = isAdminLogged();

$message = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'create' || $action === 'update') {
        $code = strtolower(trim($_POST['code']));
        $name = trim($_POST['name']);
        $price = floatval($_POST['price']);
        $maxUsers = intval($_POST['max_users']);
        $modules = $_POST['modules'] ?? [];
        $planId = ($action === 'update') ? intval($_POST['plan_id']) : null;
        
        try {
            $pdo->beginTransaction();
            
            if ($action === 'create') {
                // Insert Plan
                $stmt = $pdo->prepare("INSERT INTO plans (code, name, price_monthly, max_users) VALUES (?, ?, ?, ?)");
                $stmt->execute([$code, $name, $price, $maxUsers]);
                $planId = $pdo->lastInsertId();
                $message = "Plan créé avec succès";
            } else {
                // Update Plan
                $stmt = $pdo->prepare("UPDATE plans SET code = ?, name = ?, price_monthly = ?, max_users = ? WHERE id = ?");
                $stmt->execute([$code, $name, $price, $maxUsers, $planId]);
                
                // Clear existing modules
                $stmt = $pdo->prepare("DELETE FROM plan_modules WHERE plan_id = ?");
                $stmt->execute([$planId]);
                $message = "Plan mis à jour avec succès";
            }
            
            // Get Core Modules to ensure they are included
            $stmt = $pdo->query("SELECT code FROM modules WHERE is_core = 1");
            $coreModules = $stmt->fetchAll(PDO::FETCH_COLUMN);
            
            // Merge form modules with core modules
            $finalModules = array_unique(array_merge($modules, $coreModules));
            
            // Insert Modules
            $stmt = $pdo->prepare("INSERT INTO plan_modules (plan_id, module_code) VALUES (?, ?)");
            foreach ($finalModules as $modCode) {
                $stmt->execute([$planId, $modCode]);
            }
            
            $pdo->commit();
        } catch (Exception $e) {
            $pdo->rollBack();
            $message = "Erreur: " . $e->getMessage();
        }
    }
    
    if ($action === 'delete') {
        $id = $_POST['id'];
        $stmt = $pdo->prepare("DELETE FROM plans WHERE id = ?");
        $stmt->execute([$id]);
        $message = "Plan supprimé";
    }
}

// Get all plans with their modules
$stmt = $pdo->query("
    SELECT p.*, 
           GROUP_CONCAT(pm.module_code) as module_codes,
           (SELECT COUNT(*) FROM subscriptions WHERE plan_type = p.code) as subscriber_count
    FROM plans p
    LEFT JOIN plan_modules pm ON p.id = pm.plan_id
    GROUP BY p.id
    ORDER BY p.price_monthly ASC
");
$plans = $stmt->fetchAll();

// Get all modules for the form
$stmt = $pdo->query("SELECT * FROM modules ORDER BY category, sort_order");
$modulesResult = $stmt->fetchAll();
$modulesByCategory = [];
foreach ($modulesResult as $mod) {
    if (empty($mod['category'])) $mod['category'] = 'other';
    $modulesByCategory[$mod['category']][] = $mod;
}

$currentPage = 'plans';
$pageTitle = 'Plans - License Server';
?>
<?php include 'includes/header.php'; ?>
    
    <!-- Sidebar -->
    <?php include 'includes/sidebar.php'; ?>

    <!-- Main Content -->
    <main class="ml-60 p-8">
        <div class="max-w-6xl mx-auto">
            
            <div class="flex justify-between items-center mb-6">
                <div>
                    <h1 class="text-2xl font-bold text-slate-800">Plans</h1>
                    <p class="text-slate-500 text-sm">Gestion des offres commerciales</p>
                </div>
                <button onclick="openModal()" 
                    class="bg-indigo-600 text-white font-semibold px-4 py-2.5 rounded-lg flex items-center gap-2 hover:bg-indigo-700 active:scale-[0.98] transition-all text-sm">
                    <i class="fa-solid fa-plus"></i>
                    Nouveau Plan
                </button>
            </div>

            <?php if ($message): ?>
                <div class="mb-4 p-3 bg-emerald-50 border border-emerald-200 rounded-lg text-emerald-700 text-sm flex items-center gap-2">
                    <i class="fa-solid fa-check-circle"></i><?= htmlspecialchars($message) ?>
                </div>
            <?php endif; ?>

            <!-- Plans Grid -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <?php foreach ($plans as $plan): 
                    $planModules = $plan['module_codes'] ? explode(',', $plan['module_codes']) : [];
                    $planJson = htmlspecialchars(json_encode([
                        'id' => $plan['id'],
                        'code' => $plan['code'],
                        'name' => $plan['name'],
                        'price' => $plan['price_monthly'],
                        'max_users' => $plan['max_users'],
                        'modules' => $planModules
                    ]), ENT_QUOTES, 'UTF-8');
                ?>
                    <div class="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden flex flex-col">
                        <div class="p-6 flex-1">
                            <div class="flex justify-between items-start mb-4">
                                <div>
                                    <h3 class="text-xl font-bold text-slate-800"><?= htmlspecialchars($plan['name']) ?></h3>
                                    <code class="text-xs bg-slate-100 text-slate-500 px-2 py-0.5 rounded"><?= htmlspecialchars($plan['code']) ?></code>
                                </div>
                                <div class="text-right">
                                    <span class="text-2xl font-bold text-indigo-600"><?= number_format($plan['price_monthly'], 0) ?> <span class="text-sm">DA</span></span>
                                    <span class="text-xs text-slate-400 block">/mois</span>
                                </div>
                            </div>
                            
                            <div class="flex gap-4 mb-6 text-sm text-slate-600">
                                <span class="flex items-center gap-1.5"><i class="fa-solid fa-users text-slate-400"></i> <?= $plan['max_users'] ?> users</span>
                                <span class="flex items-center gap-1.5"><i class="fa-solid fa-building-user text-slate-400"></i> <?= $plan['subscriber_count'] ?> abonnés</span>
                            </div>

                            <div class="space-y-3">
                                <p class="text-xs font-semibold text-slate-500 uppercase">Modules inclus :</p>
                                <div class="flex flex-wrap gap-2">
                                    <?php foreach ($planModules as $mCode): ?>
                                        <span class="bg-indigo-50 text-indigo-700 px-2 py-1 rounded text-xs font-medium">
                                            <?= htmlspecialchars($mCode) ?>
                                        </span>
                                    <?php endforeach; ?>
                                    <?php if (empty($planModules)): ?>
                                        <span class="text-slate-400 text-xs italic">Aucun module</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        <div class="bg-slate-50 p-4 border-t border-slate-100 flex justify-end gap-3">
                            <button onclick="editPlan(<?= $planJson ?>)" class="text-indigo-600 hover:text-indigo-800 text-sm font-medium flex items-center gap-2">
                                <i class="fa-solid fa-pen"></i> Modifier
                            </button>
                            <form method="POST" onsubmit="return confirm('Supprimer ce plan ?')" class="inline">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" value="<?= $plan['id'] ?>">
                                <button type="submit" class="text-red-500 hover:text-red-700 text-sm font-medium flex items-center gap-2">
                                    <i class="fa-solid fa-trash"></i> Supprimer
                                </button>
                            </form>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

        </div>
    </main>

    <!-- Create/Edit Plan Modal -->
    <div id="createModal" class="hidden fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4">
        <div class="bg-white rounded-xl w-full max-w-2xl shadow-xl max-h-[90vh] overflow-y-auto">
            <div class="p-6 border-b border-slate-100">
                <h2 id="modalTitle" class="text-lg font-bold text-slate-800">Nouveau Plan</h2>
            </div>
            <form method="POST" id="planForm" class="p-6 space-y-6">
                <input type="hidden" name="action" id="formAction" value="create">
                <input type="hidden" name="plan_id" id="planId" value="">
                
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1.5">Nom du plan</label>
                        <input type="text" name="name" id="planName" required class="w-full bg-slate-50 border border-slate-200 rounded-lg px-3 py-2.5 text-sm" placeholder="Ex: Professionnel">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1.5">Code (slug)</label>
                        <input type="text" name="code" id="planCode" required class="w-full bg-slate-50 border border-slate-200 rounded-lg px-3 py-2.5 text-sm" placeholder="Ex: professional">
                    </div>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1.5">Prix mensuel (DA)</label>
                        <input type="number" name="price" id="planPrice" required step="0.01" class="w-full bg-slate-50 border border-slate-200 rounded-lg px-3 py-2.5 text-sm" placeholder="0.00">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1.5">Utilisateurs Max</label>
                        <input type="number" name="max_users" id="planUsers" required class="w-full bg-slate-50 border border-slate-200 rounded-lg px-3 py-2.5 text-sm">
                    </div>
                </div>

                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-3">Modules inclus</label>
                    <div class="grid grid-cols-2 md:grid-cols-3 gap-3">
                        <?php foreach ($modulesByCategory as $cat => $catModules): ?>
                            <div class="col-span-full mt-2 mb-1">
                                <span class="text-xs font-bold text-indigo-600 uppercase tracking-wider"><?= htmlspecialchars($cat) ?></span>
                            </div>
                            <?php foreach ($catModules as $mod): 
                                $isCore = $mod['is_core'] == 1;
                            ?>
                                <label class="flex items-start gap-2 p-2.5 border border-slate-200 rounded-lg cursor-pointer hover:bg-slate-50 transition-colors <?= $isCore ? 'bg-slate-50 opacity-75' : '' ?>">
                                    <input type="checkbox" name="modules[]" value="<?= $mod['code'] ?>" 
                                           class="mt-1 rounded text-indigo-600 focus:ring-indigo-500 module-checkbox"
                                           <?= $isCore ? 'checked disabled data-core="1"' : '' ?>>
                                    <div>
                                        <span class="block text-sm font-medium text-slate-700">
                                            <?= htmlspecialchars($mod['name']) ?>
                                            <?php if ($isCore): ?>
                                                <span class="text-xs text-indigo-600 font-bold ml-1">(Inclus)</span>
                                            <?php endif; ?>
                                        </span>
                                        <span class="block text-xs text-slate-400"><?= htmlspecialchars($mod['code']) ?></span>
                                    </div>
                                </label>
                            <?php endforeach; ?>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="flex gap-3 pt-4 border-t border-slate-100">
                    <button type="button" onclick="document.getElementById('createModal').classList.add('hidden')" class="flex-1 py-2.5 border border-slate-200 text-slate-600 rounded-lg hover:bg-slate-50 font-medium text-sm">Annuler</button>
                    <button type="submit" id="submitBtn" class="flex-1 py-2.5 bg-indigo-600 text-white font-semibold rounded-lg hover:bg-indigo-700 text-sm">Créer le Plan</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function openModal() {
            document.getElementById('modalTitle').textContent = 'Nouveau Plan';
            document.getElementById('formAction').value = 'create';
            document.getElementById('planId').value = '';
            document.getElementById('planName').value = '';
            document.getElementById('planCode').value = '';
            document.getElementById('planPrice').value = '';
            document.getElementById('planUsers').value = '5';
            document.getElementById('submitBtn').textContent = 'Créer le Plan';
            
            // Uncheck all except core
            document.querySelectorAll('.module-checkbox').forEach(cb => {
                if (cb.dataset.core == "1") {
                    cb.checked = true;
                } else {
                    cb.checked = false;
                }
            });
            
            document.getElementById('createModal').classList.remove('hidden');
        }

        function editPlan(plan) {
            document.getElementById('modalTitle').textContent = 'Modifier le Plan';
            document.getElementById('formAction').value = 'update';
            document.getElementById('planId').value = plan.id;
            document.getElementById('planName').value = plan.name;
            document.getElementById('planCode').value = plan.code;
            document.getElementById('planPrice').value = plan.price;
            document.getElementById('planUsers').value = plan.max_users;
            document.getElementById('submitBtn').textContent = 'Mettre à jour';
            
            // Check included modules
            document.querySelectorAll('.module-checkbox').forEach(cb => {
                if (cb.dataset.core == "1") {
                    cb.checked = true;
                } else {
                    cb.checked = plan.modules.includes(cb.value);
                }
            });
            
            document.getElementById('createModal').classList.remove('hidden');
        }
    </script>
</body>
</html>
