<?php
session_start();
include '../../db.php';
include '../helper_functions/data_request.php';
include '../../shared/functionsinc.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    if (isset($_POST['permissions'])) {

        $processedPermissions = [];

        foreach ($_POST['permissions'] as $resourceId => $actions) {

            $resourcePermissions = [
                'resource_id' => $resourceId,
                'read' => isset($actions['read']) ? 1 : 0,
                'write' => isset($actions['write']) ? 1 : 0,
                'delete' => isset($actions['delete']) ? 1 : 0,
                'deny' => isset($actions['deny']) ? 1 : 0
            ];

            $processedPermissions[] = $resourcePermissions;
        }

        // Validite the new role's permissions against the current user's permissions
        $current_user_permissions = map_user_permissions($_SESSION['current_user_permissions']);
        
        if (validate_permissions($current_user_permissions, $processedPermissions)) {

            $roleName = $_POST['roleName'];
            $createdby = $_SESSION['userid'];
            $site_id = $_POST['propList'];
            $rLayer = $_POST['layerList'];

            // Set the table the created_by id is refering to. This way admins are able to create Custom Roles
            if ($_SESSION['layer'] === 'super_admin' || $_SESSION['layer'] === 'admin' || $_SESSION['layer'] === 'dealer') {
                $creator_type = 'users';
            }else if ($_SESSION['layer'] === 'sub_dealer' || $_SESSION['layer'] === 'organization admin') {
                $creator_type = 'dealer_admins';
            }else {
                $creator_type = 'property_users';
            }

            $stmt = $pdo->prepare("INSERT INTO custom_roles (name, site_id, layer, created_by, creator_type) VALUES (:name, :site_id, :layer, :created_by, :creator_type)");
            $stmt->bindParam(':name', $roleName, PDO::PARAM_STR);
            $stmt->bindParam(':site_id', $site_id, PDO::PARAM_INT);
            $stmt->bindParam(':layer', $rLayer, PDO::PARAM_STR);
            $stmt->bindParam(':created_by', $createdby, PDO::PARAM_INT);
            $stmt->bindParam(':creator_type', $creator_type, PDO::PARAM_STR);

            $stmt->execute();

            $lastInsertIdNR = $pdo->lastInsertId();

            $insertStmt = $pdo->prepare("INSERT INTO custom_role_resources (role_id, resource_id, action_id, site_id) VALUES (:role_id, :resource_id, :action_id, :site_id)");
            
            foreach ($processedPermissions as $permission) {
                $roleId = $lastInsertIdNR;
                $resourceId = $permission['resource_id'];
                
                if ($permission['read'] == 1) {
                    $actionRead = 1;
                    $insertStmt->bindParam(':role_id', $roleId, PDO::PARAM_INT);
                    $insertStmt->bindParam(':resource_id', $resourceId, PDO::PARAM_INT);
                    $insertStmt->bindParam(':action_id', $actionRead, PDO::PARAM_INT);
                    $insertStmt->bindParam(':site_id', $site_id, PDO::PARAM_INT);
                    $insertStmt->execute();
                }
                
                if ($permission['write'] == 1) {
                    $actionWrite = 2;
                    $insertStmt->bindParam(':role_id', $roleId, PDO::PARAM_INT);
                    $insertStmt->bindParam(':resource_id', $resourceId, PDO::PARAM_INT);
                    $insertStmt->bindParam(':action_id', $actionWrite, PDO::PARAM_INT);
                    $insertStmt->bindParam(':site_id', $site_id, PDO::PARAM_INT);
                    $insertStmt->execute();
                }
                
                if ($permission['delete'] == 1) {
                    $actionDelete = 3;
                    $insertStmt->bindParam(':role_id', $roleId, PDO::PARAM_INT);
                    $insertStmt->bindParam(':resource_id', $resourceId, PDO::PARAM_INT);
                    $insertStmt->bindParam(':action_id', $actionDelete, PDO::PARAM_INT);
                    $insertStmt->bindParam(':site_id', $site_id, PDO::PARAM_INT);
                    $insertStmt->execute();
                }
                
                if ($permission['deny'] == 1) {
                    $actionDeny = 4;
                    $insertStmt->bindParam(':role_id', $roleId, PDO::PARAM_INT);
                    $insertStmt->bindParam(':resource_id', $resourceId, PDO::PARAM_INT);
                    $insertStmt->bindParam(':action_id', $actionDeny, PDO::PARAM_INT);
                    $insertStmt->bindParam(':site_id', $site_id, PDO::PARAM_INT);
                    $insertStmt->execute();
                }
            }

            header( "Location: ../../dashboard.php?tab=roles" );

        } else {
            echo "Error: The new role permissions exceed your allowed permissions.";
        }

    } else {
        echo "No permissions data submitted.";
    }

    exit();
}

function map_user_permissions($permissions) {
    $mapped_permissions = [];
    foreach ($permissions as $role) {
        foreach ($role['resources'] as $resource) {
            $resource_id = $resource['resource_id'];
            if (!isset($mapped_permissions[$resource_id])) {
                $mapped_permissions[$resource_id] = ['read' => 0, 'write' => 0, 'delete' => 0, 'deny' => 0];
            }
            // Map permissions to their highest value
            switch ($resource['action_id']) {
                case 1: $mapped_permissions[$resource_id]['read'] = 1; break;
                case 2: $mapped_permissions[$resource_id]['write'] = 1; break;
                case 3: $mapped_permissions[$resource_id]['delete'] = 1; break;
                case 4: $mapped_permissions[$resource_id]['deny'] = 1; break;
            }
        }
    }
    return $mapped_permissions;
}

function validate_permissions($current_permissions, $new_permissions) {
    foreach ($new_permissions as $permission) {
        $resource_id = $permission['resource_id'];
        if (isset($current_permissions[$resource_id])) {
            // Check each action against the current user's permissions
            if ($permission['read'] > $current_permissions[$resource_id]['read'] ||
                $permission['write'] > $current_permissions[$resource_id]['write'] ||
                $permission['delete'] > $current_permissions[$resource_id]['delete'] ||
                $permission['deny'] > $current_permissions[$resource_id]['deny']) {
                return false;
            }
        } else {
            // Not Allowed
            return false;
        }
    }
    return true;
}