<?php
/**
 * License Server Installation Script - Clean Design
 */
session_start();

$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'license_server';

$messages = [];
$success = true;

try {
    $pdo = new PDO("mysql:host=$host", $user, $pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);
    $messages[] = ['✓ Connected to MySQL', 'ok'];
    
    $pdo->exec("CREATE DATABASE IF NOT EXISTS `$dbname` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
    $pdo->exec("USE `$dbname`");
    $messages[] = ['✓ Database created', 'ok'];
    
    // Create all tables
    $pdo->exec("CREATE TABLE IF NOT EXISTS tenants (
        id CHAR(36) PRIMARY KEY,
        code VARCHAR(20) UNIQUE NOT NULL,
        name VARCHAR(255) NOT NULL,
        contact_name VARCHAR(255),
        contact_email VARCHAR(255) NOT NULL,
        contact_phone VARCHAR(50),
        address TEXT,
        timezone VARCHAR(50) DEFAULT 'Europe/Paris',
        language VARCHAR(5) DEFAULT 'fr',
        status ENUM('trial', 'active', 'suspended', 'churned') DEFAULT 'trial',
        trial_ends_at DATETIME,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_status (status),
        INDEX idx_code (code)
    ) ENGINE=InnoDB");
    
    $pdo->exec("CREATE TABLE IF NOT EXISTS instances (
        id CHAR(36) PRIMARY KEY,
        tenant_id CHAR(36) NOT NULL,
        license_key VARCHAR(128) UNIQUE NOT NULL,
        public_key TEXT,
        server_url VARCHAR(255),
        server_ip VARCHAR(45),
        version VARCHAR(20),
        environment ENUM('production', 'staging', 'development') DEFAULT 'production',
        last_heartbeat DATETIME,
        is_active TINYINT(1) DEFAULT 1,
        metadata JSON,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
    ) ENGINE=InnoDB");
    
    $pdo->exec("CREATE TABLE IF NOT EXISTS modules (
        id INT AUTO_INCREMENT PRIMARY KEY,
        code VARCHAR(50) UNIQUE NOT NULL,
        name VARCHAR(100) NOT NULL,
        description TEXT,
        category VARCHAR(50),
        icon VARCHAR(100),
        price_monthly DECIMAL(10,2) DEFAULT 0.00,
        price_yearly DECIMAL(10,2) DEFAULT 0.00,
        is_core TINYINT(1) DEFAULT 0,
        dependencies TEXT,
        sort_order INT DEFAULT 0,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB");
    
    $pdo->exec("CREATE TABLE IF NOT EXISTS subscriptions (
        id CHAR(36) PRIMARY KEY,
        tenant_id CHAR(36) NOT NULL,
        plan_type ENUM('starter', 'professional', 'enterprise', 'custom') DEFAULT 'starter',
        billing_cycle ENUM('monthly', 'yearly') DEFAULT 'monthly',
        max_users INT DEFAULT 5,
        max_employees INT DEFAULT 50,
        max_storage_gb INT DEFAULT 10,
        starts_at DATE NOT NULL,
        expires_at DATE,
        auto_renew TINYINT(1) DEFAULT 1,
        status ENUM('active', 'expired', 'cancelled') DEFAULT 'active',
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
    ) ENGINE=InnoDB");
    
    $pdo->exec("CREATE TABLE IF NOT EXISTS subscription_modules (
        id INT AUTO_INCREMENT PRIMARY KEY,
        subscription_id CHAR(36) NOT NULL,
        module_code VARCHAR(50) NOT NULL,
        granted_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        revoked_at DATETIME NULL,
        is_active TINYINT(1) DEFAULT 1,
        FOREIGN KEY (subscription_id) REFERENCES subscriptions(id) ON DELETE CASCADE,
        FOREIGN KEY (module_code) REFERENCES modules(code) ON DELETE CASCADE,
        UNIQUE KEY unique_sub_module (subscription_id, module_code)
    ) ENGINE=InnoDB");
    
    $pdo->exec("CREATE TABLE IF NOT EXISTS telemetry (
        id BIGINT AUTO_INCREMENT PRIMARY KEY,
        instance_id CHAR(36) NOT NULL,
        event_type VARCHAR(50),
        user_count INT,
        storage_used_mb INT,
        active_sessions INT,
        payload JSON,
        client_ip VARCHAR(45),
        recorded_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (instance_id) REFERENCES instances(id) ON DELETE CASCADE
    ) ENGINE=InnoDB");
    
    $pdo->exec("CREATE TABLE IF NOT EXISTS audit_logs (
        id BIGINT AUTO_INCREMENT PRIMARY KEY,
        tenant_id CHAR(36),
        actor_type ENUM('admin', 'system', 'api') DEFAULT 'admin',
        actor_id VARCHAR(100),
        action VARCHAR(100) NOT NULL,
        target_type VARCHAR(50),
        target_id VARCHAR(100),
        old_value JSON,
        new_value JSON,
        ip_address VARCHAR(45),
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE SET NULL
    ) ENGINE=InnoDB");
    
    $pdo->exec("CREATE TABLE IF NOT EXISTS admin_users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(50) UNIQUE NOT NULL,
        email VARCHAR(255) UNIQUE NOT NULL,
        password_hash VARCHAR(255) NOT NULL,
        role ENUM('super_admin', 'admin', 'support') DEFAULT 'admin',
        last_login DATETIME,
        is_active TINYINT(1) DEFAULT 1,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB");
    
    $messages[] = ['✓ All tables created', 'ok'];
    
    // Insert default modules
    $defaultModules = [
        ['rh', 'Ressources Humaines', 'hr', 'fa-solid fa-users-gear', 1, 1],
        ['calendar', 'Calendrier', 'core', 'fa-regular fa-calendar-check', 1, 2],
        ['discussions', 'Discussions', 'core', 'fa-solid fa-comments', 1, 3],
        ['comptabilite', 'Comptabilité', 'finance', 'fa-solid fa-file-invoice-dollar', 0, 4],
        ['facturation', 'Facturation', 'finance', 'fa-solid fa-file-invoice', 0, 5],
        ['documents', 'Documents', 'core', 'fa-solid fa-folder-open', 0, 6],
        ['projets', 'Projets', 'operations', 'fa-solid fa-list-check', 0, 7],
        ['inventaire', 'Inventaire', 'operations', 'fa-solid fa-boxes-stacked', 0, 8],
        ['todo', 'To-do List', 'core', 'fa-solid fa-clipboard-list', 1, 9],
        ['users', 'Utilisateurs', 'admin', 'fa-solid fa-users', 0, 10]
    ];
    
    $stmt = $pdo->prepare("INSERT IGNORE INTO modules (code, name, category, icon, is_core, sort_order) VALUES (?, ?, ?, ?, ?, ?)");
    foreach ($defaultModules as $mod) {
        $stmt->execute($mod);
    }
    $messages[] = ['✓ Default modules inserted', 'ok'];
    
    // Create admin user
    $hash = password_hash('admin', PASSWORD_DEFAULT);
    $stmt = $pdo->query("SELECT id FROM admin_users WHERE username = 'admin'");
    if ($stmt->fetch()) {
        $pdo->prepare("UPDATE admin_users SET password_hash = ? WHERE username = 'admin'")->execute([$hash]);
    } else {
        $pdo->prepare("INSERT INTO admin_users (username, email, password_hash, role) VALUES ('admin', 'admin@chronorex.com', ?, 'super_admin')")->execute([$hash]);
    }
    $messages[] = ['✓ Admin user ready', 'ok'];
    
} catch (PDOException $e) {
    $messages[] = ['✗ Error: ' . $e->getMessage(), 'error'];
    $success = false;
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Installation - License Server</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>* { font-family: 'Inter', sans-serif; }</style>
</head>
<body class="min-h-screen bg-slate-50 flex items-center justify-center p-6">
    
    <div class="w-full max-w-lg">
        <div class="text-center mb-6">
            <div class="inline-flex items-center justify-center w-14 h-14 bg-indigo-600 rounded-2xl mb-4 shadow-lg shadow-indigo-200">
                <i class="fa-solid fa-key text-xl text-white"></i>
            </div>
            <h1 class="text-xl font-bold text-slate-800">License Server</h1>
            <p class="text-slate-500 text-sm">Installation</p>
        </div>

        <div class="bg-white rounded-2xl p-6 shadow-sm border border-slate-200 mb-4">
            <div class="space-y-2 mb-6">
                <?php foreach ($messages as $msg): ?>
                    <div class="flex items-center gap-2 text-sm <?= $msg[1] === 'ok' ? 'text-emerald-600' : 'text-red-600' ?>">
                        <i class="fa-solid <?= $msg[1] === 'ok' ? 'fa-check-circle' : 'fa-times-circle' ?>"></i>
                        <?= htmlspecialchars($msg[0]) ?>
                    </div>
                <?php endforeach; ?>
            </div>
            
            <?php if ($success): ?>
                <div class="bg-emerald-50 border border-emerald-200 rounded-xl p-4 mb-4">
                    <h3 class="font-semibold text-emerald-800 mb-2">✅ Installation Complete</h3>
                    <p class="text-emerald-700 text-sm">Login credentials:</p>
                    <div class="mt-2 space-y-1">
                        <div class="flex items-center gap-2 text-sm">
                            <span class="text-slate-600">Username:</span>
                            <code class="bg-white px-2 py-0.5 rounded border text-slate-800 font-mono">admin</code>
                        </div>
                        <div class="flex items-center gap-2 text-sm">
                            <span class="text-slate-600">Password:</span>
                            <code class="bg-white px-2 py-0.5 rounded border text-slate-800 font-mono">admin</code>
                        </div>
                    </div>
                </div>
                
                <a href="login.php" class="block w-full bg-indigo-600 text-white font-semibold py-3 rounded-xl hover:bg-indigo-700 transition-all text-center">
                    <i class="fa-solid fa-arrow-right mr-2"></i>Go to Login
                </a>
            <?php endif; ?>
        </div>
        
        <?php if ($success): ?>
            <div class="bg-red-50 border border-red-200 rounded-xl p-4">
                <div class="flex items-center gap-2 text-red-700 font-medium text-sm mb-1">
                    <i class="fa-solid fa-triangle-exclamation"></i>
                    Security Warning
                </div>
                <p class="text-red-600 text-sm">Delete this file (install.php) after installation!</p>
            </div>
        <?php endif; ?>
    </div>

</body>
</html>
