<?php
/**
 * Script to update Group 30:
 * 1. Change group name from "LadiesPink" to "LadiesFriendlies" in InviteEventGroups table
 * 2. Update admin user name from "Admin LadiesPink" to "Admin LadiesFriendlies" in Users table
 * 3. Remove all users from InviteGroupUsers table except admin 999930
 */

include "event-server.php";

echo "<!DOCTYPE html>
<html>
<head>
    <title>Update Group 30</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .success { color: green; font-weight: bold; }
        .error { color: red; font-weight: bold; }
        .info { color: blue; }
        h2 { color: #333; }
    </style>
</head>
<body>
    <h2>Updating Group 30</h2>";

// Start transaction
$conn->begin_transaction();

try {
    // Step 1: Update group name in InviteEventGroups
    echo "<p>Step 1: Updating group name from 'LadiesPink' to 'LadiesFriendlies'...</p>";
    
    $updateGroupStmt = $conn->prepare("UPDATE InviteEventGroups SET eventGroupName = ? WHERE groupNumber = 30");
    $newGroupName = "LadiesFriendlies";
    $updateGroupStmt->bind_param("s", $newGroupName);
    
    if ($updateGroupStmt->execute()) {
        $affectedRows = $updateGroupStmt->affected_rows;
        echo "<p class='success'>✅ Successfully updated group name to 'LadiesFriendlies' (affected rows: $affectedRows)</p>";
    } else {
        throw new Exception("Failed to update group name: " . $conn->error);
    }
    $updateGroupStmt->close();
    
    // Step 2: Find admin user by memberId
    echo "<p>Step 2: Finding admin user (memberId: 999930)...</p>";
    
    $adminMemberId = "999930";
    $findAdminStmt = $conn->prepare("SELECT id, name FROM Users WHERE memberId = ?");
    $findAdminStmt->bind_param("s", $adminMemberId);
    $findAdminStmt->execute();
    $adminResult = $findAdminStmt->get_result();
    
    if ($adminResult->num_rows == 0) {
        throw new Exception("Admin user with memberId 999930 not found. Please create admin user first.");
    }
    
    $adminRow = $adminResult->fetch_assoc();
    $adminUserId = $adminRow['id'];
    $currentAdminName = $adminRow['name'];
    echo "<p class='info'>ℹ️ Found admin user (ID: $adminUserId, Current Name: " . htmlspecialchars($currentAdminName) . ")</p>";
    $findAdminStmt->close();
    
    // Step 3: Update admin user name
    echo "<p>Step 3: Updating admin user name to 'Admin LadiesFriendlies'...</p>";
    
    $newAdminName = "Admin LadiesFriendlies";
    $updateAdminStmt = $conn->prepare("UPDATE Users SET name = ? WHERE id = ?");
    $updateAdminStmt->bind_param("si", $newAdminName, $adminUserId);
    
    if ($updateAdminStmt->execute()) {
        $affectedRows = $updateAdminStmt->affected_rows;
        echo "<p class='success'>✅ Successfully updated admin user name to 'Admin LadiesFriendlies' (affected rows: $affectedRows)</p>";
    } else {
        throw new Exception("Failed to update admin user name: " . $conn->error);
    }
    $updateAdminStmt->close();
    
    // Step 4: Check current users in the group
    echo "<p>Step 4: Checking current users in group 30...</p>";
    
    $checkUsersStmt = $conn->prepare("SELECT id FROM InviteGroupUsers WHERE groupNo = 30");
    $checkUsersStmt->execute();
    $result = $checkUsersStmt->get_result();
    $userIds = [];
    while ($row = $result->fetch_assoc()) {
        $userIds[] = $row['id'];
    }
    $checkUsersStmt->close();
    
    $totalUsers = count($userIds);
    echo "<p class='info'>ℹ️ Found $totalUsers users in group 30</p>";
    
    // Step 5: Delete all users except admin
    echo "<p>Step 5: Removing users except admin (ID: $adminUserId)...</p>";
    
    $deleteStmt = $conn->prepare("DELETE FROM InviteGroupUsers WHERE groupNo = 30 AND id != ?");
    $deleteStmt->bind_param("i", $adminUserId);
    
    if ($deleteStmt->execute()) {
        $deletedRows = $deleteStmt->affected_rows;
        echo "<p class='success'>✅ Successfully removed $deletedRows users from group 30</p>";
        
        // Verify admin is still in the group
        $verifyStmt = $conn->prepare("SELECT COUNT(*) as count FROM InviteGroupUsers WHERE groupNo = 30 AND id = ?");
        $verifyStmt->bind_param("i", $adminUserId);
        $verifyStmt->execute();
        $verifyResult = $verifyStmt->get_result();
        $verifyRow = $verifyResult->fetch_assoc();
        $verifyStmt->close();
        
        if ($verifyRow['count'] > 0) {
            echo "<p class='success'>✅ Verified: Admin (ID: $adminUserId) is still in group 30</p>";
        } else {
            // If admin is not in group, add them
            echo "<p class='info'>ℹ️ Admin not found in group 30, adding admin to group...</p>";
            $addAdminStmt = $conn->prepare("INSERT INTO InviteGroupUsers (id, groupNo) VALUES (?, 30)");
            $addAdminStmt->bind_param("i", $adminUserId);
            if ($addAdminStmt->execute()) {
                echo "<p class='success'>✅ Admin added to group 30</p>";
            } else {
                throw new Exception("Failed to add admin to group: " . $conn->error);
            }
            $addAdminStmt->close();
        }
    } else {
        throw new Exception("Failed to delete users: " . $conn->error);
    }
    $deleteStmt->close();
    
    // Commit transaction
    $conn->commit();
    echo "<hr>";
    echo "<h3 class='success'>✅ All updates completed successfully!</h3>";
    echo "<p><strong>Summary:</strong></p>";
    echo "<ul>";
    echo "<li>Group 30 name changed from 'LadiesPink' to 'LadiesFriendlies'</li>";
    echo "<li>Admin user name changed to 'Admin LadiesFriendlies'</li>";
    echo "<li>Removed $deletedRows users from group 30</li>";
    echo "<li>Admin (ID: $adminUserId, memberId: $adminMemberId) preserved in group 30</li>";
    echo "</ul>";
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    echo "<p class='error'>❌ Error: " . htmlspecialchars($e->getMessage()) . "</p>";
    echo "<p class='error'>Transaction rolled back. No changes were made.</p>";
}

// Show final state
echo "<hr>";
echo "<h3>Final State Verification</h3>";

// Check group name
$finalGroupStmt = $conn->prepare("SELECT eventGroupName FROM InviteEventGroups WHERE groupNumber = 30");
$finalGroupStmt->execute();
$finalGroupResult = $finalGroupStmt->get_result();
if ($finalGroupRow = $finalGroupResult->fetch_assoc()) {
    echo "<p>Group name: <strong>" . htmlspecialchars($finalGroupRow['eventGroupName']) . "</strong></p>";
}
$finalGroupStmt->close();

// Check admin user name
$finalAdminStmt = $conn->prepare("SELECT id, name, memberId FROM Users WHERE memberId = '999930'");
$finalAdminStmt->execute();
$finalAdminResult = $finalAdminStmt->get_result();
if ($finalAdminRow = $finalAdminResult->fetch_assoc()) {
    echo "<p>Admin user: <strong>" . htmlspecialchars($finalAdminRow['name']) . "</strong> (ID: " . $finalAdminRow['id'] . ", memberId: " . $finalAdminRow['memberId'] . ")</p>";
}
$finalAdminStmt->close();

// Check remaining users
$finalUsersStmt = $conn->prepare("SELECT id FROM InviteGroupUsers WHERE groupNo = 30 ORDER BY id");
$finalUsersStmt->execute();
$finalUsersResult = $finalUsersStmt->get_result();
$remainingUsers = [];
while ($row = $finalUsersResult->fetch_assoc()) {
    $remainingUsers[] = $row['id'];
}
$finalUsersStmt->close();

echo "<p>Remaining users in group 30: " . count($remainingUsers) . "</p>";
if (count($remainingUsers) > 0) {
    echo "<ul>";
    foreach ($remainingUsers as $userId) {
        // Get user name for display
        $userNameStmt = $conn->prepare("SELECT name, memberId FROM Users WHERE id = ?");
        $userNameStmt->bind_param("i", $userId);
        $userNameStmt->execute();
        $userNameResult = $userNameStmt->get_result();
        if ($userNameRow = $userNameResult->fetch_assoc()) {
            echo "<li>User ID: $userId - " . htmlspecialchars($userNameRow['name']) . " (memberId: " . $userNameRow['memberId'] . ")</li>";
        } else {
            echo "<li>User ID: $userId</li>";
        }
        $userNameStmt->close();
    }
    echo "</ul>";
}

$conn->close();

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


