<?php
/**
 * Admin - Server Resource Simulator (Enhanced)
 * Professional resource estimation based on real-world ERP benchmarks
 * 
 * METHODOLOGY BASED ON:
 * - ERPNext/Frappe benchmarks: ~400MB per site, 0.3 vCPU per concurrent user
 * - HansaWorld: 0.5GB base + 10-50% of DB size
 * - Comarch ERP: 4 cores / 32GB as entry-level
 * - Real production data: 1 vCPU = 6 concurrent users effectively
 */
require_once '../config.php';
$admin = isAdminLogged();

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

// Category display names
$categoryNames = [
    'core' => 'Core',
    'hr' => 'Ressources Humaines',
    'finance' => 'Finance & Comptabilité',
    'operations' => 'Opérations & Logistique',
    'admin' => 'Administration',
    'ai' => 'Intelligence Artificielle',
    'manufacturing' => 'Production & Fabrication',
    'pos' => 'Point de Vente',
    'other' => 'Autres'
];

/**
 * RESOURCE PROFILES - Based on real-world data
 * 
 * Each module category has:
 * - baseCpu: Base CPU cores needed (vCPU)
 * - baseRam: Base RAM in GB
 * - baseStorage: Base storage in GB
 * - perUserCpu: Additional CPU per concurrent user
 * - perUserRam: Additional RAM per concurrent user (MB)
 * - perEmployeeStorage: Storage per employee/year (GB) for data growth
 * - dbIntensive: Whether this module is database-heavy
 * - needsGpu: Whether GPU is recommended
 * - cacheable: How much can be cached (reduces RAM spikes)
 */
$resourceProfiles = [
    'core' => [
        'baseCpu' => 0.5, 'baseRam' => 0.8, 'baseStorage' => 5,
        'perUserCpu' => 0.03, 'perUserRam' => 40, 'perEmployeeStorage' => 0.1,
        'dbIntensive' => false, 'needsGpu' => false, 'cacheable' => 0.8
    ],
    'hr' => [
        'baseCpu' => 0.4, 'baseRam' => 1.0, 'baseStorage' => 8,
        'perUserCpu' => 0.05, 'perUserRam' => 60, 'perEmployeeStorage' => 0.5,
        'dbIntensive' => true, 'needsGpu' => false, 'cacheable' => 0.6
    ],
    'finance' => [
        'baseCpu' => 0.6, 'baseRam' => 1.5, 'baseStorage' => 15,
        'perUserCpu' => 0.08, 'perUserRam' => 80, 'perEmployeeStorage' => 1.0,
        'dbIntensive' => true, 'needsGpu' => false, 'cacheable' => 0.4
    ],
    'operations' => [
        'baseCpu' => 0.5, 'baseRam' => 1.2, 'baseStorage' => 20,
        'perUserCpu' => 0.06, 'perUserRam' => 70, 'perEmployeeStorage' => 2.0,
        'dbIntensive' => true, 'needsGpu' => false, 'cacheable' => 0.5
    ],
    'admin' => [
        'baseCpu' => 0.2, 'baseRam' => 0.4, 'baseStorage' => 2,
        'perUserCpu' => 0.02, 'perUserRam' => 30, 'perEmployeeStorage' => 0.05,
        'dbIntensive' => false, 'needsGpu' => false, 'cacheable' => 0.9
    ],
    'ai' => [
        'baseCpu' => 2.0, 'baseRam' => 8.0, 'baseStorage' => 30,
        'perUserCpu' => 0.2, 'perUserRam' => 200, 'perEmployeeStorage' => 0.5,
        'dbIntensive' => false, 'needsGpu' => true, 'cacheable' => 0.3
    ],
    'manufacturing' => [
        'baseCpu' => 0.8, 'baseRam' => 2.0, 'baseStorage' => 25,
        'perUserCpu' => 0.07, 'perUserRam' => 90, 'perEmployeeStorage' => 3.0,
        'dbIntensive' => true, 'needsGpu' => false, 'cacheable' => 0.4
    ],
    'pos' => [
        'baseCpu' => 0.6, 'baseRam' => 1.0, 'baseStorage' => 10,
        'perUserCpu' => 0.1, 'perUserRam' => 100, 'perEmployeeStorage' => 1.5,
        'dbIntensive' => true, 'needsGpu' => false, 'cacheable' => 0.5
    ],
    'other' => [
        'baseCpu' => 0.3, 'baseRam' => 0.5, 'baseStorage' => 5,
        'perUserCpu' => 0.04, 'perUserRam' => 50, 'perEmployeeStorage' => 0.2,
        'dbIntensive' => false, 'needsGpu' => false, 'cacheable' => 0.7
    ]
];

/**
 * SERVER TIERS - Based on real cloud provider offerings
 * Prices in DZD (approximated from USD at ~135 DZD/USD)
 */
$serverTiers = [
    'micro' => [
        'name' => 'Micro Instance',
        'desc' => 'Développement & Tests',
        'cpu' => 1, 'ram' => 2, 'storage' => 50,
        'maxEmployees' => 10, 'maxConcurrent' => 5,
        'costMin' => 2000, 'costMax' => 5000,
        'providers' => 'DigitalOcean, Vultr, Hetzner',
        'type' => 'Cloud VPS'
    ],
    'starter' => [
        'name' => 'VPS Starter',
        'desc' => 'Startups & TPE (< 25 employés)',
        'cpu' => 2, 'ram' => 4, 'storage' => 80,
        'maxEmployees' => 25, 'maxConcurrent' => 15,
        'costMin' => 5000, 'costMax' => 12000,
        'providers' => 'DigitalOcean, Contabo, Hetzner',
        'type' => 'Cloud VPS'
    ],
    'standard' => [
        'name' => 'VPS Standard',
        'desc' => 'PME en croissance (25-75 employés)',
        'cpu' => 4, 'ram' => 8, 'storage' => 160,
        'maxEmployees' => 75, 'maxConcurrent' => 40,
        'costMin' => 12000, 'costMax' => 25000,
        'providers' => 'DigitalOcean, Linode, OVH',
        'type' => 'Cloud VPS'
    ],
    'performance' => [
        'name' => 'VPS Performance',
        'desc' => 'PME établies (75-150 employés)',
        'cpu' => 8, 'ram' => 16, 'storage' => 320,
        'maxEmployees' => 150, 'maxConcurrent' => 80,
        'costMin' => 25000, 'costMax' => 50000,
        'providers' => 'DigitalOcean, Linode, Vultr',
        'type' => 'Cloud VPS High-Perf'
    ],
    'business' => [
        'name' => 'Serveur Business',
        'desc' => 'Moyennes entreprises (150-300 employés)',
        'cpu' => 16, 'ram' => 32, 'storage' => 500,
        'maxEmployees' => 300, 'maxConcurrent' => 150,
        'costMin' => 50000, 'costMax' => 100000,
        'providers' => 'OVH, Scaleway, Hetzner',
        'type' => 'Bare Metal / Dedicated'
    ],
    'enterprise' => [
        'name' => 'Serveur Enterprise',
        'desc' => 'Grandes entreprises (300-500 employés)',
        'cpu' => 32, 'ram' => 64, 'storage' => 1000,
        'maxEmployees' => 500, 'maxConcurrent' => 250,
        'costMin' => 100000, 'costMax' => 200000,
        'providers' => 'OVH, AWS, GCP, Azure',
        'type' => 'Dedicated / Cloud Enterprise'
    ],
    'gpu' => [
        'name' => 'Serveur GPU (IA)',
        'desc' => 'Avec modules IA/ML',
        'cpu' => 16, 'ram' => 64, 'storage' => 500, 'gpu' => 16,
        'maxEmployees' => 500, 'maxConcurrent' => 100,
        'costMin' => 150000, 'costMax' => 400000,
        'providers' => 'AWS, GCP, Azure, Lambda Labs',
        'type' => 'Cloud GPU / A100/H100'
    ]
];

$currentPage = 'simulator';
$pageTitle = 'Simulateur Ressources - License Server';
?>
<?php include 'includes/header.php'; ?>
<style>
    .resource-bar { transition: width 0.5s ease-out; }
    .module-card:hover { transform: translateY(-2px); box-shadow: 0 4px 15px rgba(0,0,0,0.1); }
    .module-card { transition: all 0.2s ease; cursor: pointer; }
    .module-card.selected { border-color: #6366f1 !important; background: rgba(99, 102, 241, 0.1) !important; }
    .result-card { animation: slideUp 0.4s ease-out; }
    @keyframes slideUp {
        from { opacity: 0; transform: translateY(20px); }
        to { opacity: 1; transform: translateY(0); }
    }
    .gauge-circle { transition: stroke-dashoffset 0.5s ease-out; }
    .tier-card { transition: all 0.3s ease; }
    .tier-card.active { border-color: #6366f1; box-shadow: 0 0 0 3px rgba(99,102,241,0.2); }
    .stat-pulse { animation: pulse 2s infinite; }
    @keyframes pulse {
        0%, 100% { opacity: 1; transform: scale(1); }
        50% { opacity: 0.7; transform: scale(1.05); }
    }
</style>
    
<!-- Sidebar -->
<?php include 'includes/sidebar.php'; ?>

<!-- Main Content -->
<main class="ml-60 p-8">
    <div class="max-w-7xl mx-auto">
        
        <!-- Header -->
        <div class="mb-8">
            <div class="flex items-center gap-3 mb-2">
                <div class="w-12 h-12 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-2xl flex items-center justify-center shadow-lg">
                    <i class="fa-solid fa-calculator text-white text-xl"></i>
                </div>
                <div>
                    <h1 class="text-2xl font-bold text-slate-800">Simulateur de Ressources Serveur</h1>
                    <p class="text-slate-500 text-sm">Estimation basée sur des benchmarks réels (ERPNext, Odoo, SAP)</p>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 xl:grid-cols-12 gap-6">
            
            <!-- Left Column - Configuration -->
            <div class="xl:col-span-7 space-y-6">
                
                <!-- Enterprise Size & Usage Pattern -->
                <div class="bg-white rounded-2xl p-6 shadow-sm border border-slate-200">
                    <h2 class="text-lg font-semibold text-slate-800 mb-5 flex items-center gap-2">
                        <i class="fa-solid fa-building text-indigo-500"></i>
                        Configuration de l'Entreprise
                    </h2>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <!-- Employee Count -->
                        <div>
                            <label class="text-sm font-medium text-slate-600 mb-2 block">
                                <i class="fa-solid fa-users mr-2 text-slate-400"></i>Nombre d'Employés
                            </label>
                            <div class="flex items-center gap-3">
                                <input type="range" id="employeeSlider" min="1" max="500" value="25" 
                                       class="flex-1 h-2 bg-slate-200 rounded-lg appearance-none cursor-pointer accent-indigo-600">
                                <input type="number" id="employeeCount" value="25" min="1" max="10000"
                                       class="w-20 px-3 py-2 border border-slate-300 rounded-lg text-center font-bold text-indigo-600 text-lg">
                            </div>
                            <p class="text-xs text-slate-400 mt-1">Total des employés dans le système</p>
                        </div>
                        
                        <!-- Concurrent Users -->
                        <div>
                            <label class="text-sm font-medium text-slate-600 mb-2 block">
                                <i class="fa-solid fa-user-clock mr-2 text-slate-400"></i>Utilisateurs Simultanés
                            </label>
                            <div class="flex items-center gap-3">
                                <input type="range" id="concurrentSlider" min="1" max="200" value="10" 
                                       class="flex-1 h-2 bg-slate-200 rounded-lg appearance-none cursor-pointer accent-emerald-600">
                                <input type="number" id="concurrentUsers" value="10" min="1" max="1000"
                                       class="w-20 px-3 py-2 border border-slate-300 rounded-lg text-center font-bold text-emerald-600 text-lg">
                            </div>
                            <p class="text-xs text-slate-400 mt-1">Pic d'utilisateurs en même temps (~30-50% des employés)</p>
                        </div>
                        
                        <!-- Data Retention -->
                        <div>
                            <label class="text-sm font-medium text-slate-600 mb-2 block">
                                <i class="fa-solid fa-clock-rotate-left mr-2 text-slate-400"></i>Durée de Rétention
                            </label>
                            <select id="retentionYears" class="w-full px-3 py-2 border border-slate-300 rounded-lg text-slate-700">
                                <option value="1">1 an</option>
                                <option value="2">2 ans</option>
                                <option value="3" selected>3 ans</option>
                                <option value="5">5 ans</option>
                                <option value="10">10 ans (archivage légal)</option>
                            </select>
                            <p class="text-xs text-slate-400 mt-1">Historique des données conservé</p>
                        </div>
                        
                        <!-- Usage Intensity -->
                        <div>
                            <label class="text-sm font-medium text-slate-600 mb-2 block">
                                <i class="fa-solid fa-gauge-high mr-2 text-slate-400"></i>Intensité d'Utilisation
                            </label>
                            <select id="usageIntensity" class="w-full px-3 py-2 border border-slate-300 rounded-lg text-slate-700">
                                <option value="light">Légère (consultations, reporting occasionnel)</option>
                                <option value="normal" selected>Normale (saisie quotidienne, rapports)</option>
                                <option value="heavy">Intensive (transactions fréquentes, temps réel)</option>
                                <option value="extreme">Extrême (POS, production 24/7)</option>
                            </select>
                            <p class="text-xs text-slate-400 mt-1">Influence le CPU et la RAM nécessaires</p>
                        </div>
                    </div>
                </div>

                <!-- Module Selection -->
                <div class="bg-white rounded-2xl p-6 shadow-sm border border-slate-200">
                    <div class="flex items-center justify-between mb-5">
                        <h2 class="text-lg font-semibold text-slate-800 flex items-center gap-2">
                            <i class="fa-solid fa-puzzle-piece text-indigo-500"></i>
                            Modules Activés
                        </h2>
                        <div class="flex gap-2">
                            <button onclick="selectAllModules()" class="px-3 py-1.5 text-xs font-medium bg-indigo-100 text-indigo-700 rounded-lg hover:bg-indigo-200 transition">
                                <i class="fa-solid fa-check-double mr-1"></i>Tout
                            </button>
                            <button onclick="deselectAllModules()" class="px-3 py-1.5 text-xs font-medium bg-slate-100 text-slate-600 rounded-lg hover:bg-slate-200 transition">
                                <i class="fa-solid fa-xmark mr-1"></i>Aucun
                            </button>
                        </div>
                    </div>

                    <div class="space-y-5">
                        <?php foreach ($modulesByCategory as $category => $mods): ?>
                        <div>
                            <h3 class="text-xs font-bold text-slate-500 mb-3 uppercase tracking-wider flex items-center gap-2">
                                <span class="w-2 h-2 rounded-full bg-<?= $category === 'ai' ? 'purple' : ($category === 'hr' ? 'blue' : ($category === 'finance' ? 'emerald' : 'indigo')) ?>-500"></span>
                                <?= htmlspecialchars($categoryNames[$category] ?? ucfirst($category)) ?>
                                <span class="text-slate-400 font-normal">(<?= count($mods) ?>)</span>
                            </h3>
                            <div class="grid grid-cols-2 lg:grid-cols-3 gap-2">
                                <?php foreach ($mods as $mod): ?>
                                <label class="module-card flex items-center gap-2 p-3 border border-slate-200 rounded-xl hover:border-indigo-300 has-[:checked]:border-indigo-500 has-[:checked]:bg-indigo-50">
                                    <input type="checkbox" name="modules[]" value="<?= htmlspecialchars($mod['code']) ?>" 
                                           data-category="<?= htmlspecialchars($category) ?>"
                                           class="module-checkbox w-4 h-4 text-indigo-600 rounded border-slate-300" 
                                           <?= $mod['is_core'] ? 'checked disabled' : '' ?>
                                           onchange="calculateResources()">
                                    <i class="fa-solid <?= htmlspecialchars($mod['icon'] ?: 'fa-cube') ?> text-slate-400 text-sm w-4"></i>
                                    <span class="text-sm font-medium text-slate-700 truncate"><?= htmlspecialchars($mod['name']) ?></span>
                                    <?php if ($mod['is_core']): ?>
                                    <span class="ml-auto text-[10px] bg-emerald-100 text-emerald-700 px-1.5 py-0.5 rounded">Core</span>
                                    <?php endif; ?>
                                </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <!-- Right Column - Results -->
            <div class="xl:col-span-5 space-y-6">
                
                <!-- Resource Gauges -->
                <div class="bg-gradient-to-br from-slate-800 to-slate-900 rounded-2xl p-6 shadow-xl text-white">
                    <h2 class="text-base font-semibold mb-5 flex items-center gap-2">
                        <i class="fa-solid fa-microchip text-indigo-400"></i>
                        Ressources Calculées
                    </h2>
                    
                    <div class="grid grid-cols-2 gap-4 mb-6">
                        <!-- CPU Gauge -->
                        <div class="text-center">
                            <div class="relative w-24 h-24 mx-auto mb-2">
                                <svg class="w-full h-full transform -rotate-90" viewBox="0 0 100 100">
                                    <circle cx="50" cy="50" r="45" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="8"/>
                                    <circle id="cpuGauge" cx="50" cy="50" r="45" fill="none" stroke="#6366f1" stroke-width="8" 
                                            stroke-dasharray="283" stroke-dashoffset="200" stroke-linecap="round" class="gauge-circle"/>
                                </svg>
                                <div class="absolute inset-0 flex flex-col items-center justify-center">
                                    <span id="cpuValue" class="text-xl font-bold">2</span>
                                    <span class="text-[10px] text-slate-400">vCPU</span>
                                </div>
                            </div>
                            <p class="text-xs text-slate-400">Processeur</p>
                        </div>
                        
                        <!-- RAM Gauge -->
                        <div class="text-center">
                            <div class="relative w-24 h-24 mx-auto mb-2">
                                <svg class="w-full h-full transform -rotate-90" viewBox="0 0 100 100">
                                    <circle cx="50" cy="50" r="45" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="8"/>
                                    <circle id="ramGauge" cx="50" cy="50" r="45" fill="none" stroke="#10b981" stroke-width="8" 
                                            stroke-dasharray="283" stroke-dashoffset="200" stroke-linecap="round" class="gauge-circle"/>
                                </svg>
                                <div class="absolute inset-0 flex flex-col items-center justify-center">
                                    <span id="ramValue" class="text-xl font-bold">4</span>
                                    <span class="text-[10px] text-slate-400">GB RAM</span>
                                </div>
                            </div>
                            <p class="text-xs text-slate-400">Mémoire</p>
                        </div>
                        
                        <!-- Storage Gauge -->
                        <div class="text-center">
                            <div class="relative w-24 h-24 mx-auto mb-2">
                                <svg class="w-full h-full transform -rotate-90" viewBox="0 0 100 100">
                                    <circle cx="50" cy="50" r="45" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="8"/>
                                    <circle id="storageGauge" cx="50" cy="50" r="45" fill="none" stroke="#f59e0b" stroke-width="8" 
                                            stroke-dasharray="283" stroke-dashoffset="200" stroke-linecap="round" class="gauge-circle"/>
                                </svg>
                                <div class="absolute inset-0 flex flex-col items-center justify-center">
                                    <span id="storageValue" class="text-xl font-bold">50</span>
                                    <span class="text-[10px] text-slate-400">GB SSD</span>
                                </div>
                            </div>
                            <p class="text-xs text-slate-400">Stockage</p>
                        </div>
                        
                        <!-- Bandwidth -->
                        <div class="text-center">
                            <div class="relative w-24 h-24 mx-auto mb-2">
                                <svg class="w-full h-full transform -rotate-90" viewBox="0 0 100 100">
                                    <circle cx="50" cy="50" r="45" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="8"/>
                                    <circle id="bandwidthGauge" cx="50" cy="50" r="45" fill="none" stroke="#ec4899" stroke-width="8" 
                                            stroke-dasharray="283" stroke-dashoffset="200" stroke-linecap="round" class="gauge-circle"/>
                                </svg>
                                <div class="absolute inset-0 flex flex-col items-center justify-center">
                                    <span id="bandwidthValue" class="text-xl font-bold">1</span>
                                    <span class="text-[10px] text-slate-400">TB/mois</span>
                                </div>
                            </div>
                            <p class="text-xs text-slate-400">Bande Passante</p>
                        </div>
                    </div>
                    
                    <!-- GPU Warning -->
                    <div id="gpuSection" class="hidden p-3 bg-amber-500/20 border border-amber-500/30 rounded-xl mb-4">
                        <div class="flex items-center gap-3">
                            <i class="fa-solid fa-microchip text-amber-400 stat-pulse"></i>
                            <div>
                                <p class="font-medium text-amber-300 text-sm">GPU Requis</p>
                                <p class="text-xs text-amber-200/70">Les modules IA nécessitent un GPU dédié (8-16 GB VRAM)</p>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Quick Stats -->
                    <div class="grid grid-cols-3 gap-3 pt-4 border-t border-white/10">
                        <div class="text-center">
                            <p id="dbSizeValue" class="text-lg font-bold text-indigo-400">2 GB</p>
                            <p class="text-[10px] text-slate-500">Base de données</p>
                        </div>
                        <div class="text-center">
                            <p id="backupValue" class="text-lg font-bold text-emerald-400">6 GB</p>
                            <p class="text-[10px] text-slate-500">Backups (3x)</p>
                        </div>
                        <div class="text-center">
                            <p id="peakRamValue" class="text-lg font-bold text-amber-400">6 GB</p>
                            <p class="text-[10px] text-slate-500">RAM Pic (1.5x)</p>
                        </div>
                    </div>
                </div>

                <!-- Server Recommendation -->
                <div class="bg-white rounded-2xl p-6 shadow-sm border border-slate-200">
                    <h2 class="text-base font-semibold text-slate-800 mb-4 flex items-center gap-2">
                        <i class="fa-solid fa-server text-indigo-500"></i>
                        Serveur Recommandé
                    </h2>
                    
                    <div id="serverRecommendation" class="result-card">
                        <div id="tierCard" class="p-4 bg-gradient-to-r from-indigo-50 to-purple-50 border border-indigo-200 rounded-xl mb-4">
                            <div class="flex items-start gap-3">
                                <div class="w-12 h-12 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg flex-shrink-0">
                                    <i id="tierIcon" class="fa-solid fa-cloud text-white"></i>
                                </div>
                                <div class="flex-1 min-w-0">
                                    <h3 id="serverTier" class="font-bold text-indigo-800 text-lg">VPS Standard</h3>
                                    <p id="serverDesc" class="text-sm text-indigo-600">PME en croissance</p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="space-y-3 text-sm">
                            <div class="flex justify-between items-center py-2 border-b border-slate-100">
                                <span class="text-slate-500 flex items-center gap-2">
                                    <i class="fa-solid fa-server w-4 text-slate-400"></i>Type
                                </span>
                                <span id="serverType" class="font-medium text-slate-700">Cloud VPS</span>
                            </div>
                            <div class="flex justify-between items-center py-2 border-b border-slate-100">
                                <span class="text-slate-500 flex items-center gap-2">
                                    <i class="fa-solid fa-microchip w-4 text-slate-400"></i>Config Minimale
                                </span>
                                <span id="minConfig" class="font-medium text-slate-700">4 vCPU / 8 GB</span>
                            </div>
                            <div class="flex justify-between items-center py-2 border-b border-slate-100">
                                <span class="text-slate-500 flex items-center gap-2">
                                    <i class="fa-solid fa-money-bill-wave w-4 text-slate-400"></i>Coût Estimé
                                </span>
                                <span id="serverCost" class="font-bold text-emerald-600">12,000 - 25,000 DA/mois</span>
                            </div>
                            <div class="flex justify-between items-center py-2">
                                <span class="text-slate-500 flex items-center gap-2">
                                    <i class="fa-solid fa-cloud w-4 text-slate-400"></i>Fournisseurs
                                </span>
                                <span id="providerList" class="font-medium text-slate-700 text-right">DigitalOcean, Linode</span>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Performance Score -->
                <div class="bg-white rounded-2xl p-6 shadow-sm border border-slate-200">
                    <h2 class="text-base font-semibold text-slate-800 mb-4 flex items-center gap-2">
                        <i class="fa-solid fa-gauge-high text-indigo-500"></i>
                        Score de Performance Estimé
                    </h2>
                    
                    <div class="flex items-center gap-4 mb-4">
                        <div id="perfScoreRing" class="relative w-20 h-20 flex-shrink-0">
                            <svg class="w-full h-full transform -rotate-90" viewBox="0 0 100 100">
                                <circle cx="50" cy="50" r="40" fill="none" stroke="#e2e8f0" stroke-width="10"/>
                                <circle id="perfGauge" cx="50" cy="50" r="40" fill="none" stroke="#10b981" stroke-width="10" 
                                        stroke-dasharray="251" stroke-dashoffset="50" stroke-linecap="round" class="gauge-circle"/>
                            </svg>
                            <div class="absolute inset-0 flex items-center justify-center">
                                <span id="perfScore" class="text-2xl font-black text-emerald-600">85</span>
                            </div>
                        </div>
                        <div>
                            <p id="perfLabel" class="font-bold text-emerald-700">Excellent</p>
                            <p id="perfDesc" class="text-xs text-slate-500">Configuration optimale pour votre usage</p>
                        </div>
                    </div>
                    
                    <div class="grid grid-cols-3 gap-2 text-center text-xs">
                        <div class="p-2 bg-slate-50 rounded-lg">
                            <p id="responseTime" class="font-bold text-slate-700">&lt; 200ms</p>
                            <p class="text-slate-400">Temps réponse</p>
                        </div>
                        <div class="p-2 bg-slate-50 rounded-lg">
                            <p id="uptime" class="font-bold text-slate-700">99.9%</p>
                            <p class="text-slate-400">Disponibilité</p>
                        </div>
                        <div class="p-2 bg-slate-50 rounded-lg">
                            <p id="scalability" class="font-bold text-slate-700">+50%</p>
                            <p class="text-slate-400">Marge croissance</p>
                        </div>
                    </div>
                </div>

                <!-- Actions -->
                <div class="flex gap-3">
                    <button onclick="printReport()" class="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-indigo-600 text-white rounded-xl font-medium hover:bg-indigo-700 transition">
                        <i class="fa-solid fa-file-pdf"></i>
                        Exporter PDF
                    </button>
                    <button onclick="copyConfig()" class="px-4 py-3 bg-slate-100 text-slate-700 rounded-xl font-medium hover:bg-slate-200 transition">
                        <i class="fa-solid fa-copy"></i>
                    </button>
                </div>
            </div>
        </div>
        
        <!-- Methodology Note -->
        <div class="mt-8 p-4 bg-slate-50 rounded-xl border border-slate-200">
            <h3 class="font-semibold text-slate-700 text-sm mb-2 flex items-center gap-2">
                <i class="fa-solid fa-circle-info text-slate-400"></i>
                Méthodologie de Calcul
            </h3>
            <p class="text-xs text-slate-500 leading-relaxed">
                Ces estimations sont basées sur des benchmarks réels de systèmes ERP (ERPNext, Odoo, SAP Business One). 
                <strong>Règles appliquées :</strong> ~0.3 vCPU par utilisateur concurrent, ~60-100 MB RAM par utilisateur actif, 
                stockage = données × années × facteur module, marge de sécurité de 1.5x pour les pics de charge.
                Les coûts sont indicatifs et varient selon le fournisseur et la région.
            </p>
        </div>
    </div>
</main>

<script>
    // Resource profiles from PHP
    const resourceProfiles = <?= json_encode($resourceProfiles) ?>;
    const serverTiers = <?= json_encode($serverTiers) ?>;
    
    // Usage intensity multipliers
    const intensityMultipliers = {
        light: { cpu: 0.7, ram: 0.8 },
        normal: { cpu: 1.0, ram: 1.0 },
        heavy: { cpu: 1.4, ram: 1.3 },
        extreme: { cpu: 2.0, ram: 1.6 }
    };
    
    // Base system requirements (OS, web server, database server)
    const BASE_SYSTEM = {
        cpu: 1,      // 1 core for OS/nginx/PHP-FPM
        ram: 1.5,    // 1.5 GB for OS + services
        storage: 10  // 10 GB for OS + software
    };
    
    // Database overhead per employee per year (GB)
    const DB_PER_EMPLOYEE_PER_YEAR = 0.1; // ~100 MB per employee per year base
    
    // Slider synchronization
    const employeeSlider = document.getElementById('employeeSlider');
    const employeeCount = document.getElementById('employeeCount');
    const concurrentSlider = document.getElementById('concurrentSlider');
    const concurrentUsers = document.getElementById('concurrentUsers');
    const retentionYears = document.getElementById('retentionYears');
    const usageIntensity = document.getElementById('usageIntensity');
    
    employeeSlider.addEventListener('input', function() {
        employeeCount.value = this.value;
        // Auto-adjust concurrent users (30-50% of employees)
        const suggestedConcurrent = Math.max(1, Math.round(this.value * 0.4));
        if (suggestedConcurrent <= 200) {
            concurrentUsers.value = suggestedConcurrent;
            concurrentSlider.value = suggestedConcurrent;
        }
        calculateResources();
    });
    
    employeeCount.addEventListener('input', function() {
        const val = Math.min(10000, Math.max(1, parseInt(this.value) || 1));
        this.value = val;
        employeeSlider.value = Math.min(500, val);
        calculateResources();
    });
    
    concurrentSlider.addEventListener('input', function() {
        concurrentUsers.value = this.value;
        calculateResources();
    });
    
    concurrentUsers.addEventListener('input', function() {
        const val = Math.min(1000, Math.max(1, parseInt(this.value) || 1));
        this.value = val;
        concurrentSlider.value = Math.min(200, val);
        calculateResources();
    });
    
    retentionYears.addEventListener('change', calculateResources);
    usageIntensity.addEventListener('change', calculateResources);
    
    function selectAllModules() {
        document.querySelectorAll('.module-checkbox:not(:disabled)').forEach(cb => cb.checked = true);
        calculateResources();
    }
    
    function deselectAllModules() {
        document.querySelectorAll('.module-checkbox:not(:disabled)').forEach(cb => cb.checked = false);
        calculateResources();
    }
    
    function calculateResources() {
        const employees = parseInt(employeeCount.value) || 1;
        const concurrent = parseInt(concurrentUsers.value) || 1;
        const years = parseInt(retentionYears.value) || 3;
        const intensity = usageIntensity.value;
        const multiplier = intensityMultipliers[intensity];
        
        // Start with base system requirements
        let cpu = BASE_SYSTEM.cpu;
        let ram = BASE_SYSTEM.ram;
        let storage = BASE_SYSTEM.storage;
        let needsGpu = false;
        let moduleCount = 0;
        let hasDbIntensive = false;
        
        // Calculate module resources
        document.querySelectorAll('.module-checkbox:checked').forEach(cb => {
            const category = cb.dataset.category || 'other';
            const profile = resourceProfiles[category] || resourceProfiles['other'];
            
            // Base module requirements
            cpu += profile.baseCpu || 0;
            ram += profile.baseRam || 0;
            storage += profile.baseStorage || 0;
            
            // Per-concurrent user scaling
            cpu += concurrent * (profile.perUserCpu || 0);
            ram += concurrent * ((profile.perUserRam || 0) / 1024); // Convert MB to GB
            
            // Storage growth over time
            storage += employees * years * (profile.perEmployeeStorage || 0);
            
            if (profile.needsGpu) needsGpu = true;
            if (profile.dbIntensive) hasDbIntensive = true;
            moduleCount++;
        });
        
        // Apply intensity multiplier
        cpu *= multiplier.cpu;
        ram *= multiplier.ram;
        
        // Add database server overhead if DB-intensive modules are used
        if (hasDbIntensive) {
            ram += 2; // Extra 2GB for database caching
            cpu += 0.5; // Extra CPU for database queries
        }
        
        // Calculate derived values
        const dbSize = Math.ceil(employees * years * DB_PER_EMPLOYEE_PER_YEAR * moduleCount * 0.3);
        const bandwidth = Math.max(1, Math.ceil(concurrent * 0.05)); // ~50MB per user per month minimum
        const peakRam = ram * 1.5; // Peak memory can be 50% higher
        const backupSize = dbSize * 3; // Keep 3 backup copies
        
        // Round values appropriately
        cpu = Math.max(1, Math.ceil(cpu));
        ram = Math.max(2, Math.ceil(ram));
        storage = Math.max(20, Math.ceil(storage + dbSize + backupSize));
        
        // Update gauges (max scale: CPU=32, RAM=128, Storage=2000, Bandwidth=10)
        updateGauge('cpuGauge', cpu, 32);
        updateGauge('ramGauge', ram, 128);
        updateGauge('storageGauge', storage, 2000);
        updateGauge('bandwidthGauge', bandwidth, 10);
        
        // Update values
        document.getElementById('cpuValue').textContent = cpu;
        document.getElementById('ramValue').textContent = ram;
        document.getElementById('storageValue').textContent = storage;
        document.getElementById('bandwidthValue').textContent = bandwidth;
        document.getElementById('dbSizeValue').textContent = dbSize + ' GB';
        document.getElementById('backupValue').textContent = backupSize + ' GB';
        document.getElementById('peakRamValue').textContent = Math.ceil(peakRam) + ' GB';
        
        // GPU section
        document.getElementById('gpuSection').classList.toggle('hidden', !needsGpu);
        
        // Server recommendation
        updateServerRecommendation(cpu, ram, storage, needsGpu, employees, concurrent);
        
        // Performance score
        updatePerformanceScore(cpu, ram, storage, employees, concurrent, intensity);
    }
    
    function updateGauge(id, value, max) {
        const circumference = 283; // 2 * PI * 45
        const offset = circumference - (Math.min(value, max) / max) * circumference;
        document.getElementById(id).style.strokeDashoffset = offset;
    }
    
    function updateServerRecommendation(cpu, ram, storage, needsGpu, employees, concurrent) {
        let selectedTier = null;
        
        if (needsGpu) {
            selectedTier = serverTiers.gpu;
        } else {
            // Find appropriate tier based on requirements
            const tierOrder = ['micro', 'starter', 'standard', 'performance', 'business', 'enterprise'];
            for (const tierKey of tierOrder) {
                const tier = serverTiers[tierKey];
                if (tier.cpu >= cpu && tier.ram >= ram && tier.storage >= storage && 
                    tier.maxEmployees >= employees && tier.maxConcurrent >= concurrent) {
                    selectedTier = tier;
                    break;
                }
            }
            // Fallback to enterprise if nothing fits
            if (!selectedTier) selectedTier = serverTiers.enterprise;
        }
        
        // Update UI
        document.getElementById('serverTier').textContent = selectedTier.name;
        document.getElementById('serverDesc').textContent = selectedTier.desc;
        document.getElementById('serverType').textContent = selectedTier.type;
        document.getElementById('minConfig').textContent = `${selectedTier.cpu} vCPU / ${selectedTier.ram} GB`;
        document.getElementById('serverCost').textContent = `${selectedTier.costMin.toLocaleString()} - ${selectedTier.costMax.toLocaleString()} DA/mois`;
        document.getElementById('providerList').textContent = selectedTier.providers;
        
        // Update icon based on tier
        const iconMap = {
            'micro': 'fa-cloud',
            'starter': 'fa-cloud',
            'standard': 'fa-server',
            'performance': 'fa-server',
            'business': 'fa-database',
            'enterprise': 'fa-building',
            'gpu': 'fa-microchip'
        };
        document.getElementById('tierIcon').className = 'fa-solid ' + (iconMap[Object.keys(serverTiers).find(k => serverTiers[k] === selectedTier)] || 'fa-server') + ' text-white';
    }
    
    function updatePerformanceScore(cpu, ram, storage, employees, concurrent, intensity) {
        // Calculate a performance score based on headroom
        let score = 100;
        
        // Deduct for high utilization ratios
        const cpuRatio = concurrent / (cpu * 6); // ~6 concurrent users per core is optimal
        const ramRatio = (concurrent * 0.1) / ram; // ~100MB per concurrent user
        
        if (cpuRatio > 0.8) score -= 20;
        else if (cpuRatio > 0.6) score -= 10;
        
        if (ramRatio > 0.8) score -= 20;
        else if (ramRatio > 0.6) score -= 10;
        
        // Intensity penalty
        if (intensity === 'extreme') score -= 15;
        else if (intensity === 'heavy') score -= 5;
        
        // Employee density check
        if (employees > 300 && cpu < 16) score -= 10;
        if (employees > 150 && cpu < 8) score -= 10;
        
        score = Math.max(40, Math.min(100, score));
        
        // Update UI
        document.getElementById('perfScore').textContent = score;
        
        // Update gauge
        const circumference = 251;
        const offset = circumference - (score / 100) * circumference;
        document.getElementById('perfGauge').style.strokeDashoffset = offset;
        
        // Color and label
        let color, label, desc;
        if (score >= 85) {
            color = '#10b981'; label = 'Excellent';
            desc = 'Configuration optimale avec marge de croissance';
        } else if (score >= 70) {
            color = '#6366f1'; label = 'Bon';
            desc = 'Performance satisfaisante pour l\'usage prévu';
        } else if (score >= 55) {
            color = '#f59e0b'; label = 'Acceptable';
            desc = 'Peut ralentir en période de forte charge';
        } else {
            color = '#ef4444'; label = 'Insuffisant';
            desc = 'Risque de lenteurs, envisagez une config supérieure';
        }
        
        document.getElementById('perfGauge').style.stroke = color;
        document.getElementById('perfScore').style.color = color;
        document.getElementById('perfLabel').textContent = label;
        document.getElementById('perfLabel').style.color = color;
        document.getElementById('perfDesc').textContent = desc;
        
        // Response time estimation
        const responseTime = score >= 85 ? '<100ms' : score >= 70 ? '<200ms' : score >= 55 ? '<500ms' : '>500ms';
        const scalability = score >= 85 ? '+100%' : score >= 70 ? '+50%' : score >= 55 ? '+20%' : '0%';
        
        document.getElementById('responseTime').textContent = responseTime;
        document.getElementById('scalability').textContent = scalability;
    }
    
    function printReport() {
        window.print();
    }
    
    function copyConfig() {
        const config = {
            employees: employeeCount.value,
            concurrent: concurrentUsers.value,
            cpu: document.getElementById('cpuValue').textContent,
            ram: document.getElementById('ramValue').textContent,
            storage: document.getElementById('storageValue').textContent,
            server: document.getElementById('serverTier').textContent,
            cost: document.getElementById('serverCost').textContent
        };
        
        const text = `Configuration ERP Recommandée:
- Employés: ${config.employees}
- Utilisateurs simultanés: ${config.concurrent}
- CPU: ${config.cpu} vCPU
- RAM: ${config.ram} GB
- Stockage: ${config.storage} GB
- Serveur: ${config.server}
- Coût estimé: ${config.cost}`;
        
        navigator.clipboard.writeText(text).then(() => {
            alert('Configuration copiée dans le presse-papiers !');
        });
    }
    
    // Initial calculation
    calculateResources();
</script>
</body>
</html>
