<?php
/**
 * Migration Script: Add streak_updated_date column
 * Run this once to fix the streak counting issue
 */

// Enable error display for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'includes/config.php';

try {
    $pdo = getDBConnection();
    
    echo "<h2>Running Migration: Add Streak Tracking</h2>";
    echo "<pre>";
    
    // Check if column already exists
    $checkStmt = $pdo->query("
        SELECT COUNT(*) as col_exists 
        FROM information_schema.COLUMNS 
        WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'user_stats' 
        AND COLUMN_NAME = 'streak_updated_date'
    ");
    $result = $checkStmt->fetch(PDO::FETCH_ASSOC);
    
    if ($result['col_exists'] > 0) {
        echo "✓ Column 'streak_updated_date' already exists in user_stats table.\n";
    } else {
        echo "Adding 'streak_updated_date' column to user_stats table...\n";
        
        $pdo->exec("
            ALTER TABLE user_stats 
            ADD COLUMN streak_updated_date DATE DEFAULT NULL
            COMMENT 'Track when streak was last updated to prevent duplicates'
        ");
        
        echo "✓ Column added successfully!\n";
    }
    
    // Update existing rows
    echo "\nUpdating existing records...\n";
    $updateStmt = $pdo->prepare("
        UPDATE user_stats 
        SET streak_updated_date = CURDATE() 
        WHERE consecutive_days > 0 AND streak_updated_date IS NULL
    ");
    $updateStmt->execute();
    $rowsUpdated = $updateStmt->rowCount();
    
    echo "✓ Updated $rowsUpdated existing user records.\n";
    
    echo "\n<strong>Migration completed successfully!</strong>\n";
    echo "\nYou can now safely delete this file (run_migration.php).\n";
    echo "</pre>";
    
    echo "<p><a href='chat.php'>← Back to Chat</a></p>";
    
} catch (PDOException $e) {
    echo "<h2>Migration Failed</h2>";
    echo "<pre style='color: red;'>";
    echo "Error: " . htmlspecialchars($e->getMessage());
    echo "</pre>";
    echo "<p>Please check your database connection and try again.</p>";
}
?>
