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

if (isset($_SESSION['userid'])) {
    
    if (isset($_POST['getResources'])) {

        return getResources($pdo, $_SESSION['layer']);

    }
    
    if (isset($_POST['getroles'])) {

        if ($_SESSION['layer'] === 'sub_dealer' || $_SESSION['layer'] === 'organization admin') {
            $roles = getRoles($pdo, 'user');
        }else {
            $roles = getRoles($pdo, $_SESSION['layer']);
        }

        $site_IDcr = getProperty($_SESSION['userid'], $_SESSION['layer']);
        $customRolesArray = fetchCustomRolesForProperties($site_IDcr);
        
        $customRoles = [];
        foreach ($customRolesArray as $propertyRoles) {
            foreach ($propertyRoles as $role) {
                $role['is_custom'] = true;
                $customRoles[] = $role;
            }
        }
        
        $mergedRoles = array_merge($roles, $customRoles);
        
        $uniqueRoles = [];
        foreach ($mergedRoles as $role) {
            $uniqueRoles[$role['id']] = $role;
        }
        $mergedUniqueRoles = array_values($uniqueRoles);
        
        echo json_encode($mergedUniqueRoles);
        
    }

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

        if ($_POST['gettype'] === '0') {

            $rolesToOmit = ['super_admin', 'admin', 'dealer', 'sub_dealer', 'organization admin', 'property admin', 'visitor'];

        } else if ($_POST['gettype'] === '1') {

            $rolesToOmit = ['super_admin', 'admin', 'dealer', 'sub_dealer', 'organization admin', 'user', 'visitor'];

        }
    
        $roles = getRoles($pdo, $_SESSION['layer']);

        $site_IDcr = getProperty($_SESSION['userid'], $_SESSION['layer']);
        $customRolesArray = fetchCustomRolesForProperties($site_IDcr);
        
        $customRoles = [];
        foreach ($customRolesArray as $propertyRoles) {
            foreach ($propertyRoles as $role) {
                $role['is_custom'] = true;
                $customRoles[] = $role;
            }
        }

        $mergedRoles = array_merge($roles, $customRoles);

        $filteredRoles = array_filter($mergedRoles, function($role) use ($rolesToOmit) {
            return !in_array($role['name'], $rolesToOmit);
        });

        $uniqueRoles = [];
        foreach ($filteredRoles as $role) {
            $uniqueRoles[$role['id']] = $role;
        }
        $mergedUniqueRoles = array_values($uniqueRoles);

        echo json_encode($mergedUniqueRoles);
    }
    

    if (isset($_POST['getProps'])) {
        $userId = $_SESSION['userid'];
        $userLayer = $_SESSION['layer'];

        $propDatas = getProperty($userId, $userLayer);

        $propDataFull = array("current_site" => $_SESSION['property']);
        $propDatas[] = $propDataFull;

        echo json_encode($propDatas);

    }

}
