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

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

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'create') {
        $id = generateUUID();
        $code = strtoupper(trim($_POST['code']));
        $name = trim($_POST['name']);
        $email = trim($_POST['email']);
        $status = $_POST['status'];
        $planId = intval($_POST['plan_id'] ?? 0);
        
        try {
            $pdo->beginTransaction();

            $stmt = $pdo->prepare("INSERT INTO tenants (id, code, name, contact_email, status) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$id, $code, $name, $email, $status]);
            
            $instanceId = generateUUID();
            $licenseKey = generateLicenseKey($code);
            $stmt = $pdo->prepare("INSERT INTO instances (id, tenant_id, license_key) VALUES (?, ?, ?)");
            $stmt->execute([$instanceId, $id, $licenseKey]);
            
            // Get Plan Details
            $stmt = $pdo->prepare("SELECT * FROM plans WHERE id = ?");
            $stmt->execute([$planId]);
            $plan = $stmt->fetch();

            if (!$plan) {
                // Fallback to defaults if no plan selected (should not happen)
                $plan = ['code' => 'starter', 'max_users' => 5, 'max_employees' => 20];
            }

            $subId = generateUUID();
            $stmt = $pdo->prepare("INSERT INTO subscriptions (id, tenant_id, plan_type, max_users, max_employees, starts_at, expires_at) VALUES (?, ?, ?, ?, ?, CURDATE(), DATE_ADD(CURDATE(), INTERVAL 1 YEAR))");
            $stmt->execute([$subId, $id, $plan['code'], $plan['max_users'], $plan['max_employees']]);
            
            // Add modules from the selected plan
            if ($planId > 0) {
                // Get modules for this plan
                $stmt = $pdo->prepare("SELECT module_code FROM plan_modules WHERE plan_id = ?");
                $stmt->execute([$planId]);
                $planModules = $stmt->fetchAll();

                $stmt = $pdo->prepare("INSERT INTO subscription_modules (subscription_id, module_code) VALUES (?, ?)");
                foreach ($planModules as $mod) {
                    $stmt->execute([$subId, $mod['module_code']]);
                }
            } else {
                // Fallback: Core modules
                $stmt = $pdo->query("SELECT code FROM modules WHERE is_core = 1");
                $coreModules = $stmt->fetchAll();
                foreach ($coreModules as $mod) {
                    $pdo->prepare("INSERT INTO subscription_modules (subscription_id, module_code) VALUES (?, ?)")->execute([$subId, $mod['code']]);
                }
            }
            
            $pdo->commit();
            $message = "Client créé avec succès. Clé de licence: $licenseKey";
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = "Erreur: " . $e->getMessage();
        }
    }
    
    if ($action === 'delete') {
        $id = $_POST['id'];
        $stmt = $pdo->prepare("DELETE FROM tenants WHERE id = ?");
        $stmt->execute([$id]);
        $message = "Client supprimé";
    }
    
    if ($action === 'update_status') {
        $id = $_POST['id'];
        $status = $_POST['status'];
        $stmt = $pdo->prepare("UPDATE tenants SET status = ? WHERE id = ?");
        $stmt->execute([$status, $id]);
        $message = "Statut mis à jour";
    }
}

// Get all tenants
$stmt = $pdo->query("
    SELECT t.*, 
        (SELECT license_key FROM instances WHERE tenant_id = t.id LIMIT 1) as license_key,
        (SELECT last_heartbeat FROM instances WHERE tenant_id = t.id LIMIT 1) as last_heartbeat,
        (SELECT plan_type FROM subscriptions WHERE tenant_id = t.id AND status = 'active' LIMIT 1) as current_plan
    FROM tenants t 
    ORDER BY t.created_at DESC
");
$tenants = $stmt->fetchAll();

// Get available plans for modal
$stmt = $pdo->query("SELECT * FROM plans ORDER BY price_monthly");
$availablePlans = $stmt->fetchAll();

$currentPage = 'tenants';
$pageTitle = 'Clients - 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">
            
            <!-- Header -->
            <div class="flex justify-between items-center mb-6">
                <div>
                    <h1 class="text-2xl font-bold text-slate-800">Clients</h1>
                    <p class="text-slate-500 text-sm">Gestion des entreprises clientes</p>
                </div>
                <button onclick="document.getElementById('createModal').classList.remove('hidden')" 
                    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 Client
                </button>
            </div>

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

            <!-- Tenants Table -->
            <div class="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden">
                <table class="w-full">
                    <thead class="bg-slate-50 border-b border-slate-200">
                        <tr>
                            <th class="px-5 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Client</th>
                            <th class="px-5 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Plan</th>
                            <th class="px-5 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Token de Connexion</th>
                            <th class="px-5 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Statut</th>
                            <th class="px-5 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Dernier Ping</th>
                            <th class="px-5 py-3 text-right text-xs font-semibold text-slate-500 uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100">
                        <?php foreach ($tenants as $tenant): ?>
                            <tr class="hover:bg-slate-50 transition-colors">
                                <td class="px-5 py-4">
                                    <div>
                                        <p class="text-slate-800 font-semibold text-sm"><?= htmlspecialchars($tenant['name']) ?></p>
                                        <p class="text-slate-400 text-xs"><?= htmlspecialchars($tenant['code']) ?> • <?= htmlspecialchars($tenant['contact_email']) ?></p>
                                    </div>
                                </td>
                                <td class="px-5 py-4">
                                    <span class="bg-indigo-50 text-indigo-700 px-2 py-1 rounded text-xs font-medium uppercase">
                                        <?= htmlspecialchars($tenant['current_plan'] ?? 'N/A') ?>
                                    </span>
                                </td>
                                <td class="px-5 py-4">
                                    <?php 
                                    $licenseKey = $tenant['license_key'] ?? '';
                                    $token = $licenseKey ? generateConnectionToken($licenseKey) : '';
                                    ?>
                                    <div class="flex items-center gap-2">
                                        <code class="text-xs bg-slate-100 px-2 py-1 rounded text-slate-600 max-w-[120px] truncate font-mono"><?= htmlspecialchars(substr($token, 0, 16)) ?>...</code>
                                        <?php if ($token): ?>
                                        <button type="button" onclick="copyToken('<?= htmlspecialchars($token) ?>', this)" 
                                            class="bg-indigo-600 text-white text-xs px-2.5 py-1.5 rounded-lg hover:bg-indigo-700 transition-all flex items-center gap-1 font-medium">
                                            <i class="fa-solid fa-copy"></i> Copier
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td class="px-5 py-4">
                                    <?php
                                    $statusStyles = [
                                        'active' => 'bg-emerald-100 text-emerald-700',
                                        'trial' => 'bg-amber-100 text-amber-700',
                                        'suspended' => 'bg-red-100 text-red-700',
                                        'churned' => 'bg-slate-100 text-slate-500'
                                    ];
                                    $style = $statusStyles[$tenant['status']] ?? 'bg-slate-100 text-slate-500';
                                    ?>
                                    <span class="px-2.5 py-1 rounded-full text-xs font-semibold <?= $style ?>">
                                        <?= ucfirst($tenant['status']) ?>
                                    </span>
                                </td>
                                <td class="px-5 py-4 text-slate-500 text-sm">
                                    <?= $tenant['last_heartbeat'] ? date('d/m H:i', strtotime($tenant['last_heartbeat'])) : 'Jamais' ?>
                                </td>
                                <td class="px-5 py-4 text-right">
                                    <div class="flex items-center justify-end gap-2">
                                        <?php if ($tenant['status'] === 'suspended'): ?>
                                            <form method="POST" class="inline">
                                                <input type="hidden" name="action" value="update_status">
                                                <input type="hidden" name="id" value="<?= $tenant['id'] ?>">
                                                <input type="hidden" name="status" value="active">
                                                <button type="submit" 
                                                    class="text-emerald-600 hover:text-emerald-700 p-1.5 hover:bg-emerald-50 rounded-lg transition-all"
                                                    title="Réactiver la licence">
                                                    <i class="fa-solid fa-play"></i>
                                                </button>
                                            </form>
                                        <?php else: ?>
                                            <form method="POST" class="inline" onsubmit="return confirm('Suspendre la licence de ce client ?')">
                                                <input type="hidden" name="action" value="update_status">
                                                <input type="hidden" name="id" value="<?= $tenant['id'] ?>">
                                                <input type="hidden" name="status" value="suspended">
                                                <button type="submit" 
                                                    class="text-amber-500 hover:text-amber-600 p-1.5 hover:bg-amber-50 rounded-lg transition-all"
                                                    title="Suspendre la licence">
                                                    <i class="fa-solid fa-pause"></i>
                                                </button>
                                            </form>
                                        <?php endif; ?>
                                        <form method="POST" class="inline" onsubmit="return confirm('Supprimer ce client ?')">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="id" value="<?= $tenant['id'] ?>">
                                            <button type="submit" class="text-red-500 hover:text-red-600 p-1.5 hover:bg-red-50 rounded-lg transition-all" title="Supprimer">
                                                <i class="fa-solid fa-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($tenants)): ?>
                            <tr>
                                <td colspan="6" class="px-5 py-10 text-center text-slate-400 italic">
                                    Aucun client enregistré
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

        </div>
    </main>

    <!-- Create Modal -->
    <div id="createModal" class="hidden fixed inset-0 bg-black/40 flex items-center justify-center z-50">
        <div class="bg-white rounded-xl p-6 w-full max-w-md shadow-xl">
            <h2 class="text-lg font-bold text-slate-800 mb-5">Nouveau Client</h2>
            <form method="POST" class="space-y-4">
                <input type="hidden" name="action" value="create">
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-1.5">Code (unique)</label>
                    <input type="text" name="code" required class="w-full bg-slate-50 border border-slate-200 rounded-lg px-3 py-2.5 text-slate-800 focus:outline-none focus:border-indigo-500 transition-all text-sm" placeholder="ACME">
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-1.5">Nom de l'entreprise</label>
                    <input type="text" name="name" required class="w-full bg-slate-50 border border-slate-200 rounded-lg px-3 py-2.5 text-slate-800 focus:outline-none focus:border-indigo-500 transition-all text-sm" placeholder="ACME Corporation">
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-1.5">Email contact</label>
                    <input type="email" name="email" required class="w-full bg-slate-50 border border-slate-200 rounded-lg px-3 py-2.5 text-slate-800 focus:outline-none focus:border-indigo-500 transition-all text-sm" placeholder="contact@acme.com">
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-1.5">Plan d'abonnement</label>
                    <select name="plan_id" class="w-full bg-slate-50 border border-slate-200 rounded-lg px-3 py-2.5 text-slate-800 focus:outline-none focus:border-indigo-500 transition-all text-sm">
                        <?php foreach ($availablePlans as $p): ?>
                            <option value="<?= $p['id'] ?>">
                                <?= htmlspecialchars($p['name']) ?> - <?= number_format($p['price_monthly'], 0) ?> DA/mois
                            </option>
                        <?php endforeach; ?>
                        <?php if (empty($availablePlans)): ?>
                            <option value="0">Par défaut (Starter)</option>
                        <?php endif; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-1.5">Statut</label>
                    <select name="status" class="w-full bg-slate-50 border border-slate-200 rounded-lg px-3 py-2.5 text-slate-800 focus:outline-none focus:border-indigo-500 transition-all text-sm">
                        <option value="trial">Trial</option>
                        <option value="active">Actif</option>
                    </select>
                </div>
                <div class="flex gap-3 pt-3">
                    <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 transition-all">Annuler</button>
                    <button type="submit" class="flex-1 py-2.5 bg-indigo-600 text-white font-semibold rounded-lg hover:bg-indigo-700 text-sm transition-all">Créer</button>
                </div>
            </form>
        </div>
    </div>

    <script>
    function copyToken(token, btn) {
        navigator.clipboard.writeText(token).then(() => {
            const originalHTML = btn.innerHTML;
            btn.innerHTML = '<i class="fa-solid fa-check"></i> Copié!';
            btn.classList.remove('bg-indigo-600', 'hover:bg-indigo-700');
            btn.classList.add('bg-emerald-600');
            setTimeout(() => {
                btn.innerHTML = originalHTML;
                btn.classList.remove('bg-emerald-600');
                btn.classList.add('bg-indigo-600', 'hover:bg-indigo-700');
            }, 2000);
        }).catch(err => {
            alert('Erreur de copie: ' + err);
        });
    }
    </script>

</body>
</html>
