<?php
$host = "localhost";
$user = "root";
$password = "";
$dbname = "admission_system";

$conn = new mysqli($host, $user, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "Force fixing admin@uol.edu.pk role issue...\n\n";

$email = "admin@uol.edu.pk";

// First, let's check the table structure
echo "=== Checking Table Structure ===\n";
$structure = $conn->query("DESCRIBE users");
while($row = $structure->fetch_assoc()) {
    echo "Field: {$row['Field']}, Type: {$row['Type']}, Null: {$row['Null']}, Key: {$row['Key']}\n";
}

// Check current data
echo "\n=== Current User Data ===\n";
$check = $conn->query("SELECT * FROM users WHERE email = '$email'");
if($check->num_rows > 0) {
    $row = $check->fetch_assoc();
    echo "User found with ID: {$row['id']}\n";
    foreach($row as $key => $value) {
        echo "$key: '$value'\n";
    }
} else {
    echo "User not found!\n";
    exit();
}

// Delete and recreate the user with correct role
echo "\n=== Recreating User with Correct Role ===\n";
$delete_sql = "DELETE FROM users WHERE email = '$email'";
if ($conn->query($delete_sql) === TRUE) {
    echo "Old user deleted successfully\n";
    
    // Insert new user with correct data
    $password = "admin@123";
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    $insert_sql = "INSERT INTO users (full_name, email, password, role, cnic, phone) 
                   VALUES ('System Administrator', '$email', '$hashed_password', 'system_admin', '4444444444444', '44444444444')";
    
    if ($conn->query($insert_sql) === TRUE) {
        echo "New user created with system_admin role\n";
    } else {
        echo "Error creating new user: " . $conn->error . "\n";
    }
} else {
    echo "Error deleting old user: " . $conn->error . "\n";
}

// Final verification
echo "\n=== Final Verification ===\n";
$verify = $conn->query("SELECT id, email, role, full_name FROM users WHERE email = '$email'");
if($verify->num_rows > 0) {
    $row = $verify->fetch_assoc();
    echo "ID: {$row['id']}\n";
    echo "Email: {$row['email']}\n";
    echo "Role: '{$row['role']}'\n";
    echo "Full Name: {$row['full_name']}\n";
    
    // Test login query
    echo "\n=== Testing Login Query ===\n";
    $test_sql = "SELECT id, full_name, password, role FROM users WHERE email = '$email' AND role IN ('admin', 'system_admin')";
    $test_result = $conn->query($test_sql);
    echo "Results found: " . $test_result->num_rows . "\n";
    
    if ($test_result->num_rows == 1) {
        echo "SUCCESS: Login query will find this user\n";
        echo "\nLogin credentials ready:\n";
        echo "Email: admin@uol.edu.pk\n";
        echo "Password: admin@123\n";
        echo "Role: system_admin\n";
    } else {
        echo "FAILED: Login query still won't find this user\n";
    }
}

$conn->close();
?>
