<?php
/**
 * Script to clear Group 30 (Ladies Friendlies) for testing:
 * Keep only 4 test members: admin, Barry Kirk, Jo Musson, and Robert Hall
 * Remove all other users from InviteGroupUsers table for group 30
 */

include "event-server.php";

echo "<!DOCTYPE html>
<html>
<head>
    <title>Clear Group 30 for Testing</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; }
        .warning { color: orange; }
        h2 { color: #333; }
        table { border-collapse: collapse; width: 100%; margin: 20px 0; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <h2>Clearing Group 30 for Testing</h2>
    <p class='warning'>⚠️ This will remove all users from group 30 except the 4 test members.</p>";

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

try {
    // Step 1: Find the 4 test users
    echo "<h3>Step 1: Finding Test Users</h3>";
    
    $testUsers = [
        'admin' => ['name' => 'Admin LadiesFriendlies', 'memberId' => '999930'],
        'barry_kirk' => ['name' => 'KIRK, BARRY', 'memberId' => null],
        'jo_musson' => ['name' => 'MUSSON, JOSEPHINE', 'memberId' => null],
        'robert_hall' => ['name' => 'HALL, ROBERT', 'memberId' => null]
    ];
    
    $foundUserIds = [];
    
    // Find admin by memberId
    $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) {
        $adminRow = $adminResult->fetch_assoc();
        $foundUserIds['admin'] = $adminRow['id'];
        echo "<p class='info'>✅ Found admin: " . htmlspecialchars($adminRow['name']) . " (ID: " . $adminRow['id'] . ")</p>";
    } else {
        throw new Exception("Admin user with memberId 999930 not found.");
    }
    $findAdminStmt->close();
    
    // Find other users by name (case-insensitive, handle variations)
    $findUserStmt = $conn->prepare("SELECT id, name FROM Users WHERE UPPER(name) LIKE ?");
    
    foreach (['barry_kirk', 'jo_musson', 'robert_hall'] as $key) {
        $searchName = $testUsers[$key]['name'];
        // Try exact match first, then with variations
        $searchPattern = strtoupper($searchName) . '%';
        $findUserStmt->bind_param("s", $searchPattern);
        $findUserStmt->execute();
        $result = $findUserStmt->get_result();
        
        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $foundUserIds[$key] = $row['id'];
            echo "<p class='info'>✅ Found " . htmlspecialchars($key) . ": " . htmlspecialchars($row['name']) . " (ID: " . $row['id'] . ")</p>";
        } else {
            // Try alternative search - remove comma variations
            $altPattern = str_replace(',', '', strtoupper($searchName)) . '%';
            $findUserStmt->bind_param("s", $altPattern);
            $findUserStmt->execute();
            $altResult = $findUserStmt->get_result();
            
            if ($altResult->num_rows > 0) {
                $row = $altResult->fetch_assoc();
                $foundUserIds[$key] = $row['id'];
                echo "<p class='info'>✅ Found " . htmlspecialchars($key) . ": " . htmlspecialchars($row['name']) . " (ID: " . $row['id'] . ")</p>";
            } else {
                throw new Exception("User not found: " . htmlspecialchars($searchName));
            }
        }
    }
    $findUserStmt->close();
    
    if (count($foundUserIds) !== 4) {
        throw new Exception("Expected 4 users but found " . count($foundUserIds));
    }
    
    // Step 2: Check current users in group 30
    echo "<h3>Step 2: Checking Current Users in Group 30</h3>";
    
    $checkUsersStmt = $conn->prepare("
        SELECT igu.id, u.name, u.memberId 
        FROM InviteGroupUsers igu 
        JOIN Users u ON igu.id = u.id 
        WHERE igu.groupNo = 30 
        ORDER BY u.name
    ");
    $checkUsersStmt->execute();
    $result = $checkUsersStmt->get_result();
    
    $currentUsers = [];
    while ($row = $result->fetch_assoc()) {
        $currentUsers[] = $row;
    }
    $checkUsersStmt->close();
    
    $totalUsers = count($currentUsers);
    echo "<p class='info'>ℹ️ Found $totalUsers users currently in group 30</p>";
    
    if ($totalUsers > 0) {
        echo "<table>";
        echo "<tr><th>ID</th><th>Name</th><th>Member ID</th><th>Status</th></tr>";
        foreach ($currentUsers as $user) {
            $isTestUser = in_array($user['id'], $foundUserIds);
            $status = $isTestUser ? "<span class='success'>✅ Keep</span>" : "<span class='error'>❌ Remove</span>";
            echo "<tr>";
            echo "<td>" . $user['id'] . "</td>";
            echo "<td>" . htmlspecialchars($user['name']) . "</td>";
            echo "<td>" . htmlspecialchars($user['memberId']) . "</td>";
            echo "<td>$status</td>";
            echo "</tr>";
        }
        echo "</table>";
    }
    
    // Step 3: Delete all users except the 4 test users
    echo "<h3>Step 3: Removing Users (Keeping Only Test Members)</h3>";
    
    $keepUserIds = array_values($foundUserIds);
    $placeholders = implode(',', array_fill(0, count($keepUserIds), '?'));
    $types = str_repeat('i', count($keepUserIds));
    
    $deleteStmt = $conn->prepare("DELETE FROM InviteGroupUsers WHERE groupNo = 30 AND id NOT IN ($placeholders)");
    
    // Bind parameters dynamically
    $params = array_merge([$types], $keepUserIds);
    $refs = [];
    foreach ($params as $key => $value) {
        $refs[$key] = &$params[$key];
    }
    call_user_func_array([$deleteStmt, 'bind_param'], $refs);
    
    if ($deleteStmt->execute()) {
        $deletedRows = $deleteStmt->affected_rows;
        echo "<p class='success'>✅ Successfully removed $deletedRows users from group 30</p>";
    } else {
        throw new Exception("Failed to delete users: " . $conn->error);
    }
    $deleteStmt->close();
    
    // Step 4: Ensure all 4 test users are in the group
    echo "<h3>Step 4: Ensuring Test Users Are in Group 30</h3>";
    
    foreach ($foundUserIds as $key => $userId) {
        $checkStmt = $conn->prepare("SELECT COUNT(*) as count FROM InviteGroupUsers WHERE groupNo = 30 AND id = ?");
        $checkStmt->bind_param("i", $userId);
        $checkStmt->execute();
        $checkResult = $checkStmt->get_result();
        $checkRow = $checkResult->fetch_assoc();
        $checkStmt->close();
        
        if ($checkRow['count'] == 0) {
            // Add user to group
            $addStmt = $conn->prepare("INSERT INTO InviteGroupUsers (id, groupNo, createdAt, updatedAt) VALUES (?, 30, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)");
            $addStmt->bind_param("i", $userId);
            if ($addStmt->execute()) {
                echo "<p class='info'>ℹ️ Added " . htmlspecialchars($key) . " (ID: $userId) to group 30</p>";
            } else {
                throw new Exception("Failed to add user to group: " . $conn->error);
            }
            $addStmt->close();
        } else {
            echo "<p class='success'>✅ " . htmlspecialchars($key) . " (ID: $userId) is already in group 30</p>";
        }
    }
    
    // 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>Removed $deletedRows users from group 30</li>";
    echo "<li>Kept 4 test members in group 30:</li>";
    echo "<ul>";
    foreach ($foundUserIds as $key => $userId) {
        $userNameStmt = $conn->prepare("SELECT name FROM Users WHERE id = ?");
        $userNameStmt->bind_param("i", $userId);
        $userNameStmt->execute();
        $userNameResult = $userNameStmt->get_result();
        $userNameRow = $userNameResult->fetch_assoc();
        $userNameStmt->close();
        echo "<li>" . htmlspecialchars($key) . ": " . htmlspecialchars($userNameRow['name']) . " (ID: $userId)</li>";
    }
    echo "</ul>";
    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>";

// List all users in group 30
$finalUsersStmt = $conn->prepare("
    SELECT u.id, u.name, u.email, u.memberId 
    FROM InviteGroupUsers igu 
    JOIN Users u ON igu.id = u.id 
    WHERE igu.groupNo = 30 
    ORDER BY u.name
");
$finalUsersStmt->execute();
$finalUsersResult = $finalUsersStmt->get_result();

$remainingCount = $finalUsersResult->num_rows;
echo "<p>Total users in group 30: <strong>$remainingCount</strong></p>";

if ($remainingCount > 0) {
    echo "<table>";
    echo "<tr><th>ID</th><th>Name</th><th>Email</th><th>Member ID</th></tr>";
    while ($row = $finalUsersResult->fetch_assoc()) {
        echo "<tr>";
        echo "<td>" . $row['id'] . "</td>";
        echo "<td>" . htmlspecialchars($row['name']) . "</td>";
        echo "<td>" . htmlspecialchars($row['email']) . "</td>";
        echo "<td>" . htmlspecialchars($row['memberId']) . "</td>";
        echo "</tr>";
    }
    echo "</table>";
} else {
    echo "<p class='warning'>⚠️ No users found in group 30</p>";
}

$finalUsersStmt->close();
$conn->close();

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

