<?php
/**
 * modules/rolepermissions/list_rolepermissions.php
 * The HRBAC Permission Matrix Engine
 */

// 1. STRICT SECURITY KICK-OUT
$p = $GLOBALS['my_privs'] ?? ['can_view' => 0, 'can_add' => 0, 'can_edit' => 0, 'can_del' => 0];
if (in_array(1, $_SESSION['all_role_ids'] ?? [])) {
    $p = ['can_view' => 1, 'can_add' => 1, 'can_edit' => 1, 'can_del' => 1];
}

// Permissions module requires supreme access (Treating this as an Edit action)
if ($p['can_edit'] == 0) {
    header("Location: index.php?s=" . encrypt_url('mod=dashboard&page=list') . "&status=access_denied");
    exit;
}

// 2. HRBAC GATEKEEPER: Filter roles so users can only manage tiers below them
$my_priority = $_SESSION['role_priority'] ?? 99;
$allowed_priority_clause = ($my_priority == 1) ? ">= 1" : "> $my_priority";

// 3. PRG HANDLER: Role Selector Redirect
// Translates the dropdown POST into a secure encrypted GET URL
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action_select_role'])) {
    $r_id = (int)$_POST['role_id'];
    header("Location: index.php?s=" . encrypt_url("mod=rolepermissions&page=list_rolepermissions&role_id=$r_id"));
    exit;
}

// 4. PRG HANDLER: Save Permissions Matrix
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action_save_matrix'])) {
    $role_id = (int)$_POST['selected_role_id'];
    $perms   = $_POST['perm'] ?? []; // Array of [menu_id => [v=>1, a=>1, e=>1, d=>1]]
    $assigner = (int)$_SESSION['user_id'];

    // Security Check: Verify they aren't trying to hack the hidden input to modify a higher tier role
    $check_role = $db->query("SELECT ROLE_PRIORITY FROM TBL_ROLES WHERE ROLE_ID = $role_id");
    $target_role = mysqli_fetch_assoc($check_role);
    if ($my_priority != 1 && $target_role['ROLE_PRIORITY'] <= $my_priority) {
        header("Location: index.php?s=" . encrypt_url('mod=rolepermissions&page=list_rolepermissions') . "&status=access_denied");
        exit;
    }

    // A. Wipe existing permissions for this role cleanly
    $db->query("DELETE FROM TBL_ROLE_PERMISSIONS WHERE ROLE_ID = $role_id");

    // B. Insert the new checkbox values
    foreach ($perms as $menu_id => $actions) {
        $v = isset($actions['v']) ? 1 : 0;
        $a = isset($actions['a']) ? 1 : 0;
        $e = isset($actions['e']) ? 1 : 0;
        $d = isset($actions['d']) ? 1 : 0;
        
        // Only insert if at least one checkbox is ticked
        if ($v || $a || $e || $d) {
            $sql = "INSERT INTO TBL_ROLE_PERMISSIONS (ROLE_ID, MENU_ID, CAN_VIEW, CAN_ADD, CAN_EDIT, CAN_DEL, ASSIGNED_BY) 
                    VALUES ($role_id, $menu_id, $v, $a, $e, $d, $assigner)";
            $db->query($sql);
        }
    }

    header("Location: index.php?s=" . encrypt_url("mod=rolepermissions&page=list_rolepermissions&role_id=$role_id") . "&status=updated");
    exit;
}

// 5. FETCH DATA FOR UI
// Replace with this:
$active_role_id = isset($GLOBALS['request_data']['role_id']) ? (int)$GLOBALS['request_data']['role_id'] : 0;
//echo $active_role_id;die();

// Fetch manageable roles for the dropdown
$roles_sql = "SELECT ROLE_ID, ROLE_NAME FROM TBL_ROLES WHERE STATUS = 'ACTIVE' AND ROLE_PRIORITY $allowed_priority_clause ORDER BY ROLE_PRIORITY ASC";
$roles_result = $db->query($roles_sql);

// If a role is selected, fetch the full menu architecture and its current permissions
$menu_matrix = [];
if ($active_role_id > 0) {
    $menu_sql = "SELECT m.MAIN_MENU_ID, m.MENU_NAME as PARENT_NAME, m.MENU_ICON, 
                        c.CHILD_MENU_ID, c.MENU_NAME as CHILD_NAME, c.MENU_URL,
                        p.CAN_VIEW, p.CAN_ADD, p.CAN_EDIT, p.CAN_DEL
                 FROM TBL_MAIN_MENU m
                 JOIN TBL_CHILD_MENU c ON m.MAIN_MENU_ID = c.MAIN_MENU_ID
                 LEFT JOIN TBL_ROLE_PERMISSIONS p ON c.CHILD_MENU_ID = p.MENU_ID AND p.ROLE_ID = $active_role_id
                 WHERE m.STATUS = 'ACTIVE' AND c.STATUS = 'ACTIVE'
                 ORDER BY m.SORT_ORDER ASC, c.SORT_ORDER ASC"; 
    
    $matrix_result = $db->query($menu_sql);
    while ($row = mysqli_fetch_assoc($matrix_result)) {
        $menu_matrix[$row['PARENT_NAME']][] = $row;
    }
}
?>

<style>
    /* Custom Orange Checkboxes for the Matrix */
    .matrix-checkbox {
        width: 20px;
        height: 20px;
        cursor: pointer;
        accent-color: var(--slcmc-orange);
    }
    .table-matrix th { background-color: var(--slcmc-black); color: white; text-align: center; }
    .table-matrix td.center { text-align: center; vertical-align: middle; }
    .parent-row { background-color: #f4f6f9; font-weight: bold; }
</style>

<section class="content-header">
    <div class="container-fluid">
        <h1 class="font-weight-bold text-primary"><i class="fas fa-key mr-2"></i>Access Control Matrix</h1>
    </div>
</section>

<section class="content">
    <div class="container-fluid">
        
        <!-- STEP 1: ROLE SELECTOR -->
        <div class="card card-outline card-primary shadow-sm mb-4">
            <div class="card-body">
                <form action="" method="POST" class="form-inline">
                    <input type="hidden" name="action_select_role" value="1">
                    <label class="mr-3 font-weight-bold">Select Role to Configure:</label>
                    <select name="role_id" class="form-control mr-3" style="width: 300px;" required onchange="this.form.submit()">
                        <option value="">-- Choose Role --</option>
                        <?php while($r = mysqli_fetch_assoc($roles_result)): ?>
                            <option value="<?php echo $r['ROLE_ID']; ?>" <?php echo ($active_role_id == $r['ROLE_ID']) ? 'selected' : ''; ?>>
                                <?php echo $r['ROLE_NAME']; ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                    <?php if($active_role_id == 0): ?>
                        <span class="text-muted"><i class="fas fa-arrow-left mr-1"></i> Select a role to load the matrix.</span>
                    <?php endif; ?>
                </form>
            </div>
        </div>

        <!-- STEP 2: THE MATRIX GRID (Only visible if a role is selected) -->
        <?php if ($active_role_id > 0): ?>
        <form action="" method="POST">
            <input type="hidden" name="action_save_matrix" value="1">
            <input type="hidden" name="selected_role_id" value="<?php echo $active_role_id; ?>">

            <div class="card shadow-sm">
                <div class="card-body p-0">
                    <table class="table table-bordered table-hover table-matrix mb-0">
                        <thead>
                            <tr>
                                <th style="text-align: left; padding-left: 20px;">System Module / Page</th>
                                <th width="12%">View (Read)</th>
                                <th width="12%">Add (Create)</th>
                                <th width="12%">Edit (Update)</th>
                                <th width="12%">Delete (Drop)</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($menu_matrix as $parent => $children): ?>
                                <!-- Parent Category Header -->
                                <tr class="parent-row text-primary">
                                    <td colspan="5" style="padding-left: 20px;">
                                        <i class="<?php echo $children[0]['MENU_ICON']; ?> mr-2"></i> 
                                        <?php echo strtoupper($parent); ?>
                                    </td>
                                </tr>
                                
                                <!-- Child Pages -->
                                <?php foreach ($children as $child): 
                                    $cid = $child['CHILD_MENU_ID'];
                                ?>
                                <tr>
                                    <td style="padding-left: 40px;">
                                        <i class="far fa-circle text-muted mr-2" style="font-size: 10px;"></i>
                                        <?php echo $child['CHILD_NAME']; ?>
                                        <br><small class="text-muted ml-4">Route: <?php echo $child['MENU_URL']; ?></small>
                                    </td>
                                    
                                    <!-- The Checkboxes (Using Arrays) -->
                                    <td class="center bg-light">
                                        <input type="checkbox" name="perm[<?php echo $cid; ?>][v]" class="matrix-checkbox" <?php echo ($child['CAN_VIEW'] == 1) ? 'checked' : ''; ?>>
                                    </td>
                                    <td class="center">
                                        <input type="checkbox" name="perm[<?php echo $cid; ?>][a]" class="matrix-checkbox" <?php echo ($child['CAN_ADD'] == 1) ? 'checked' : ''; ?>>
                                    </td>
                                    <td class="center bg-light">
                                        <input type="checkbox" name="perm[<?php echo $cid; ?>][e]" class="matrix-checkbox" <?php echo ($child['CAN_EDIT'] == 1) ? 'checked' : ''; ?>>
                                    </td>
                                    <td class="center">
                                        <input type="checkbox" name="perm[<?php echo $cid; ?>][d]" class="matrix-checkbox text-danger" <?php echo ($child['CAN_DEL'] == 1) ? 'checked' : ''; ?>>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <div class="card-footer bg-white text-right p-3">
                    <button type="submit" class="btn btn-primary px-5 font-weight-bold shadow-lg">
                        <i class="fas fa-shield-alt mr-2"></i> ENFORCE PERMISSIONS
                    </button>
                </div>
            </div>
        </form>
        <?php endif; ?>

    </div>
</section>