<?php
require_once '../core/bootstrap.php';

$db = new Database();
echo "<h1>Setting up Finance Manager Role & Permissions</h1>";

// 1. Create Role
$role_name = 'finance_manager';
$role_desc = 'Manages finances, withdrawals, and fines.';

$db->query("SELECT id FROM roles WHERE name = :name");
$db->bind(':name', $role_name);
$existing_role = $db->single();

if (!$existing_role) {
    $db->query("INSERT INTO roles (name, description) VALUES (:name, :desc)");
    $db->bind(':name', $role_name);
    $db->bind(':desc', $role_desc);
    $db->execute();
    $role_id = $db->lastInsertId();
    echo "Created role: $role_name<br>";
} else {
    $role_id = $existing_role->id;
    echo "Role $role_name already exists (ID: $role_id)<br>";
}

// 2. Define Permissions
$permissions = [
    'fines:view',
    'fines:create',
    'fines:delete',
    'payments:view',
    'wallets:view',
    'wallets:manage',
    'withdrawals:view',
    'withdrawals:manage',
    'finance:dashboard'
];

// 3. Create Permissions and Assign to Role
foreach ($permissions as $perm_name) {
    // Check if permission exists
    $db->query("SELECT id FROM permissions WHERE name = :name");
    $db->bind(':name', $perm_name);
    $existing_perm = $db->single();

    if (!$existing_perm) {
        $db->query("INSERT INTO permissions (name, description) VALUES (:name, :desc)");
        $db->bind(':name', $perm_name);
        $db->bind(':desc', 'Permission for ' . $perm_name);
        $db->execute();
        $perm_id = $db->lastInsertId();
        echo "Created permission: $perm_name<br>";
    } else {
        $perm_id = $existing_perm->id;
    }

    // Assign to Role
    $db->query("SELECT * FROM role_permissions WHERE role_id = :rid AND permission_id = :pid");
    $db->bind(':rid', $role_id);
    $db->bind(':pid', $perm_id);
    if (!$db->single()) {
        $db->query("INSERT INTO role_permissions (role_id, permission_id) VALUES (:rid, :pid)");
        $db->bind(':rid', $role_id);
        $db->bind(':pid', $perm_id);
        $db->execute();
        echo "Assigned $perm_name to $role_name<br>";
    }
}

echo "<br><strong>Setup Complete.</strong>";
?>