<?php
session_start();

require_once '../Config/Database.php';
require_once '../Model/SystemPermission.php';
require_once '../Model/SystemGroup.php';
$system_group = new SystemGroup();
$system_permission = new SystemPermission();

$system_permissions = $system_permission->read_all_system_permissions();

if(isset($_GET['all_system_permissions'])){
    echo json_encode(
        array("data"=>$system_permissions)
    ); 
}

if(isset($_POST['add_system_permission'])){
    $action_link = $_POST['action_link'];
    $display_name = $_POST['display_name'];
    $system_group_name = $_POST['system_group_name'];
    $group_details = $system_group->get_system_group_by_name($system_group_name);
    $group_number = $group_details[0]['system_group_id'];
    $hidden = $_POST['hidden'];
    $data = array(
        "action_link"=>$action_link,
        "display_name"=>$display_name,
        "group_number"=>$group_number,
        "hidden"=>$hidden
    );
    $success = $system_permission->add_system_permission($data);
    if($success){
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}

if(isset($_POST['update_system_permission'])){
    $system_permission_id = $_POST['system_permission_id'];
    $action_link = $_POST['action_link'];
    $display_name = $_POST['display_name'];
    $system_group_name = $_POST['system_group_name'];
    $group_details = $system_group->get_system_group_by_name($system_group_name);
    $group_number = $group_details[0]['system_group_id'];
    $hidden = $_POST['hidden'];
    $data = array(
        "action_link"=>$action_link,
        "display_name"=>$display_name,
        "group_number"=>$group_number,
        "hidden"=>$hidden
    );
    $key = array(
        "system_permission_id"=>$system_permission_id
    );
    $success = $system_permission->update_system_permission($key,$data);
    if($success){
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}


if(isset($_POST['remove_system_permission'])){
    $system_permission_id = $_POST['system_permission_id'];
    $data = $system_permission->remove_system_permission($system_permission_id);
    if(!$data){
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}

// Empty Table
if(isset($_POST['empty_table'])){
    $table_name = $_POST['table_name'];
    $success = $system_permission->empty_table($table_name);
    if(!$success){
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}