<?php
include 'DB.php';
$permissions = array(
    'Add-Truck' => array(),
	'Master' => array(),
    'PDI' => array('View','Edit','Delete','Update-Status','Truck-Detail'),
	'Completed' => array('View','Edit','Delete','Truck-Data','Approved'),
	'Approved' => array('View','Edit','Delete'),
	'Selected' => array('View','Edit','Delete','Customer-Detail','Revert-Status'),
	'Truck-Details' => array('View','Edit','Delete','Add-Data'),
	'User' => array('View','Edit')
);

$user_id = $_GET['id'];
$userPermissions = array();
if (!empty($user_id)) {
    $bdd = new DB();
	$values=array();
    $userPermissionsQuery = "SELECT page, button FROM permissions WHERE user_id = $user_id";
    $userPermissionsResult = $bdd->getAll($userPermissionsQuery,$values);
    foreach ($userPermissionsResult as $row) {
        $userPermissions[$row['page']] = explode(',', $row['button']);
    }
	$bdd->disconnect();
}
$htmlContent = ''; 

foreach ($permissions as $permission => $submenus) {
    $htmlContent .= '<label>';
    $htmlContent .= '<input type="checkbox" name="main_permissions[]" value="' . $permission . '" onclick="toggleSubmenu(\'' . str_replace(' ', '-', $permission) . '_submenu\')" ';

    // Check if the permission is in the user's permissions and mark it as checked
    if (isset($userPermissions[$permission])) {
        $htmlContent .= 'checked';
    }

    $htmlContent .= '> ' . $permission . '</label><br>';

    if (isset($userPermissions[$permission])) {
        $htmlContent .= '<div style="display:block;" class="submenu" id="' . str_replace(' ', '-', $permission) . '_submenu">';
    } else {
        $htmlContent .= '<div style="display:none;" class="submenu" id="' . str_replace(' ', '-', $permission) . '_submenu">';
    }
    if (!empty($submenus)) {
        $htmlContent .= '<h5>Sub-menu for ' . $permission . ':</h5>';
    }

    // Generate sub-menu checkboxes here and mark them as checked if they exist in the user's permissions
    foreach ($submenus as $submenu) {
        $htmlContent .= '<label>';
        $htmlContent .= '<input type="checkbox" name="submenu_permissions[' . $permission . '][]" value="' . $submenu . '" ';

        if (isset($userPermissions[$permission]) && in_array($submenu, $userPermissions[$permission])) {
            $htmlContent .= 'checked';
        }

        $htmlContent .= '> ' . $submenu . '</label><br>';
    }

    if (!empty($submenus)) {
        $htmlContent .= '<br>';
        $htmlContent .= '<br>';
    }
    $htmlContent .= '</div>';
}

// Return the generated HTML content as an AJAX response
echo $htmlContent;
?>
