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

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

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

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

if(!isset($_GET['action'])){

    $data_region = $obj_region->get_data_select($obj_crud);

    $acsc_create = $obj_access->check_access($obj_cruds,$_SESSION['admin_id'],'create_client');
    $acsc_edit = $obj_access->check_access($obj_cruds,$_SESSION['admin_id'],'edit_client');
    $acsc_delete = $obj_access->check_access($obj_cruds,$_SESSION['admin_id'],'delete_client');

    if($acsg_client != 1){
        header("Location:".$path['dashboard']);
    }

    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'] == "insert"){

        $N_name = $obj_crud->escape_string(check_input($_POST['name']));
        $N_email = $obj_crud->escape_string(check_input($_POST['email']));
        $N_phone = $obj_crud->escape_string(check_input($_POST['phone']));
        $N_region = $obj_crud->escape_string(check_input($_POST['region']));
        $N_address = $obj_crud->escape_string(check_input($_POST['address']));

        $check_email = $obj_client->check_email($obj_crud, $N_email);
        if($check_email == 0){
            $result = $obj_client->insert_data($obj_crud, $N_name, $N_phone, $N_email, $N_address, $N_region);
            if($result != 0){
                $message = "Client <i><b>'".correctDisplay($N_name)."'</b></i> has been succesfully created.";
                $_SESSION['alert'] = "success";
            } else {
                $message = "Failed to insert new client.Something is Wrong.";
                $_SESSION['alert'] = "error";
            }
        } else {
            $message = "Insert data Failed.<br/>Email already exist.";
            $_SESSION['alert'] = "error";
        }

        $_SESSION['status'] = $message;
        header("Location:".$path['client']);

    } else if($_GET['action'] == "delete"){
        $N_id = $obj_crud->escape_string(check_input($_GET['id']));
        $N_title = $obj_crud->escape_string(check_input($_GET['title']));

        $result = $obj_client->delete_data($obj_crud, $N_id);
        if($result != 0){
            $message = "Client <i><b>'".correctDisplay($N_title)."'</b></i> has been succesfully deleted.";
            $_SESSION['alert'] = "success";
        } else {
            $message = "Failed to delete client.Something is wrong!";
            $_SESSION['alert'] = "error";
        }

        $_SESSION['status'] = $message;
        header("Location:".$path['client']);
    }
}
?>