<?php
session_start();
require_once '../utils/errorhandler.php';
require_once '../utils/response.php';
require_once '../model/dbclass.php';
require_once '../model/model.php';
require_once '../model/user.php';

date_default_timezone_set('Africa/Lagos');

if($_SESSION["user_id"] == null || $_SESSION["user_id"] === ""){
    $response = array("status" => false,"code" => 204,"message" => "Session expired. Proceed to login");
    exit(json_encode($response));
}
$user = new User();

$resp = array("status" => false,"code" => "204","message"=>"");
$email = filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) ? $_POST["email"] : "-";
//exit("email " . $_SESSION["wuseremail"] . " role: " . $_SESSION["role"]);
if($_SESSION["role"] !== "SUPERADMIN"){
    exit(json_encode(array("status" => false,"code" => 204,"message" => "Operation is not allowed")));
}
if( $email === "-"){
    $resp["message"] = "user is invalid";
    $user->addUserActivity($_SESSION["email"], "Attempt to update access controls for: $email  at " . date("Y-m-d H:i:s"), date("Y-m-d H:i:s"), "ACCESS CONTROL");
    exit(json_encode($resp));
}

$permissions = ((isset($_POST["permissions"]) && $_POST["permissions"] !== "") ? $_POST["permissions"] : "-");
$role = ((isset($_POST["role"]) && $_POST["role"] !== "") ? $_POST["role"] : "STAFF");
//$platform = ((isset($_POST["platform"]) && $_POST["platform"] !== "") ? $_POST["platform"] : "MOBILE");
$resuser = $user->getUserInfo("email = '" . $email . "'");

if($role === "SUPERADMIN"){
    //exit(json_encode(array("status" => false,"code" => 204,"message" => "Operation is not allowed")));
}

if($resuser){
    if($permissions !== "-"){
        //$resultupdate = $user->updateUserDetails("platform='$platform',role='" . $role . "',permissions='" . $permissions . "'", $resuser["id"]);
        $resultupdate = $user->updateUserDetails("role='" . $role . "',permissions='" . $permissions . "'", $resuser["id"]);
        if($resultupdate){
            $resp["message"] = "Successful";
            $resp["status"] = true;
            $resp["code"] = 200;
            $user->addUserActivity($_SESSION["email"], "Access controls for: $email updated  at " . date("Y-m-d H:i:s"), date("Y-m-d H:i:s"), "ACCESS CONTROL");
            exit(json_encode($resp));
        }
    }else{
        $resp["message"] = "Bad permission data";
        exit(json_encode($resp));
    }
}else{
    $resp["message"] = "We could not find this user";
    exit(json_encode($resp));
}
    

?>