<?php
require_once($global['root-model']."Crud.php");
$obj_crud = new Crud();

require_once($global['root-model']."Role.php");
$obj_role = new Role();

require_once($global['root-model']."Access.php");
$obj_access = new Access();

if(!isset($_GET['action']) && $_GET['id'] != ""){

    $O_id = $obj_crud->escape_string(check_input($_GET['id']));
    $data = $obj_role->get_data_detail($obj_crud, $O_id);

    $data_at = $obj_access->get_list_at($obj_crud, $O_id);

    $data_general = $obj_access->get_data_module($obj_crud, 'general');
    $data_dashboard = $obj_access->get_data_module($obj_crud, 'dashboard');
    $data_admin = $obj_access->get_data_module($obj_crud, 'admin');
    $data_po = $obj_access->get_data_module($obj_crud, 'po');
    $data_report = $obj_access->get_data_module($obj_crud, 'report');
    $data_client = $obj_access->get_data_module($obj_crud, 'client');
    $data_region = $obj_access->get_data_module($obj_crud, 'region');
    $data_unit = $obj_access->get_data_module($obj_crud, 'unit');
    $data_ppn = $obj_access->get_data_module($obj_crud, 'ppn');

    if(isset($_SESSION['status'])){
        $message = $_SESSION['status'];
        unset($_SESSION['status']);
    } else {
        $message = "";
    }

    if(isset($_SESSION['alert'])){
        $alert = $_SESSION['alert'];
        unset($_SESSION['alert']);
    } else {
        $alert = "";
    }


} else if(isset($_GET['action'])){

    if($_GET['action'] == "edit"){

        $N_item_id = $obj_crud->escape_string(check_input($_POST['item_id']));
        $N_title = $obj_crud->escape_string(check_input($_POST['title']));
        $N_slug = strtolower(preg_replace('/\s+/', '_', $N_title));

        $result = $obj_role->update_data($obj_crud, $N_item_id, $N_title, $N_slug);
        if($result != 0){
            $del_access = $obj_access->delete_at_by_role($obj_crud, $N_item_id);
            if(!empty($_POST['access'])) {
                foreach($_POST['access'] as $access) {
                    $res_access = $obj_access->insert_at($obj_crud, $N_item_id, $access);
                }
            }
            $message = "Admin Role <i><b>'" . $N_title . "'</b></i> Succesfully Edited.";
            $_SESSION['alert'] = "success";
        }else{
            $message = "Admin Role <i><b>'" . $N_title . "'</b></i> Failed to Edited.";
            $_SESSION['alert'] = "error";
        }

        $_SESSION['status'] = $message;
        header("Location:".$path['role-edit'].$N_item_id."/");

    }
}
?>