<?php
/**
 * Migration Script: Remove Facebook Fields
 * This script will:
 * 1. Create backup of Facebook fields
 * 2. Remove Facebook fields from members table
 * 3. Update any references to Facebook fields
 */

// Include database connection
include_once('lib/viewer_functions.php');

// Database connection (make sure to replace these with your actual DB credentials)
$servername = "localhost";
$username = "root";  // Your DB username
$password = "";      // Your DB password
$dbname = "cmsb_db";  // Your DB name

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Create backup table
$backupTable = 'members_facebook_backup_' . date('YmdHis');
$createBackupTable = "CREATE TABLE $backupTable LIKE members";
mysqli_query($conn, $createBackupTable);

// Copy Facebook fields to backup
$copyFields = "INSERT INTO $backupTable SELECT * FROM members";
mysqli_query($conn, $copyFields);

// List of Facebook fields to remove
$facebookFields = [
    'facebook_id',
    'facebook_access_token',
    'facebook_first_name',
    'facebook_last_name',
    'facebook_email',
    'facebook_picture',
    'facebook_gender',
    'facebook_user_friends'
];

// Remove Facebook fields
foreach ($facebookFields as $field) {
    $alterTable = "ALTER TABLE members DROP COLUMN $field";
    mysqli_query($conn, $alterTable);
}

// Update user profile fields
$updateProfile = "UPDATE members SET 
    email = COALESCE(email, facebook_email),
    first_name = COALESCE(first_name, facebook_first_name),
    last_name = COALESCE(last_name, facebook_last_name),
    profile_picture = COALESCE(profile_picture, facebook_picture)
WHERE email IS NULL OR first_name IS NULL OR last_name IS NULL OR profile_picture IS NULL";
mysqli_query($conn, $updateProfile);

// Log migration
$logFile = 'migration_log.txt';
$logMessage = date('Y-m-d H:i:s') . " - Facebook fields migration completed. Backup table: $backupTable\n";
file_put_contents($logFile, $logMessage, FILE_APPEND);

echo "Migration completed successfully. Backup table created: $backupTable\n";

// Close connection
mysqli_close($conn);
?>
