<?php
class RolePermissionFactory {
    private $db;
    private $permissions;

    public function __construct(){
        $this->db                       =   DBConnectorFactory::loadDriver();
    }

    public function setData(array $data)    {
        $this->permissions              =   $data;
        return $this;
    }
    public function submitRolePermissions(){
        $this->db->query('START TRANSACTION');
        $role_id = $this->permissions['Role_ID'];
        $logged_id = smc_session()['user_logged_id'];
        $permissions = json_decode($this->permissions['Per']);
        if($role_id == 0){
            $this->db->prepare_Stmt('INSERT INTO
                        tbl_common_roles
                    (
                        Role_Name,
                        Logged_ID,
                        Parent_ID
                    )
                    VALUES (?,?,?)',[&$this->permissions['Role_Name'],&$logged_id,
                                       &$this->permissions['Parent_ID']]); 
            $role_id = $this->db->id();
        }else{
            if(!Session::is_smart_admin()){
                $roles = CommonFunctions::get_user_roles(false);
                $roles_array = explode(',',$roles);
                if(!in_array($role_id,$roles_array)){
                    return ['unauthorized_edit_role'];
                } 
            }
            self::deleteUnneededPermissions($role_id,$permissions);
            $this->db->prepare_Stmt('Update 
                        tbl_common_roles
                    set 
                        Role_Name = ?,
                        Parent_ID = ?
                    where
                        Role_ID = ?',[&$this->permissions['Role_Name'],&$this->permissions['Parent_ID'],
                                      &$role_id]); 
            self::clearPermissions();
        }

        foreach($permissions as $permission_id){
            if(!is_null($permission_id)){
                $this->db->prepare_Stmt('INSERT INTO
                        tbl_common_role_permission
                    (
                        Role_ID,
                        Permission_ID
                    )
                    VALUES (?,?)',[&$role_id,&$permission_id]);  
            }
        }
        $error = $this->db->error();
        if(empty($error)){
            $this->db->query('COMMIT');
        }else{
            $this->db->query('ROLLBACK'); 
        }
        return array_unique($error);
    }
    private function clearPermissions() {
        $this->db->prepare_Stmt('DELETE FROM tbl_common_role_permission 
                WHERE 
                    Role_ID    =   ?',[&$this->permissions['Role_ID']]);

    }
    public function deleteUnneededPermissions($role_id,$permissions){
        $old_permissions = array();
        $role_query = $this->db->query('select Permission_ID from tbl_common_role_permission where Role_ID = "'.$role_id.'"');
        while($row = $this->db->assoc($role_query)){
            $old_permissions[] = $row['Permission_ID'];
        }
        $different_ids = array_diff($old_permissions,$permissions);
        $roles = CommonFunctions::get_user_roles(false,$role_id);
        $different_ids_string = implode(',',$different_ids);
        if(!empty($roles) && !empty($different_ids_string)){
            $this->db->prepare_Stmt("DELETE FROM tbl_common_role_permission 
                WHERE 
                    Role_ID IN ({$roles}) and Permission_ID IN ({$different_ids_string})");
        }
    }

}
