<?php
/**
 * Admin - Subscriptions Management - Clean Modern Design
 */
require_once '../config.php';
$admin = isAdminLogged();

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add_module') {
        $subId = $_POST['subscription_id'];
        $moduleCode = $_POST['module_code'];
        $stmt = $pdo->prepare("INSERT IGNORE INTO subscription_modules (subscription_id, module_code) VALUES (?, ?)");
        $stmt->execute([$subId, $moduleCode]);
        $message = "Module ajouté à l'abonnement";
    }
    
    if ($action === 'remove_module') {
        $subId = $_POST['subscription_id'];
        $moduleCode = $_POST['module_code'];
        $stmt = $pdo->prepare("DELETE FROM subscription_modules WHERE subscription_id = ? AND module_code = ?");
        $stmt->execute([$subId, $moduleCode]);
        $message = "Module retiré de l'abonnement";
    }
    
    if ($action === 'update_plan') {
        $subId = $_POST['subscription_id'];
        $plan = $_POST['plan_type'];
        $maxUsers = intval($_POST['max_users']);
        $maxEmployees = intval($_POST['max_employees']);
        $expiresAt = $_POST['expires_at'];
        
        $stmt = $pdo->prepare("UPDATE subscriptions SET plan_type = ?, max_users = ?, max_employees = ?, expires_at = ? WHERE id = ?");
        $stmt->execute([$plan, $maxUsers, $maxEmployees, $expiresAt ?: null, $subId]);
        $message = "Abonnement mis à jour";
    }
    
    // Grant trial module
    if ($action === 'grant_trial') {
        $subId = $_POST['subscription_id'];
        $moduleCode = $_POST['module_code'];
        $duration = intval($_POST['duration']);
        $startsAt = date('Y-m-d');
        $expiresAt = date('Y-m-d', strtotime("+{$duration} days"));
        
        try {
            $stmt = $pdo->prepare("
                INSERT INTO module_trials (subscription_id, module_code, starts_at, expires_at, granted_by)
                VALUES (?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE starts_at = VALUES(starts_at), expires_at = VALUES(expires_at)
            ");
            $stmt->execute([$subId, $moduleCode, $startsAt, $expiresAt, $admin['id']]);
            $message = "Module en essai accordé pour {$duration} jours";
        } catch (Exception $e) {
            $message = "Erreur: " . $e->getMessage();
        }
    }
    
    // Revoke trial
    if ($action === 'revoke_trial') {
        $subId = $_POST['subscription_id'];
        $moduleCode = $_POST['module_code'];
        $stmt = $pdo->prepare("DELETE FROM module_trials WHERE subscription_id = ? AND module_code = ?");
        $stmt->execute([$subId, $moduleCode]);
        $message = "Essai révoqué";
    }
}

$stmt = $pdo->query("
    SELECT s.*, t.name as tenant_name, t.code as tenant_code
    FROM subscriptions s
    JOIN tenants t ON s.tenant_id = t.id
    ORDER BY s.created_at DESC
");
$subscriptions = $stmt->fetchAll();

$stmt = $pdo->query("SELECT code, name FROM modules ORDER BY sort_order");
$allModules = $stmt->fetchAll();

// Fetch available plans from database
$stmt = $pdo->query("SELECT code, name FROM plans ORDER BY price_monthly ASC");
$allPlans = $stmt->fetchAll();

$currentPage = 'subscriptions';
$pageTitle = 'Abonnements - 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-5xl mx-auto">
            
            <div class="mb-6">
                <h1 class="text-2xl font-bold text-slate-800">Abonnements</h1>
                <p class="text-slate-500 text-sm">Gestion des abonnements et modules par client</p>
            </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; ?>

            <!-- Subscriptions List -->
            <div class="space-y-4">
                <?php foreach ($subscriptions as $sub): 
                    $stmt = $pdo->prepare("
                        SELECT m.code, m.name, m.icon 
                        FROM subscription_modules sm 
                        JOIN modules m ON sm.module_code = m.code 
                        WHERE sm.subscription_id = ? AND sm.is_active = 1
                    ");
                    $stmt->execute([$sub['id']]);
                    $subModules = $stmt->fetchAll();
                    $subModuleCodes = array_column($subModules, 'code');
                ?>
                    <div class="bg-white rounded-xl p-5 border border-slate-200 shadow-sm">
                        <div class="flex items-start justify-between mb-4">
                            <div>
                                <h3 class="text-slate-800 font-semibold text-lg"><?= htmlspecialchars($sub['tenant_name']) ?></h3>
                                <p class="text-slate-400 text-sm"><?= htmlspecialchars($sub['tenant_code']) ?></p>
                            </div>
                            <div class="text-right">
                                <?php
                                $planStyles = [
                                    'starter' => 'bg-slate-100 text-slate-600',
                                    'professional' => 'bg-blue-100 text-blue-700',
                                    'enterprise' => 'bg-indigo-100 text-indigo-700',
                                    'custom' => 'bg-pink-100 text-pink-700'
                                ];
                                $pStyle = $planStyles[$sub['plan_type']] ?? 'bg-slate-100 text-slate-600';
                                ?>
                                <span class="px-2.5 py-1 rounded-full text-xs font-semibold <?= $pStyle ?>">
                                    <?= ucfirst($sub['plan_type']) ?>
                                </span>
                                <p class="text-slate-400 text-xs mt-1">
                                    Expire: <?= $sub['expires_at'] ? date('d/m/Y', strtotime($sub['expires_at'])) : 'Jamais' ?>
                                </p>
                            </div>
                        </div>
                        
                        <!-- Current Modules -->
                        <div class="mb-4">
                            <p class="text-xs font-semibold text-slate-500 uppercase mb-2">Modules Actifs</p>
                            <div class="flex flex-wrap gap-2">
                                <?php foreach ($subModules as $mod): ?>
                                    <span class="bg-emerald-50 text-emerald-700 px-2.5 py-1 rounded-full text-xs font-medium flex items-center gap-1.5">
                                        <i class="<?= htmlspecialchars($mod['icon']) ?>"></i>
                                        <?= htmlspecialchars($mod['name']) ?>
                                        <form method="POST" class="inline">
                                            <input type="hidden" name="action" value="remove_module">
                                            <input type="hidden" name="subscription_id" value="<?= $sub['id'] ?>">
                                            <input type="hidden" name="module_code" value="<?= $mod['code'] ?>">
                                            <button type="submit" class="text-red-400 hover:text-red-600 ml-0.5">&times;</button>
                                        </form>
                                    </span>
                                <?php endforeach; ?>
                                <?php if (empty($subModules)): ?>
                                    <span class="text-slate-400 italic text-xs">Aucun module</span>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Add Module -->
                        <form method="POST" class="flex items-center gap-2 mb-4">
                            <input type="hidden" name="action" value="add_module">
                            <input type="hidden" name="subscription_id" value="<?= $sub['id'] ?>">
                            <select name="module_code" class="flex-1 bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 text-slate-700 text-sm focus:outline-none focus:border-indigo-500">
                                <option value="">Ajouter un module...</option>
                                <?php foreach ($allModules as $m): ?>
                                    <?php if (!in_array($m['code'], $subModuleCodes)): ?>
                                        <option value="<?= $m['code'] ?>"><?= htmlspecialchars($m['name']) ?></option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </select>
                            <button type="submit" class="bg-indigo-600 hover:bg-indigo-700 text-white px-3 py-2 rounded-lg text-sm font-medium transition-all">
                                <i class="fa-solid fa-plus mr-1"></i> Ajouter
                            </button>
                        </form>
                        
                        <!-- Trial Modules Section -->
                        <?php
                        // Get trial modules for this subscription (with graceful fallback if table doesn't exist)
                        $trialModules = [];
                        $trialCodes = [];
                        try {
                            $stmt = $pdo->prepare("
                                SELECT mt.*, m.name as module_name, m.icon
                                FROM module_trials mt
                                JOIN modules m ON mt.module_code = m.code
                                WHERE mt.subscription_id = ?
                                ORDER BY mt.expires_at ASC
                            ");
                            $stmt->execute([$sub['id']]);
                            $trialModules = $stmt->fetchAll();
                            $trialCodes = array_column($trialModules, 'module_code');
                        } catch (PDOException $e) {
                            // Table doesn't exist yet - show migration notice
                            $trialModules = null; // Use null to indicate table missing
                        }
                        
                        // Modules available for trial (not in subscription, not already in trial)
                        $availableForTrial = array_filter($allModules, function($m) use ($subModuleCodes, $trialCodes) {
                            return !in_array($m['code'], $subModuleCodes) && !in_array($m['code'], $trialCodes);
                        });
                        ?>
                        
                        <div class="border-t border-slate-100 pt-4 mb-4">
                            <p class="text-xs font-semibold text-slate-500 uppercase mb-3">
                                <i class="fa-solid fa-flask mr-1 text-amber-500"></i> Modules en Essai
                            </p>
                            
                            <?php if ($trialModules === null): ?>
                            <!-- Migration needed notice -->
                            <div class="bg-amber-50 border border-amber-200 rounded-lg p-3 text-sm">
                                <p class="text-amber-700">
                                    <i class="fa-solid fa-triangle-exclamation mr-1"></i>
                                    Fonctionnalité non initialisée. 
                                    <a href="../migrate_trials.php" class="text-amber-800 underline font-medium">Exécuter la migration</a>
                                </p>
                            </div>
                            <?php else: ?>
                            
                            <!-- Existing Trials -->
                            <?php if (!empty($trialModules)): ?>
                            <div class="flex flex-wrap gap-2 mb-3">
                                <?php foreach ($trialModules as $trial): 
                                    $isExpired = strtotime($trial['expires_at']) < time();
                                    $daysLeft = max(0, ceil((strtotime($trial['expires_at']) - time()) / 86400));
                                ?>
                                    <span class="<?= $isExpired ? 'bg-red-50 text-red-600 border-red-200' : 'bg-amber-50 text-amber-700 border-amber-200' ?> px-2.5 py-1.5 rounded-lg text-xs font-medium flex items-center gap-2 border">
                                        <i class="<?= htmlspecialchars($trial['icon']) ?>"></i>
                                        <?= htmlspecialchars($trial['module_name']) ?>
                                        <span class="<?= $isExpired ? 'bg-red-200 text-red-700' : 'bg-amber-200 text-amber-800' ?> px-1.5 py-0.5 rounded text-[10px]">
                                            <?= $isExpired ? 'Expiré' : $daysLeft . 'j' ?>
                                        </span>
                                        <form method="POST" class="inline">
                                            <input type="hidden" name="action" value="revoke_trial">
                                            <input type="hidden" name="subscription_id" value="<?= $sub['id'] ?>">
                                            <input type="hidden" name="module_code" value="<?= $trial['module_code'] ?>">
                                            <button type="submit" class="text-red-400 hover:text-red-600" title="Révoquer">&times;</button>
                                        </form>
                                    </span>
                                <?php endforeach; ?>
                            </div>
                            <?php endif; ?>
                            
                            <!-- Grant Trial Form -->
                            <?php if (!empty($availableForTrial)): ?>
                            <form method="POST" class="flex items-center gap-2">
                                <input type="hidden" name="action" value="grant_trial">
                                <input type="hidden" name="subscription_id" value="<?= $sub['id'] ?>">
                                <select name="module_code" class="flex-1 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2 text-slate-700 text-sm focus:outline-none focus:border-amber-500" required>
                                    <option value="">Choisir un module...</option>
                                    <?php foreach ($availableForTrial as $m): ?>
                                        <option value="<?= $m['code'] ?>"><?= htmlspecialchars($m['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <select name="duration" class="w-28 bg-amber-50 border border-amber-200 rounded-lg px-2 py-2 text-slate-700 text-sm focus:outline-none focus:border-amber-500">
                                    <option value="7">7 jours</option>
                                    <option value="14" selected>14 jours</option>
                                    <option value="30">30 jours</option>
                                </select>
                                <button type="submit" class="bg-amber-500 hover:bg-amber-600 text-white px-3 py-2 rounded-lg text-sm font-medium transition-all">
                                    <i class="fa-solid fa-flask mr-1"></i> Essai
                                </button>
                            </form>
                            <?php else: ?>
                            <p class="text-slate-400 text-xs italic">Tous les modules sont déjà actifs ou en essai</p>
                            <?php endif; ?>
                            <?php endif; ?>
                        </div>

                        <!-- Subscription Settings -->
                        <div class="border-t border-slate-100 pt-4">
                            <p class="text-xs font-semibold text-slate-500 uppercase mb-3">
                                <i class="fa-solid fa-cog mr-1"></i> Paramètres
                            </p>
                            <form method="POST" class="grid grid-cols-2 md:grid-cols-5 gap-3 items-end">
                                <input type="hidden" name="action" value="update_plan">
                                <input type="hidden" name="subscription_id" value="<?= $sub['id'] ?>">
                                
                                <div>
                                    <label class="block text-xs text-slate-500 mb-1">Plan</label>
                                    <select name="plan_type" class="w-full bg-slate-50 border border-slate-200 rounded-lg px-2.5 py-2 text-slate-700 text-sm focus:outline-none focus:border-indigo-500">
                                        <?php foreach ($allPlans as $plan): ?>
                                            <option value="<?= $plan['code'] ?>" <?= $sub['plan_type'] === $plan['code'] ? 'selected' : '' ?>><?= htmlspecialchars($plan['name']) ?></option>
                                        <?php endforeach; ?>
                                        <?php if (empty($allPlans)): ?>
                                            <option value="starter">Starter (par défaut)</option>
                                        <?php endif; ?>
                                    </select>
                                </div>
                                
                                <div>
                                    <label class="block text-xs text-slate-500 mb-1">Max Users</label>
                                    <input type="number" name="max_users" value="<?= $sub['max_users'] ?>" min="1" 
                                           class="w-full bg-slate-50 border border-slate-200 rounded-lg px-2.5 py-2 text-slate-700 text-sm focus:outline-none focus:border-indigo-500">
                                </div>
                                
                                <div>
                                    <label class="block text-xs text-slate-500 mb-1">Max Employés</label>
                                    <input type="number" name="max_employees" value="<?= $sub['max_employees'] ?? 50 ?>" min="1" 
                                           class="w-full bg-slate-50 border border-slate-200 rounded-lg px-2.5 py-2 text-slate-700 text-sm focus:outline-none focus:border-indigo-500">
                                </div>
                                
                                <div>
                                    <label class="block text-xs text-slate-500 mb-1">Expiration</label>
                                    <input type="date" name="expires_at" 
                                           value="<?= $sub['expires_at'] ? date('Y-m-d', strtotime($sub['expires_at'])) : '' ?>"
                                           class="w-full bg-slate-50 border border-slate-200 rounded-lg px-2.5 py-2 text-slate-700 text-sm focus:outline-none focus:border-indigo-500">
                                </div>
                                
                                <div>
                                    <button type="submit" class="w-full bg-emerald-600 hover:bg-emerald-700 text-white px-3 py-2 rounded-lg text-sm font-medium transition-all">
                                        <i class="fa-solid fa-save mr-1"></i> Sauver
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                <?php endforeach; ?>

                <?php if (empty($subscriptions)): ?>
                    <div class="bg-white rounded-xl p-10 border border-slate-200 text-center">
                        <p class="text-slate-400 italic">Aucun abonnement. Créez d'abord un client.</p>
                    </div>
                <?php endif; ?>
            </div>

        </div>
    </main>

</body>
</html>
