/home/mip/mip/app/Modules/Client/Repositories/Settings/Roles/RoleRepository.php
<?php

namespace QxCMS\Modules\Client\Repositories\Settings\Roles;
use Illuminate\Support\Arr;
use QxCMS\Modules\AbstractRepository;
use QxCMS\Modules\Client\Repositories\Settings\Roles\RoleRepositoryInterface;
use QxCMS\Modules\Client\Models\Settings\Roles\Role;
use QxCMS\Modules\Client\Models\Settings\Roles\Permission;
use QxCMS\Modules\Client\Models\Settings\UserLogs\UserLogs as Log;
use DB;
use File;

class RoleRepository extends AbstractRepository implements RoleRepositoryInterface
{
    protected $model;
    protected $permission;
    protected $log;

    function __construct(Role $model, Permission $permission, Log $log)
    {
        $this->model = $model;        
        $this->permission = $permission;
        $this->log = $log;
    }    
    
    function write_menu($client_id, $role_id)
    {
        $db_name = auth('client')->user()->client->database_name;
        $view_path = realpath(app_path()).'/Modules/Client/Views';
        $realpath =  $view_path."/cache/menus/".$client_id."/";
        File::makeDirectory($realpath, 0775, true, true);
        $filename = "custom_".$role_id.".blade.php";
        $contents = $this->build_menu($role_id, $db_name);
        $created = File::put($realpath.$filename, $contents); 
    }

    function build_menu($role_id = 0, $db_name)
    {
        $modules = DB::table(''.config('database.connections.qxcms.database').'.client_modules as clientModules')
            ->select('clientModules.*','ups.can_access','ups.can_delete','ups.can_update', 'ups.can_create', 'ups.can_export', 'ups.can_import', 'ups.can_print')
            ->leftJoin(env('DB_PREFIX', 'qxcms_').$db_name.'.role_permissions as ups', 'clientModules.id', '=', 'ups.menu_id')
            ->where('ups.role_id', $role_id)
            ->where('clientModules.is_parent', 1)
            ->where('clientModules.has_parent', 0)
            ->where('clientModules.parent_id', 0)
            ->where('clientModules.show_menu', "1")
            ->where('clientModules.menu_group_id', 1)            
           // ->orderBy('clientModules.parent_id', 'ASC')
            ->orderBy('clientModules.orderid', 'ASC')
            ->orderBy('clientModules.title', 'ASC')
            ->get();
        $html_out = "\t"."<ul class=\"sidebar-menu\">"."\n";
        $html_out .= "\t\t"."<li class=\"header\">MAIN NAVIGATION</li>"."\n";
        $html_out .= "\t\t"."<li id=\"appslidemenu0\">"."\n";
        $html_out .= "\t\t"."<a href=\"/".config('modules.client').'/dashboard'."\">"."\n";
        $html_out .= "\t\t"."<i class=\"fa fa-dashboard\"></i> <span>Dashboard</span>"."\n";
        $html_out .= "\t\t"."</a>"."\n";
        $html_out .= "\t\t"."</li>"."\n";
        foreach ($modules as $menu_key => $row )
        {            
            $id = $row->id;
            $title = $row->title;
            $link_type = $row->link_type;
            $page_id = $row->page_id;
            $module_name = $row->module_name;
            $url = $row->url;
            $uri = $row->uri;
            $icon = $row->icon;
            $menu_group_id = $row->menu_group_id;
            $position = $row->position;
            $target = $row->target;
            $parent_id = $row->parent_id;
            $is_parent = $row->is_parent;
            $show_menu = $row->show_menu;
            if ($show_menu && $parent_id == 0) {
                if ($is_parent == TRUE)
                {
                    if($url=='#') {
                        $html_out .= "\t\t"."<li id=\"appslidemenu".$id."\" class=\"treeview\">"."\n";
                        $html_out .= "\t\t\t"."<a href=\"#\"><i class=\"fa fa-".$icon."\"></i> <span>".$title."</span> <i class=\"fa fa-angle-left pull-right\"></i></a>"."\n";
                        $html_out .= $this->get_menu_childs($role_id, $id, $db_name);
                    } else {
                        $html_out .= "\t\t"."<li id=\"appslidemenu".$id."\">"."\n";
                        $html_out .= "\t\t\t".'<a href="/'.config('modules.client').'/'.$url.'"><i class="fa fa-'.$icon.'"></i><span>'.$title.'</a></a>'."\n";                        
                    }
                }                
                $html_out .= '</li>'."\n"; 
            }                
        }
        $html_out .= "\t\t".'</ul>' . "\n";
        return $html_out;
    }

    function get_menu_childs($role_id, $id, $db_name)
    {
        $has_subcats = FALSE;
        $html_out  = '';
        $modules = DB::table(''.config('database.connections.qxcms.database').'.client_modules as clientModules')
            ->select('clientModules.*','ups.can_access','ups.can_delete','ups.can_update', 'ups.can_create', 'ups.can_export', 'ups.can_import', 'ups.can_print')
            ->leftJoin(env('DB_PREFIX', 'qxcms_').$db_name.'.role_permissions as ups', 'clientModules.id', '=', 'ups.menu_id')
            ->where('ups.role_id', $role_id)
            ->where('clientModules.is_parent', 0)
            ->where('clientModules.has_parent', 1)
            ->where('clientModules.parent_id', $id)
            ->where('clientModules.show_menu', "1")
            ->where('clientModules.menu_group_id', 1)
            ->orderBy('clientModules.orderid', 'ASC')
            //->orderBy('clientModules.title', 'ASC')
            ->get();
        $html_out = "\t"."<ul class=\"treeview-menu\">"."\n";       
        foreach ($modules as $menu_key => $row )
        {
            $id = $row->id;
            $title = $row->title;
            $link_type = $row->link_type;
            $page_id = $row->page_id;
            $module_name = $row->module_name;
            $url = $row->url;
            $uri = $row->uri;
            $icon = $row->icon;
            $menu_group_id = $row->menu_group_id;
            $position = $row->position;
            $target = $row->target;
            $parent_id = $row->parent_id;
            $is_parent = $row->is_parent;
            $show_menu = $row->can_access;
            $has_subcats = TRUE;
            if($show_menu) {
                $html_out .= "\t\t\t".'<li id="appslidemenu'.$id.'"><a href="/'.config('modules.client').'/'.$url.'"><i class="fa fa-angle-double-right"></i>&nbsp;'.$title.'&nbsp;</a></li>';
            }
        }
        $html_out .= "\t\t".'</ul>' . "\n";
        return ($has_subcats) ? $html_out : FALSE;
    }

    function build_role_permissions($role_id = 0, $disabled = '')
    {
        $db_name = auth('client')->user()->client->database_name;
        $modules = DB::table(''.config('database.connections.qxcms.database').'.client_modules as clientModules')
            ->select('clientModules.*','ups.can_access','ups.can_delete','ups.can_update', 'ups.can_create', 'ups.can_export', 'ups.can_import', 'ups.can_print')
            ->leftJoin(DB::raw('(SELECT * FROM '.env('DB_PREFIX', 'qxcms_').$db_name.'.role_permissions where role_id = '.$role_id.' ) as ups'), 'clientModules.id', '=', 'ups.menu_id')
            ->where('clientModules.is_parent', 1)
            ->where('clientModules.has_parent', 0)
            ->where('clientModules.parent_id', 0)
            ->where('clientModules.show_menu', "1")
            ->where('clientModules.menu_group_id', 1)            
            //->orderBy('clientModules.parent_id', 'ASC')
            //->orderBy('clientModules.id', 'ASC')
            //->orderBy('clientModules.title', 'ASC')
            ->orderBy('clientModules.orderid', 'ASC')
            ->get();        
        $html_out = "<table class=\"table table-condensed table-bordered\">";
        foreach ($modules as $module_key => $row )
        {
            $id = $row->id;
            $title = $row->title;
            $link_type = $row->link_type;
            $page_id = $row->page_id;
            $module_name = $row->module_name;
            $url = $row->url;
            $uri = $row->uri;
            $icon = $row->icon;
            $menu_group_id = $row->menu_group_id;
            $position = $row->position;
            $target = $row->target;
            $parent_id = $row->parent_id;
            $is_parent = $row->is_parent;
            $show_menu = $row->show_menu;
            $has_read = $row->has_read;
            $has_create = $row->has_create;
            $has_update = $row->has_update;
            $has_delete = $row->has_delete;
            $has_export = $row->has_export;
            $has_import = $row->has_import;
            $has_print = $row->has_print;
            $can_access = $row->can_access;
            $can_create = $row->can_create;
            $can_update = $row->can_update;
            $can_delete = $row->can_delete;
            $can_export = $row->can_export;
            $can_import = $row->can_import;
            $can_print = $row->can_print;
            if($module_key == 0) {
                $html_out .= "<thead>";
                $html_out .= "<tr valign='middle'>";
                $html_out .= "<th colspan=\"3\" style=\"text-align:center;\" align=\"center\"> Module Name </th>";                
                $html_out .= "<th colspan=\"7\" style=\"text-align:center !important;\"> <b>Permissions</b> </th>";
                $html_out .= "</tr>"; 
                $html_out .= "</thead>";                    
                $html_out .= "<tbody>";
                $html_out .= "<tr>";
                $html_out .= "<td align=\"center\" colspan=\"3\"></td>";
                $html_out .= "<td align=\"center\"> <b>Activate</b> </td>";
                $html_out .= "<td align=\"center\"> <b>Create</b> </td>";
                $html_out .= "<td align=\"center\"> <b>Update</b> </td>";
                $html_out .= "<td align=\"center\"> <b>Delete</b> </td>";
                $html_out .= "<td align=\"center\"> <b>Export</b> </td>";
                $html_out .= "<td align=\"center\"> <b>Import</b> </td>";
                $html_out .= "<td align=\"center\"> <b>Print</b> </td>";
                $html_out .= "</tr>";
            }
            $html_out .= "<tr class=\"parent\">";
            if($url=='#'){
                $html_out .= "<td colspan=\"3\">&nbsp;<b><span class=\"fa fa-".$icon."\"></span>&nbsp;".$title."</b>&nbsp;&nbsp;<i class=\"fa fa-chevron-right\"></td>";                
                $html_out .= "<td align=\"center\" style=\"background-color:#fff;\">";
                $html_out .= "<label><input name=\"module[".$id."][can_access]\" value=\"1\"  class=\"sub-menu\" type=\"checkbox\" ".(($can_access) ? 'checked':'')." data-id=\"".$id."\" data-permission=\"show\" data-access-id=\"".$role_id."\" ".$disabled."></label>";
                $html_out .= "</td>";
                $html_out .= "<td align=\"center\" colspan=\"6\" style=\"background-color:#fff;\"> <b></b> </td>";
            } else {
                $html_out .= "<td colspan=\"3\">&nbsp;<b><span class=\"fa fa-".$icon."\"></span>&nbsp;".$title."</b></td>";
                $html_out .= "<td align=\"center\" style=\"background-color:#fff;\">";
                $html_out .= "<label><input name=\"module[".$id."][can_access]\" value=\"1\"  class=\"sub-menu\" type=\"checkbox\" ".(($can_access) ? 'checked':'')." data-id=\"".$id."\" data-permission=\"show\" data-access-id=\"".$role_id."\" ".$disabled."></label>";
                $html_out .= "</td>";
                $html_out .= "<td align=\"center\" style=\"background-color:#fff;\">";
                if ($has_create) {
                    $html_out .= "<label><input name=\"module[".$id."][can_create]\" value=\"1\" class=\"sub-menu\" type=\"checkbox\" ".(($can_create) ? 'checked':'')." data-id=\"".$id."\" data-permission=\"create\" data-access-id=\"".$role_id."\" ".$disabled."></label>";
                }
                $html_out .= "</td>";
                $html_out .= "<td align=\"center\" style=\"background-color:#fff;\">";
                if ($has_update) {
                   $html_out .= "<label><input name=\"module[".$id."][can_update]\" value=\"1\" class=\"sub-menu\" type=\"checkbox\" ".(($can_update) ? 'checked':'')." data-id=\"".$id."\" data-permission=\"update\" data-access-id=\"".$role_id."\" ".$disabled."></label>";
                }
                $html_out .= "</td>";
                $html_out .= "<td align=\"center\" style=\"background-color:#fff;\">";
                if ($has_delete) {
                    $html_out .= "<label><input name=\"module[".$id."][can_delete]\" value=\"1\" class=\"sub-menu\" type=\"checkbox\" ".(($can_delete) ? 'checked':'')." data-id=\"".$id."\" data-permission=\"delete\" data-access-id=\"".$role_id."\" ".$disabled."></label>";
                }
                $html_out .= "</td>";
                $html_out .= "<td align=\"center\" style=\"background-color:#fff;\">";
                if ($has_export) {
                    $html_out .= "<label><input name=\"module[".$id."][can_export]\" value=\"1\" class=\"sub-menu\" type=\"checkbox\" ".(($can_export) ? 'checked':'')." data-id=\"".$id."\" data-permission=\"export\" data-access-id=\"".$role_id."\" ".$disabled."></label>";
                }
                $html_out .= "</td>";
                $html_out .= "<td align=\"center\" style=\"background-color:#fff;\">";
                if ($has_import) {
                    $html_out .= "<label><input name=\"module[".$id."][can_import]\" value=\"1\" class=\"sub-menu\" type=\"checkbox\" ".(($can_import) ? 'checked':'')." data-id=\"".$id."\" data-permission=\"import\" data-access-id=\"".$role_id."\" ".$disabled."></label>";
                }
                $html_out .= "</td>";
                $html_out .= "<td align=\"center\" style=\"background-color:#fff;\">";
                if ($has_print) {
                    $html_out .= "<label><input name=\"module[".$id."][can_print]\" value=\"1\" class=\"sub-menu\" type=\"checkbox\" ".(($can_print) ? 'checked':'')." data-id=\"".$id."\" data-permission=\"print\" data-access-id=\"".$role_id."\" ".$disabled."></label>";
                }
                $html_out .= "</td>";                
            }            
            $html_out .= "</tr>";
            $html_out .=   $this->get_childs_role_permissions($db_name, $id, $role_id, $disabled);
        }
        $html_out .= '</table>';
        return $html_out;
    }

    function get_childs_role_permissions($db_name, $id, $role_id, $disabled)
    {
        $has_subcats = FALSE; 
        $html_out  = '';
        $modules = DB::table(''.config('database.connections.qxcms.database').'.client_modules as clientModules')
            ->select('clientModules.*','ups.can_access','ups.can_delete','ups.can_update', 'ups.can_create', 'ups.can_export', 'ups.can_import', 'ups.can_print')
            ->leftJoin(DB::raw('(SELECT * FROM '.env('DB_PREFIX', 'qxcms_').$db_name.'.role_permissions where role_id = '.$role_id.' ) as ups'), 'clientModules.id', '=', 'ups.menu_id')            
            ->where('clientModules.is_parent', 0)
            ->where('clientModules.has_parent', 1)
            ->where('clientModules.parent_id', $id)
            ->where('clientModules.show_menu', "1")
            ->where('clientModules.menu_group_id', 1)
            //->orderBy('clientModules.title', 'ASC')
            ->orderBy('clientModules.orderid', 'ASC')
            ->get();
        foreach ($modules as $module_key => $row )
        {
            $id = $row->id;
            $title = $row->title;
            $link_type = $row->link_type;
            $page_id = $row->page_id;
            $module_name = $row->module_name;
            $url = $row->url;
            $uri = $row->uri;
            $icon = $row->icon;
            $dyn_group_id = $row->menu_group_id;
            $position = $row->position;
            $target = $row->target;
            $parent_id = $row->parent_id;
            $is_parent = $row->is_parent;
            $show_menu = $row->show_menu;
            $has_read = $row->has_read;
            $has_create = $row->has_create;
            $has_update = $row->has_update;
            $has_delete = $row->has_delete;
            $has_export = $row->has_export;
            $has_import = $row->has_import;
            $has_print = $row->has_print;
            $can_access = $row->can_access;
            $can_create = $row->can_create;
            $can_update = $row->can_update;
            $can_delete = $row->can_delete;
            $can_export = $row->can_export;
            $can_import = $row->can_import;
            $can_print = $row->can_print;                    
            $has_subcats = TRUE;                    
            $html_out .= "<tr valign='top' class='child'>";
            $html_out .= "<td  colspan=\"3\" width=\"20%\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"fa fa-".$icon."\"></span>&nbsp;".$title."</td>";                    
            $html_out .= "</td>";
            $html_out .= "<td width=\"10%\" align=\"center\">";
            $html_out .= "<label><input name=\"module[".$id."][can_access]\" value=\"1\"  class=\"sub-menu\" type=\"checkbox\" ".(($can_access) ? 'checked':'')." data-id=\"".$id."\" data-permission=\"show\" data-access-id=\"".$role_id."\" ".$disabled."></label>";
            $html_out .= "</td>";
            $html_out .= "<td width=\"10%\" align=\"center\">";
            if ($has_create) {
                $html_out .= "<label><input name=\"module[".$id."][can_create]\" value=\"1\" class=\"sub-menu\" type=\"checkbox\" ".(($can_create) ? 'checked':'')." data-id=\"".$id."\" data-permission=\"create\" data-access-id=\"".$role_id."\" ".$disabled."></label>";
            }
            $html_out .= "</td>";
            $html_out .= "<td width=\"10%\" align=\"center\">";
            if ($has_update) {
                $html_out .= "<label><input name=\"module[".$id."][can_update]\" value=\"1\" class=\"sub-menu\" type=\"checkbox\" ".(($can_update) ? 'checked':'')." data-id=\"".$id."\" data-permission=\"update\" data-access-id=\"".$role_id."\" ".$disabled."></label>";
            }
            $html_out .= "</td>";
            $html_out .= "<td width=\"10%\" align=\"center\">";
            if ($has_delete) {
                $html_out .= "<label><input name=\"module[".$id."][can_delete]\" value=\"1\" class=\"sub-menu\" type=\"checkbox\" ".(($can_delete) ? 'checked':'')." data-id=\"".$id."\" data-permission=\"delete\" data-access-id=\"".$role_id."\" ".$disabled."></label>";
            }
            $html_out .= "</td>";
            $html_out .= "<td width=\"10%\" align=\"center\">";
            if ($has_export) {
                $html_out .= "<label><input name=\"module[".$id."][can_export]\" value=\"1\" class=\"sub-menu\" type=\"checkbox\" ".(($can_export) ? 'checked':'')." data-id=\"".$id."\" data-permission=\"export\" data-access-id=\"".$role_id."\" ".$disabled."></label>";
            }
            $html_out .= "</td>";
            $html_out .= "<td width=\"10%\" align=\"center\">";
            if ($has_import) {
                $html_out .= "<label><input name=\"module[".$id."][can_import]\" value=\"1\" class=\"sub-menu\" type=\"checkbox\" ".(($can_import) ? 'checked':'')." data-id=\"".$id."\" data-permission=\"import\" data-access-id=\"".$role_id."\" ".$disabled."></label>";
            }
            $html_out .= "</td>";
            $html_out .= "<td width=\"10%\" align=\"center\">";
            if ($has_print) {
                $html_out .= "<label><input name=\"module[".$id."][can_print]\" value=\"1\" class=\"sub-menu\" type=\"checkbox\" ".(($can_print) ? 'checked':'')." data-id=\"".$id."\" data-permission=\"print\" data-access-id=\"".$role_id."\" ".$disabled."></label>";
            }
            $html_out .= "</td>";
            $html_out .= '</tr>';
        }    
        return ($has_subcats) ? $html_out : FALSE;
    }

    public function getdefaultIDs()
    {
        return $this->model->getdefaultIDs();
    }

    public function makeRolePermissions(array $request, $role_id)
    {
        $modules = isset($request['module']) ? $request['module']:array();
        $this->permission->where('role_id', $role_id)->delete();
        if (count($modules) <= 0) return;
        foreach ($modules as $module_id => $module) {
            $module['role_id'] = $role_id;
            $module['module_id'] = $module_id;
            $this->permission->create($this->makeModulePermissions($module));
        }
        return $module;
    }

    public function makeModulePermissions(array $module)
    {
        return $useroles = [
            'menu_id' => $module['module_id'],
            'role_id' => $module['role_id'],
            'can_access' => (isset($module['can_access']) && !empty($module['can_access'])) ? $module['can_access']:0,
            'can_create' => (isset($module['can_create']) && !empty($module['can_create'])) ? $module['can_create']:0,
            'can_update' => (isset($module['can_update']) && !empty($module['can_update'])) ? $module['can_update']:0,
            'can_delete' => (isset($module['can_delete']) && !empty($module['can_delete'])) ? $module['can_delete']:0,
            'can_export' => (isset($module['can_export']) && !empty($module['can_export'])) ? $module['can_export']:0,
            'can_import' => (isset($module['can_import']) && !empty($module['can_upload'])) ? $module['can_import']:0,
            'can_print' => (isset($module['can_print']) && !empty($module['can_print'])) ? $module['can_print']:0,
        ];   
    }

    public function datatablesIndex($request = array())
    {
        if(auth()->user()->role_id != $this->model->developer_id) {
            return $model = $this->model->select(['id', 'name', 'display_name'])->whereNotIn('id', $this->model->hiddenRoleIds());
        }
        return $model = $this->model->select(['id', 'name', 'display_name']);
    }

    public function getLists()
    {

        if(auth()->user()->role_id != $this->model->developer_id) {
            return $model = $this->model->whereNotIn('id', $this->model->hiddenRoleIds())->pluck('name', 'id')->all();
        }
        return $model = $this->model->pluck('name', 'id')->all();
    }

    public function getHiddenRoleIds()
    {
        return $this->model->hiddenRoleIds();
    }

    public function getDeveloperId()
    {
        return $this->model->developer_id;
    }

    public function getEditorId()
    {
        return $this->model->editor_id;
    }

    public function getFieldOfficerId()
    {
        return $this->model->field_officer_id;
    }

    public function create(array $request)
    {
        $user = auth()->user();
        $model = $this->model->fill(Arr::except($request, ['module']));
        $model->save();
        $this->log->saveLog(['action' => 'Create', 'module_id' => $this->getModuleId(), 'user_id' => $user->id, 'data_id' => $model->id]);
        $this->makeRolePermissions($request, $model->id); 
        $this->write_menu(auth('client')->user()->client->id, $model->id);       
        return $model;
    }

    public function update($id, array $request)
    {
        $user = auth()->user();
        $model = $this->findById($id);
        $model->fill(Arr::except($request, ['module']));
        $model->save();
        session()->flash('success', 'Successfully updated.');
        $this->log->saveLog(['action' => 'Update', 'module_id' => $this->getModuleId(), 'user_id' => $user->id, 'data_id' => $model->id]);
        $this->makeRolePermissions($request, $model->id);
        $this->write_menu(auth('client')->user()->client->id, $id);        
        return $model;
    }

    public function delete($id, $client_id)
    {
        $user = auth()->user();
        if(in_array($id, $this->model->getdefaultIDs())) {
             return $this->getAjaxResponse('error', 'Default role cannot be deleted.');
        }
        $model = $this->model->findOrFail($id);
        if($model->users()->where('client_id',$client_id)->count() > 0) {
            return $this->getAjaxResponse('error', 'Role is currently used and cannot be deleted.');
        }
        $model->permissions()->delete();
        $model->delete();
        $this->log->saveLog(['action' => 'Delete', 'module_id' => $this->getModuleId(), 'user_id' => $user->id, 'data_id' => $model->id]);

        $view_path = realpath(app_path()).'/Modules/Client/Views';
        $realpath =  $view_path."/cache/menus/".$client_id."/";        
        $filename = $realpath."custom_".$id.".blade.php"; 
        File::delete($filename);
        return $this->getAjaxResponse('success', 'Successfully deleted.');
    }
}