<?php
/**
 * Auto-install migration: Add Impression Control columns
 * Run this script once to add max_views and frequency_cap_hours columns
 * 
 * Access via: http://localhost/license-server/migrations/install_impression_control.php
 */

require_once '../config.php';

header('Content-Type: text/html; charset=utf-8');

echo "<!DOCTYPE html><html><head><title>Migration: Impression Control</title>";
echo "<style>body{font-family:Arial,sans-serif;max-width:600px;margin:50px auto;padding:20px;background:#f4f4f4;}";
echo ".box{background:white;padding:20px;border-radius:8px;box-shadow:0 2px 10px rgba(0,0,0,0.1);}";
echo ".success{color:#059669;background:#ecfdf5;padding:10px;border-radius:4px;margin:10px 0;}";
echo ".error{color:#dc2626;background:#fef2f2;padding:10px;border-radius:4px;margin:10px 0;}";
echo ".info{color:#3b82f6;background:#eff6ff;padding:10px;border-radius:4px;margin:10px 0;}";
echo "</style></head><body><div class='box'>";

echo "<h1>🔧 Migration: Contrôle des Impressions</h1>";

try {
    $results = [];
    
    // FIRST: Create server_ads_stats table if it doesn't exist
    try {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS server_ads_stats (
                id INT AUTO_INCREMENT PRIMARY KEY,
                ad_id INT NOT NULL,
                ip_address VARCHAR(45) NOT NULL,
                action_type ENUM('view', 'click') NOT NULL DEFAULT 'view',
                viewed_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                UNIQUE KEY unique_view (ad_id, ip_address, action_type),
                KEY idx_ad_id (ad_id),
                KEY idx_viewed_at (viewed_at),
                FOREIGN KEY (ad_id) REFERENCES server_ads(id) ON DELETE CASCADE
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
        ");
        $results[] = ['success', '✅ Table <code>server_ads_stats</code> créée/vérifiée'];
    } catch (PDOException $e) {
        $results[] = ['error', '❌ Erreur table server_ads_stats: ' . $e->getMessage()];
    }
    
    // Check if columns already exist in server_ads
    $columns = $pdo->query("SHOW COLUMNS FROM server_ads")->fetchAll(PDO::FETCH_COLUMN);
    
    // Add max_views column if not exists
    if (!in_array('max_views', $columns)) {
        $pdo->exec("ALTER TABLE server_ads ADD COLUMN max_views INT NULL DEFAULT NULL COMMENT 'NULL or 0 = unlimited'");
        $results[] = ['success', '✅ Colonne <code>max_views</code> ajoutée avec succès'];
    } else {
        $results[] = ['info', 'ℹ️ Colonne <code>max_views</code> existe déjà'];
    }
    
    // Add frequency_cap_hours column if not exists
    if (!in_array('frequency_cap_hours', $columns)) {
        $pdo->exec("ALTER TABLE server_ads ADD COLUMN frequency_cap_hours INT DEFAULT 24 COMMENT 'Min hours between showing same ad to same IP, 0 = no limit'");
        $results[] = ['success', '✅ Colonne <code>frequency_cap_hours</code> ajoutée avec succès'];
    } else {
        $results[] = ['info', 'ℹ️ Colonne <code>frequency_cap_hours</code> existe déjà'];
    }
    
    // Fix server_ads_stats table - ensure viewed_at updates on each record
    try {
        // Check if viewed_at column can be modified
        $pdo->exec("ALTER TABLE server_ads_stats MODIFY COLUMN viewed_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP");
        $results[] = ['success', '✅ Colonne <code>viewed_at</code> modifiée pour mise à jour auto'];
    } catch (PDOException $e) {
        // Try adding if doesn't exist
        try {
            $pdo->exec("ALTER TABLE server_ads_stats ADD COLUMN viewed_at DATETIME DEFAULT CURRENT_TIMESTAMP");
            $results[] = ['success', '✅ Colonne <code>viewed_at</code> ajoutée à server_ads_stats'];
        } catch (PDOException $e2) {
            $results[] = ['info', 'ℹ️ Colonne <code>viewed_at</code> déjà correctement configurée'];
        }
    }
    
    // Display results
    foreach ($results as $r) {
        echo "<div class='{$r[0]}'>{$r[1]}</div>";
    }
    
    echo "<hr style='margin:20px 0;border:none;border-top:1px solid #e5e7eb;'>";
    echo "<h3>📊 Structure actuelle de la table:</h3>";
    echo "<table style='width:100%;border-collapse:collapse;font-size:12px;'>";
    echo "<tr style='background:#f9fafb;'><th style='padding:8px;border:1px solid #e5e7eb;'>Colonne</th><th style='padding:8px;border:1px solid #e5e7eb;'>Type</th><th style='padding:8px;border:1px solid #e5e7eb;'>Défaut</th></tr>";
    
    $desc = $pdo->query("DESCRIBE server_ads")->fetchAll();
    foreach ($desc as $col) {
        $highlight = in_array($col['Field'], ['max_views', 'frequency_cap_hours']) ? 'background:#fef3c7;font-weight:bold;' : '';
        echo "<tr style='{$highlight}'>";
        echo "<td style='padding:6px;border:1px solid #e5e7eb;'>{$col['Field']}</td>";
        echo "<td style='padding:6px;border:1px solid #e5e7eb;'>{$col['Type']}</td>";
        echo "<td style='padding:6px;border:1px solid #e5e7eb;'>" . ($col['Default'] ?? 'NULL') . "</td>";
        echo "</tr>";
    }
    echo "</table>";
    
    echo "<div class='success' style='margin-top:20px;'><strong>🎉 Migration terminée !</strong><br>Le système de contrôle des impressions est maintenant opérationnel.</div>";
    echo "<p><a href='../admin/advertising.php' style='color:#3b82f6;'>← Retour à la gestion des publicités</a></p>";
    
} catch (Exception $e) {
    echo "<div class='error'><strong>❌ Erreur:</strong> " . htmlspecialchars($e->getMessage()) . "</div>";
}

echo "</div></body></html>";
