<?php
/**
 * Migration: Add module_trials table
 * Run this once to add the trial modules functionality
 */
require_once 'config.php';

echo "<h2>Migration: Module Trials Table</h2>";

try {
    // Create module_trials table
    $sql = "CREATE TABLE IF NOT EXISTS module_trials (
        id INT AUTO_INCREMENT PRIMARY KEY,
        subscription_id CHAR(36) NOT NULL,
        module_code VARCHAR(50) NOT NULL,
        starts_at DATE NOT NULL,
        expires_at DATE NOT NULL,
        granted_by INT,
        notes TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (subscription_id) REFERENCES subscriptions(id) ON DELETE CASCADE,
        FOREIGN KEY (module_code) REFERENCES modules(code) ON DELETE CASCADE,
        UNIQUE KEY unique_trial (subscription_id, module_code),
        INDEX idx_expires (expires_at)
    ) ENGINE=InnoDB";
    
    $pdo->exec($sql);
    echo "<p style='color: green;'>✅ Table 'module_trials' créée avec succès!</p>";
    
    // Show table structure
    $stmt = $pdo->query("DESCRIBE module_trials");
    $columns = $stmt->fetchAll();
    
    echo "<h3>Structure de la table:</h3>";
    echo "<table border='1' cellpadding='5'>";
    echo "<tr><th>Colonne</th><th>Type</th><th>Null</th><th>Clé</th><th>Défaut</th></tr>";
    foreach ($columns as $col) {
        echo "<tr>";
        echo "<td>{$col['Field']}</td>";
        echo "<td>{$col['Type']}</td>";
        echo "<td>{$col['Null']}</td>";
        echo "<td>{$col['Key']}</td>";
        echo "<td>{$col['Default']}</td>";
        echo "</tr>";
    }
    echo "</table>";
    
    echo "<p><a href='admin/subscriptions.php'>→ Aller aux Abonnements</a></p>";
    
} catch (PDOException $e) {
    echo "<p style='color: red;'>❌ Erreur: " . $e->getMessage() . "</p>";
}
?>
