<?php
defined(page_security_key) or exit;

$page = 'user';
//Check if allowed
if (isAllowed($page,$_SESSION['profile'],$_SESSION['permission'],'R') === 0){
    header('location: index.php');
    exit;
}
//PAGE Security
$update_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'U');
$delete_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'D');
$create_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'C');

// Default input product values
$user = [
    'id' => '',
    'username' => '',
    'email' => '',
    'partnerhierarchy' => '',
    'view' => 3,
    'service' => 0,
    'settings' => '',
    'userkey' => 1,
    'created' => '',
    'createdby' => '',
    'updated' => '',
    'updatedby' => '',
    'lastlogin' => '',
    'language' => 'US',
    'login_count' => 0
];

$user_ID = $_GET['id'] ?? '';

if ($user_ID !=''){
    $url = 'index.php?page=users&id='.$user_ID.'';
} else {
    $url = 'index.php?page=users';
}

if (isset($_GET['id'])) {
    // ID param exists, edit an existing product
    //CALL TO API
    $api_url = '/v1/users/id='.$user_ID;
    $responses = ioServer($api_url,'');
    //Decode Payload
    if (!empty($responses)){$responses = decode_payload($responses);}else{$responses = null;}
    
    $user = json_decode(json_encode($responses[0]), true);

    if ($update_allowed === 1){
        if (isset($_POST['submit'])) {
           
            //GET ALL POST DATA
            $data = json_encode($_POST, JSON_UNESCAPED_UNICODE);
            //Secure data
            $payload = generate_payload($data);
            //API call
            $responses = ioServer('/v1/users', $payload);
            if ($responses === 'NOK'){

            } else {
            header('Location: index.php?page=users&success_msg=2');
            exit;
            }
        }
    }

    if ($update_allowed === 1){
        if (isset($_POST['reset'])) {
           
            //GET ALL POST DATA
            $data = json_encode($_POST, JSON_UNESCAPED_UNICODE);
            //Secure data
            $payload = generate_payload($data);
            //API call
            $responses = ioServer('/v1/users', $payload);
            if ($responses === 'NOK'){

            } else {
            header('Location: index.php?page=users&success_msg=2');
            exit;
            }
        }
    }

    if ($update_allowed === 1){
        if (isset($_POST['unblock'])) {
            //UNSET THE SUMBIT FROM POST
            unset($_POST['unblock']);
            //CHANGE LOGIN COUNT TO 0
            $_POST['login_count'] = '0';
            //GET ALL POST DATA
            $data = json_encode($_POST, JSON_UNESCAPED_UNICODE);
            //Secure data
            $payload = generate_payload($data);
            //API call
            $responses = ioServer('/v1/users', $payload);
            if ($responses === 'NOK'){

            } else {
            header('Location: index.php?page=users&success_msg=2');
            exit;
            }
        }
    }
    
    if ($delete_allowed === 1){
        if (isset($_POST['delete'])) {
            //GET ALL POST DATA
            $data = json_encode($_POST , JSON_UNESCAPED_UNICODE);
            //Secure data
            $payload = generate_payload($data);
            //API call
            $responses = ioServer('/v1/users', $payload);
            // Redirect and delete product
            if ($responses === 'NOK'){

            } else {
            header('Location: index.php?page=users&success_msg=3');
            exit;
            }
        }
    }
   
} else {
    // Create a new product
    if (isset($_POST['submit']) && $create_allowed === 1) {
        //GET ALL POST DATA
        $data = json_encode($_POST, JSON_UNESCAPED_UNICODE);
        //Secure data
        $payload = generate_payload($data);
        //API call
        $responses = ioServer('/v1/users', $payload);
        $responses = decode_payload($responses);

        if ($responses === 'NOK'){
            header('Location: index.php?page=user&success_msg=0');
       
        } elseif ($responses == 1){
            header('Location: index.php?page=user&success_msg=0');
        }
        else {
        header('Location: index.php?page=users&success_msg=1');
        exit;
        }
    }
}
//EMPTY VIEW
$view = '';

// Handle success messages
if (isset($_GET['success_msg'])) {
    if ($_GET['success_msg'] == 0) {
        $success_msg = $error_msg_0;
    }
}

template_header('User', 'user', 'manage');

if (isset($success_msg)){
    $view .= ' <div class="msg error">
                    <i class="fas fa-check-circle"></i>
                    <p>'.$success_msg.'</p>
                    <i class="fas fa-times"></i>
                </div>';
}

$view .='
<form action="" method="post">
    <div class="content-title responsive-flex-wrap responsive-pad-bot-3">
        <h2 class="responsive-width-100">'.$user_h2.': '.$user['username'].' '.(($user['login_count'] > 4)? '<span class="status disabled">'.$User_block:(($user['userkey'] &&  $user['userkey'] !='')? '<span class="status enabled">'.$enabled:'<span class="status">'.$disabled)).'</h2>
        <a href="index.php?page=users" class="btn alt mar-right-2">'.$button_cancel.'</a>
';

if ($delete_allowed === 1){
    $view .= '<input type="submit" name="delete" value="Delete" class="btn red mar-right-2" onclick="return confirm(\'Are you sure you want to delete this user?\')">';
}
if ($update_allowed === 1){
    $view .= '<input type="submit" name="submit" value="Save" class="btn">';
}
   
$view .= '</div>';

$view .= '<div class="tabs">
            <a href="#" class="active">'.$tab1 .'</a>
            <a href="#">'.$tab2.'</a>
            <a href="#">'.$tab3.'</a>
            '.(($update_allowed === 1 && $user_ID !='')? '<a href="#">'.$general_actions.'</a>':"").' 
        </div>
    ';

//Define Service and User enabled
$view .= '<div class="content-block tab-content active">
            <div class="form responsive-width-100">
                <label for="userkey">Active</label>
                <select id="userkey" name="userkey">
                    <option value="1" '.(($user['userkey']==1 || $user['userkey'] !='' )?' selected':'').'>'.$enabled .'</option>
                    <option value="0" '.(($user['userkey']==0 || $user['userkey'] =='' )?' selected':'').'>'.$disabled .'</option>
                </select>
                <label for="username">'.$User_username.'</label>
                <input id="name" type="text" name="username" placeholder="'.$User_username.'" value="'.$user['username'].'" pattern="^\S+$" required">
                <label for="username">'.$User_email.'</label>
                <input id="name" type="email" name="email" placeholder="'.$User_email.'" value="'.$user['email'].'" required">
                <label for="view">'.$User_permission.'</label>
                <select id="view" name="view" required>
                    <option value="3" '.($user['view']==3?' selected':'').'>'.$permission3.'</option>
                    <option value="2" '.($user['view']==2?' selected':'').'>'.$permission2.'</option>
                    <option value="1" '.($user['view']==1?' selected':'').'>'.$permission1.'</option>
    ';
//ADD PERMISSION SET BASED ON USER PERMISSION ADMIN OR ADMIN+
    if ($_SESSION['permission'] == 3){
        $view .= '  <option value="4" '.($user['view']==4?' selected':'').'>'.$permission4.'</option>';
    }
    if ($_SESSION['permission'] == 4){
        $view .= '  <option value="4" '.($user['view']==4?' selected':'').'>'.$permission4.'</option>
                    <option value="5" '.($user['view']==5?' selected':'').'>'.$permission5.'</option>';
    } 

$view .= '       </select>
                <label for="profile">'.$User_profile.'</label>
        ';
    //Show profiles for AMIN         
    if ($_SESSION['permission'] == 3 || $_SESSION['permission'] == 4){  
        $view .='<select id="settings" name="settings">      
                    <option value="" '.($user['settings']== ''?' selected':'').'></option>';

                foreach ($all_profiles as $profile) {
                    $view .='<option value="'.$profile.'" '.($user['settings']== $profile?' selected':'').'>'.$profile.'</option>';
                }
                    
         $view .='</select>';

        } else {
            //CHECK IF USER HAS A SPECIFIC PROFILE ASSIGNED
            if (isset($_SESSION['profile_name']) && $_SESSION['profile_name'] !=''){
                $view .='  <input id="name" type="text" name="settings" placeholder="settings" value="'.$_SESSION['profile_name'].'" readonly>';

            } else {
                $view .='  <input id="name" type="text" name="" placeholder="settings" value="'.$user['settings'].'" readonly>
                ';
            }
        }

$view .='       <label for="service">'.$User_service.'</label>
                <select id="service" name="service">
                    <option value="1" '.(($user['service']==1 || $user['service'] !='')?' selected':'').'>'.$enabled .'</option>
                    <option value="0" '.(($user['service']==0 || $user['service'] =='')?' selected':'').'>'.$disabled .'</option>
                </select>
                <label for="service">'.$User_language.'</label>
                <select id="language" name="language">
                    <option value="" '.(($user['language'] =='')?' selected':'').'></option>';
                foreach ($supportedLanguages as $language){
                    $view .='<option value="'.$language.'" '.(($user['language']==$language)?' selected':'').'>'.$language.'</option>';
                }   
$view .='       </select>
                <input type="hidden" name="id" value="'.$user_ID.'">
                <input type="hidden" name="old_view" value="'.$user['view'].'">  
                
        ';

$view .= '</div>
        </div>';

//GET PARTNERDATA
$partner_data = json_decode($user['partnerhierarchy'])?? json_decode($_SESSION['partnerhierarchy']) ;
//BUID UP DROPDOWNS
$salesid_dropdown = listPartner('salesid',$_SESSION['permission'],$partner_data->salesid,'');
$soldto_dropdown = listPartner('soldto',$_SESSION['permission'],$partner_data->soldto,'');
$shipto_dropdown = listPartner('shipto',$_SESSION['permission'],$partner_data->shipto,'');
$location_dropdown = listPartner('location',$_SESSION['permission'],$partner_data->location,'');

//DISPLAY
$view .= '<div class="content-block tab-content">
            <div class="form responsive-width-100">
';
if ($_SESSION['permission'] == 3 || $_SESSION['permission'] == 4){
    $view .= '<label for="status">'.$general_salesid.'</label>';
    $view .= $salesid_dropdown;
    $view .= '<label for="status">'.$general_soldto.'</label>';
    $view .= $soldto_dropdown;
}
$view .= '<label for="status">'.$general_shipto.'</label>';
$view .= $shipto_dropdown;
$view .= '<label for="status">'.$general_location.'</label>';
$view .= $location_dropdown;
$view .= '
       </div>
</div>';


//SUPERUSERS AND ADMINS CAN RESET BLOCKED USERS
if ($_SESSION['permission'] == 3 || $_SESSION['permission'] == 4){
    $login_count = '<input id="name" type="text" name="login_count" placeholder="'.$User_pw_login_count.'" value="'.$user['login_count'].'">';
} else {
    $login_count = '<input id="name" type="text" name="" placeholder="'.$User_pw_login_count.'" value="'.$user['login_count'].'" readonly>';
}

$view .= '<div class="content-block tab-content">
        <div class="form responsive-width-100">
            <label for="">'.$general_created.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_created.'" value="'.$user['created'].'" readonly>
            <label for="">'.$User_lastlogin.'</label>
            <input id="name" type="text" name="" placeholder="'.$User_lastlogin.'" value="'.$user['lastlogin'].'" readonly>
            <label for="productcode">'.$general_updated.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_updated.'" value="'.$user['updated'].'" readonly>
            <label for="productcode">'.$general_updatedby.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_updatedby.'" value="'.$user['updatedby'].'" readonly>
            <label for="">'.$User_pw_login_count.'</label>
            '.$login_count.'
        </div>
    </div>';

if ($update_allowed === 1 && $user_ID !=''){
$view .= '<div class="content-block tab-content">
    <div class="form responsive-width-100">
        <label for="service">'.$User_pw_reset .'</label>
        <input type="submit" name="reset" value="Reset" class="btn" style="width: 15%;" onclick="return confirm(\'Are you sure you want to reset this user password?\')"> 
        <label for="service">'.$User_unblock .'</label>
        <input type="submit" name="unblock" value="'.$User_unblock.'" class="btn" style="width: 15%;" onclick="return confirm(\'Are you sure you want to unblock this user?\')"> 
    </div>
</div>';
}
$view .= '</form>';


//Output
echo $view;
template_footer()
?>