<?php
/**
 * User Setup Script
 * GHAMECC Choir Management Platform
 * 
 * This script creates initial roles and test users for the application
 */

// Include database connection
require_once 'config/database.php';

// Start with a clean output buffer
ob_start();
echo "=== GHAMECC User Setup ===\n\n";

// Function to check if a table has records
function tableHasRecords($tableName) {
    global $conn;
    $result = $conn->query("SELECT COUNT(*) as count FROM $tableName");
    $row = $result->fetch_assoc();
    return $row['count'] > 0;
}

// Function to create a role
function createRole($roleKey, $name, $level, $description) {
    global $conn;
    
    // Check if role already exists
    $stmt = $conn->prepare("SELECT id FROM roles WHERE role_key = ?");
    $stmt->bind_param("s", $roleKey);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        echo "Role '$name' already exists.\n";
        $row = $result->fetch_assoc();
        $stmt->close();
        return $row['id'];
    }
    
    // Create the role
    $stmt = $conn->prepare("INSERT INTO roles (role_key, name, level, description) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("ssis", $roleKey, $name, $level, $description);
    $stmt->execute();
    $roleId = $stmt->insert_id;
    $stmt->close();
    
    echo "Created role: $name\n";
    return $roleId;
}

// Function to create a user
function createUser($username, $password, $email, $fullName, $roleId, $createdBy = null) {
    global $conn;
    
    // Check if user already exists
    $stmt = $conn->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
    $stmt->bind_param("ss", $username, $email);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        echo "User '$username' or email '$email' already exists.\n";
        $stmt->close();
        return false;
    }
    
    // Hash the password
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
    
    // Create the user
    $stmt = $conn->prepare("INSERT INTO users (username, password, email, full_name, role_id, created_by, password_changed) 
                           VALUES (?, ?, ?, ?, ?, ?, 1)");
    $stmt->bind_param("ssssii", $username, $hashedPassword, $email, $fullName, $roleId, $createdBy);
    $stmt->execute();
    $userId = $stmt->insert_id;
    $stmt->close();
    
    echo "Created user: $username ($fullName)\n";
    return $userId;
}

// Check if we need to create roles
if (!tableHasRecords('roles')) {
    echo "Creating roles...\n";
    
    // Create roles with appropriate hierarchy levels
    $adminRoleId = createRole('admin', 'Administrator', 100, 'Full system access and configuration');
    $managerRoleId = createRole('manager', 'Manager', 80, 'Manage users and system settings');
    $pastorRoleId = createRole('pastor', 'Pastor', 70, 'Pastoral oversight and management');
    $secretaryRoleId = createRole('secretary', 'Secretary', 60, 'Secretarial duties and record keeping');
    $financialRoleId = createRole('financial', 'Financial Officer', 60, 'Financial management and record keeping');
    $memberRoleId = createRole('member', 'Choir Member', 40, 'Regular choir member access');
    $userRoleId = createRole('user', 'Basic User', 20, 'Basic system access');
    
    echo "Roles created successfully.\n\n";
} else {
    echo "Roles already exist. Skipping role creation.\n\n";
    
    // Get role IDs for user creation
    $result = $conn->query("SELECT id, role_key FROM roles");
    $roles = [];
    while ($row = $result->fetch_assoc()) {
        $roles[$row['role_key']] = $row['id'];
    }
    
    $adminRoleId = $roles['admin'] ?? null;
    $managerRoleId = $roles['manager'] ?? null;
    $pastorRoleId = $roles['pastor'] ?? null;
    $secretaryRoleId = $roles['secretary'] ?? null;
    $financialRoleId = $roles['financial'] ?? null;
    $memberRoleId = $roles['member'] ?? null;
    $userRoleId = $roles['user'] ?? null;
}

// Check if we need to create test users
if (!tableHasRecords('users')) {
    echo "Creating test users...\n";
    
    // Create admin user first
    $adminId = createUser('admin', 'admin123', 'admin@ghamecc.org', 'System Administrator', $adminRoleId);
    
    // Create other test users with admin as creator
    $managerId = createUser('manager', 'manager123', 'manager@ghamecc.org', 'Choir Manager', $managerRoleId, $adminId);
    $pastorId = createUser('pastor', 'pastor123', 'pastor@ghamecc.org', 'Church Pastor', $pastorRoleId, $adminId);
    $secretaryId = createUser('secretary', 'secretary123', 'secretary@ghamecc.org', 'Choir Secretary', $secretaryRoleId, $adminId);
    $financialId = createUser('financial', 'financial123', 'financial@ghamecc.org', 'Financial Officer', $financialRoleId, $adminId);
    $memberId = createUser('member', 'member123', 'member@ghamecc.org', 'Regular Member', $memberRoleId, $adminId);
    $userId = createUser('user', 'user123', 'user@ghamecc.org', 'Basic User', $userRoleId, $adminId);
    
    echo "Test users created successfully.\n\n";
} else {
    echo "Users already exist. Skipping test user creation.\n\n";
}

// Create permissions if needed
if (!tableHasRecords('permissions')) {
    echo "Creating permissions...\n";
    
    // Define permissions
    $permissions = [
        ['view_dashboard', 'View Dashboard', 'Can view the main dashboard'],
        ['manage_members', 'Manage Members', 'Can add, edit, and delete members'],
        ['view_members', 'View Members', 'Can view member information'],
        ['manage_events', 'Manage Events', 'Can create and manage events'],
        ['view_events', 'View Events', 'Can view event information'],
        ['manage_attendance', 'Manage Attendance', 'Can record and edit attendance'],
        ['view_attendance', 'View Attendance', 'Can view attendance records'],
        ['manage_finances', 'Manage Finances', 'Can record and manage financial records'],
        ['view_finances', 'View Finances', 'Can view financial records'],
        ['manage_reports', 'Manage Reports', 'Can create and manage reports'],
        ['view_reports', 'View Reports', 'Can view reports'],
        ['manage_users', 'Manage Users', 'Can create and manage user accounts'],
        ['manage_roles', 'Manage Roles', 'Can create and manage roles'],
        ['system_settings', 'System Settings', 'Can modify system settings']
    ];
    
    // Insert permissions
    $stmt = $conn->prepare("INSERT INTO permissions (key, name, description) VALUES (?, ?, ?)");
    foreach ($permissions as $permission) {
        $stmt->bind_param("sss", $permission[0], $permission[1], $permission[2]);
        $stmt->execute();
        echo "Created permission: {$permission[1]}\n";
    }
    $stmt->close();
    
    echo "Permissions created successfully.\n\n";
} else {
    echo "Permissions already exist. Skipping permission creation.\n\n";
}

// Display login information
echo "=== Login Information ===\n";
echo "You can now log in with the following test accounts:\n";
echo "Admin: username='admin', password='admin123'\n";
echo "Manager: username='manager', password='manager123'\n";
echo "Pastor: username='pastor', password='pastor123'\n";
echo "Secretary: username='secretary', password='secretary123'\n";
echo "Financial: username='financial', password='financial123'\n";
echo "Member: username='member', password='member123'\n";
echo "User: username='user', password='user123'\n\n";

echo "Setup completed successfully!\n";

// Output the buffer
$output = ob_get_clean();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GHAMECC User Setup</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        pre {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            white-space: pre-wrap;
        }
    </style>
</head>
<body>
    <div class="container my-5">
        <div class="row">
            <div class="col-12">
                <h1>GHAMECC User Setup</h1>
                <div class="card">
                    <div class="card-header">
                        Setup Results
                    </div>
                    <div class="card-body">
                        <pre><?php echo htmlspecialchars($output); ?></pre>
                        <a href="login.php" class="btn btn-primary">Go to Login Page</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
