<?php
session_start();
require_once 'config/database.php';
require_once 'includes/auth.php';

// Only admins can run this
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    die("Access denied. Please login as admin.");
}

$db = new Database();
$conn = $db->getConnection();

echo "<h2>Database Fix Tool</h2>";

try {
    echo "Current column structure:<br>";
    $stmt = $conn->query("DESCRIBE users");
    $columns = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($columns as $col) {
        if ($col['Field'] == 'role') {
            echo "Field: " . $col['Field'] . " | Type: " . $col['Type'] . "<br>";
        }
    }

    echo "<br>Attempting to fix 'role' column...<br>";
    $conn->exec("ALTER TABLE users MODIFY COLUMN role VARCHAR(50) NOT NULL DEFAULT 'pharmacist'");
    echo "<span style='color:green;'>SUCCESS: Column converted to VARCHAR(50).</span><br>";

    // Also update any empty roles to a default
    $count = $conn->exec("UPDATE users SET role = 'pharmacist' WHERE role = '' OR role IS NULL");
    echo "Updated $count users with empty roles to 'pharmacist'.<br>";

} catch (Exception $e) {
    echo "<span style='color:red;'>ERROR: " . $e->getMessage() . "</span><br>";
    echo "Trying alternative fix (adding to ENUM)...<br>";
    try {
        $conn->exec("ALTER TABLE users MODIFY COLUMN role ENUM('admin', 'pharmacist', 'doctor', 'nurse', 'secretary', 'pharmacy_assistant') NOT NULL DEFAULT 'pharmacist'");
        echo "<span style='color:green;'>SUCCESS: Column updated with new ENUM values.</span><br>";
    } catch (Exception $e2) {
        echo "<span style='color:red;'>FINAL ERROR: " . $e2->getMessage() . "</span><br>";
    }
}

echo "<br><a href='complete_user_management.php'>Return to User Management</a>";
?>