<?php
$uID =intval($_POST['user_id']);
$selected_users=$_POST['selected_users'];

$u = $db->userInfoByID($uID);

if(empty($u)){$error=fl(); setMessage(36,'User');}
else{
    $db->transactionStart();
    $assignd_users= $db->selectAll('user_manager','where assing_user_id='.$uID.' and isActive=1','assing_user_id,user_id,id',$general->showQuery());
    $new_assignd=[]; 
    $remove_assignd=[]; 
    if(empty($assignd_users)){
        $new_assignd= $selected_users;
    }
    else{
         $assignd_users_id=[];
        foreach($assignd_users as $su){
            $assignd_users_id[]=$su['user_id'];
            if(!in_array($su['user_id'],$selected_users)){
                $remove_assignd[]=$su['id'];
            }
        }
        
        foreach($selected_users as $su){
            if(!in_array($su,$assignd_users_id)){
                $new_assignd[]=$su;
            }
        } 
        
    }




    if(!empty($new_assignd)){  
        foreach($new_assignd as $u){
            $data = [
                'user_id'       => $u,
                'assing_user_id'=> $uID,
                'assing_time'   => TIME,
                'assing_by'     => USER_ID,   
            ];

            $insert=$db->insert('user_manager',$data,true);

            if(!$insert){$error=fl(); setMessage(66);}
        }
    }
    if(!empty($remove_assignd)){  
        foreach($remove_assignd as $id){
            $data = [  
                'release_time'   => TIME,
                'release_by'     => USER_ID,   
                'isActive'       => 0,   
            ];
            $where=['id'=>$id];

            $update=$db->update('user_manager',$data,$where);

            if(!$update){$error=fl(); setMessage(66);}
        }
    }
    

    $ac=false;
    if(!isset($error)){
        $ac=true;
        $jArray['status'] = 1;
        setMessage(2,'User successfully assigned.');
    }
    $db->transactionStop($ac);
}
?>
