<?php
include 'C:\xampp\htdocs\admission_portal\includes\db.php';

// Check if admins table exists
$check_table = $conn->query("SHOW TABLES LIKE 'admins'");
if($check_table->num_rows == 0) {
    echo "Creating admins table...\n";
    $create = $conn->query("CREATE TABLE admins (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(50) UNIQUE NOT NULL,
        email VARCHAR(100) UNIQUE NOT NULL,
        password VARCHAR(255) NOT NULL,
        role VARCHAR(20) DEFAULT 'admin',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    if($create) {
        echo "Admins table created successfully.\n";
    } else {
        echo "Error creating admins table: " . $conn->error . "\n";
    }
}

// Check if role column exists in admins table
$check = $conn->query("DESCRIBE admins");
$has_role = false;
while($row = $check->fetch_assoc()) {
    if($row['Field'] == 'role') {
        $has_role = true;
        break;
    }
}

if(!$has_role) {
    echo "Adding role column to admins table...\n";
    $alter = $conn->query("ALTER TABLE admins ADD COLUMN role VARCHAR(20) DEFAULT 'admin' AFTER email");
    if($alter) {
        echo "Role column added successfully.\n";
    } else {
        echo "Error adding role column: " . $conn->error . "\n";
    }
}

// Check if there's a system administrator
$check_sys_admin = $conn->query("SELECT * FROM admins WHERE role = 'system_admin'");
if($check_sys_admin->num_rows == 0) {
    echo "No system administrator found. Creating one...\n";
    // Update the first admin to be system administrator
    $update = $conn->query("UPDATE admins SET role = 'system_admin' WHERE role = 'admin' LIMIT 1");
    if($update && $conn->affected_rows > 0) {
        echo "First admin user promoted to system administrator.\n";
    } elseif($conn->query("SELECT COUNT(*) as count FROM admins")->fetch_assoc()['count'] == 0) {
        echo "No admin users found. Please create an admin user first.\n";
    } else {
        echo "All admins are already system administrators or no admins to update.\n";
    }
}

// Show current admin users
$result = $conn->query("SELECT id, username, email, role FROM admins");
echo "\nCurrent Admin Users:\n";
while($row = $result->fetch_assoc()) {
    echo "ID: {$row['id']}, Username: {$row['username']}, Email: {$row['email']}, Role: {$row['role']}\n";
}

$conn->close();
?>
