<?php
// Add Admin Role System
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once('includes/config.php');

echo "<h2>Setting Up Admin Role System</h2>";

if (!$con) {
    die("❌ Database connection failed: " . mysqli_connect_error());
}

echo "✅ Connected to database<br><br>";

// Step 1: Check if role column exists
echo "<h3>Step 1: Checking Database Structure</h3>";

$check_column = mysqli_query($con, "SHOW COLUMNS FROM users LIKE 'role'");

if (mysqli_num_rows($check_column) == 0) {
    echo "⚠️ 'role' column doesn't exist. Adding it...<br>";

    // Add role column
    $add_column = "ALTER TABLE users ADD COLUMN role VARCHAR(20) DEFAULT 'customer' AFTER password";

    if (mysqli_query($con, $add_column)) {
        echo "✅ Successfully added 'role' column to users table<br>";
    } else {
        echo "❌ Failed to add column: " . mysqli_error($con) . "<br>";
    }
} else {
    echo "✅ 'role' column already exists<br>";
}

echo "<br><h3>Step 2: Current Users and Their Roles</h3>";

// Show all users
$users = mysqli_query($con, "SELECT id, name, email, role FROM users");

if ($users && mysqli_num_rows($users) > 0) {
    echo "<table border='1' cellpadding='10' style='border-collapse: collapse;'>";
    echo "<tr><th>ID</th><th>Name</th><th>Email</th><th>Current Role</th><th>Actions</th></tr>";

    while ($user = mysqli_fetch_assoc($users)) {
        $role_badge = '';
        if ($user['role'] == 'admin') {
            $role_badge = "<span style='background: #f44336; color: white; padding: 3px 8px; border-radius: 3px;'>ADMIN</span>";
        } else {
            $role_badge = "<span style='background: #9e9e9e; color: white; padding: 3px 8px; border-radius: 3px;'>Customer</span>";
        }

        echo "<tr>";
        echo "<td>{$user['id']}</td>";
        echo "<td>{$user['name']}</td>";
        echo "<td>{$user['email']}</td>";
        echo "<td>{$role_badge}</td>";
        echo "<td>";

        if ($user['role'] != 'admin') {
            echo "<a href='?make_admin={$user['id']}' style='background: #4caf50; color: white; padding: 5px 10px; text-decoration: none; border-radius: 3px;'>Make Admin</a>";
        } else {
            echo "<a href='?make_customer={$user['id']}' style='background: #ff9800; color: white; padding: 5px 10px; text-decoration: none; border-radius: 3px;'>Make Customer</a>";
        }

        echo "</td>";
        echo "</tr>";
    }
    echo "</table>";
} else {
    echo "<p style='color: red;'>❌ No users found in database!</p>";
}

// Handle role changes
if (isset($_GET['make_admin'])) {
    $user_id = (int) $_GET['make_admin'];
    $stmt = $con->prepare("UPDATE users SET role = 'admin' WHERE id = ?");
    $stmt->bind_param("i", $user_id);

    if ($stmt->execute()) {
        echo "<script>alert('User has been made an admin!'); window.location.href='setup-admin-roles.php';</script>";
    }
    $stmt->close();
}

if (isset($_GET['make_customer'])) {
    $user_id = (int) $_GET['make_customer'];
    $stmt = $con->prepare("UPDATE users SET role = 'customer' WHERE id = ?");
    $stmt->bind_param("i", $user_id);

    if ($stmt->execute()) {
        echo "<script>alert('User role changed to customer!'); window.location.href='setup-admin-roles.php';</script>";
    }
    $stmt->close();
}

echo "<br><h3>Step 3: Updated Login System</h3>";
echo "<p>The login system now needs to store the user role in session.</p>";
echo "<p><strong>File to update:</strong> <code>login.php</code></p>";

echo "<div style='background: #f5f5f5; padding: 15px; border-radius: 5px; margin: 10px 0;'>";
echo "<h4>Required Code Change:</h4>";
echo "<p>In <code>login.php</code>, after checking password, add this line:</p>";
echo "<pre style='background: #263238; color: #aed581; padding: 15px; border-radius: 5px; overflow-x: auto;'>";
echo htmlspecialchars("// Set session variables
\$_SESSION['login'] = \$user['email'];
\$_SESSION['id'] = \$user['id'];
\$_SESSION['username'] = \$user['name'];
\$_SESSION['role'] = \$user['role'];  // ← ADD THIS LINE");
echo "</pre>";
echo "</div>";

echo "<br><h3>Step 4: How to Check if User is Admin</h3>";

echo "<div style='background: #e3f2fd; padding: 15px; border-radius: 5px; margin: 10px 0;'>";
echo "<h4>Method 1: Simple Check</h4>";
echo "<pre style='background: #263238; color: #aed581; padding: 15px; border-radius: 5px; overflow-x: auto;'>";
echo htmlspecialchars("<?php
if (isset(\$_SESSION['role']) && \$_SESSION['role'] == 'admin') {
    // User is admin
    echo 'Welcome Admin!';
} else {
    // User is customer
    echo 'Welcome Customer!';
}
?>");
echo "</pre>";
echo "</div>";

echo "<div style='background: #f3e5f5; padding: 15px; border-radius: 5px; margin: 10px 0;'>";
echo "<h4>Method 2: Redirect if Not Admin</h4>";
echo "<pre style='background: #263238; color: #aed581; padding: 15px; border-radius: 5px; overflow-x: auto;'>";
echo htmlspecialchars("<?php
// Protect admin-only pages
if (!isset(\$_SESSION['role']) || \$_SESSION['role'] != 'admin') {
    header('location: index.php');
    exit();
}
?>");
echo "</pre>";
echo "</div>";

echo "<div style='background: #fff3e0; padding: 15px; border-radius: 5px; margin: 10px 0;'>";
echo "<h4>Method 3: Helper Function</h4>";
echo "<pre style='background: #263238; color: #aed581; padding: 15px; border-radius: 5px; overflow-x: auto;'>";
echo htmlspecialchars("<?php
function isAdmin() {
    return isset(\$_SESSION['role']) && \$_SESSION['role'] == 'admin';
}

function isLoggedIn() {
    return isset(\$_SESSION['login']) && !empty(\$_SESSION['login']);
}

// Usage
if (isAdmin()) {
    // Show admin menu
}
?>");
echo "</pre>";
echo "</div>";

echo "<br><h3>Step 5: Display Admin Badge in Header</h3>";
echo "<div style='background: #e8f5e9; padding: 15px; border-radius: 5px; margin: 10px 0;'>";
echo "<p>Add to <code>main-header.php</code>:</p>";
echo "<pre style='background: #263238; color: #aed581; padding: 15px; border-radius: 5px; overflow-x: auto;'>";
echo htmlspecialchars("<?php if (isset(\$_SESSION['role']) && \$_SESSION['role'] == 'admin'): ?>
    <span style='background: #f44336; color: white; padding: 5px 10px; 
                 border-radius: 15px; font-size: 12px; margin-left: 10px;'>
        ADMIN
    </span>
<?php endif; ?>");
echo "</pre>";
echo "</div>";

echo "<br><div style='margin-top: 30px; padding: 20px; background: #f5f5f5; border-radius: 5px;'>";
echo "<h3>Summary:</h3>";
echo "<ul>";
echo "<li>✅ 'role' column added to users table</li>";
echo "<li>✅ You can now assign admin role to users</li>";
echo "<li>✅ Default role for new users is 'customer'</li>";
echo "<li>✅ Admin users have role = 'admin'</li>";
echo "</ul>";

$admin_count = mysqli_query($con, "SELECT COUNT(*) as count FROM users WHERE role = 'admin'");
$admin_row = mysqli_fetch_assoc($admin_count);

echo "<p><strong>Current Admins:</strong> {$admin_row['count']}</p>";
echo "</div>";

echo "<br><a href='login.php' style='padding: 10px 20px; background: #E8663D; color: white; text-decoration: none; border-radius: 5px;'>Go to Login</a>";
echo " <a href='index.php' style='padding: 10px 20px; background: #2196f3; color: white; text-decoration: none; border-radius: 5px; margin-left: 10px;'>Go to Homepage</a>";

mysqli_close($con);
?>
