<?php

class SettingsAjax extends mainController {

    private $db;

    public function __construct() {
        parent::__construct();
        $this->load->model('setting');
        $this->controller_permission = Session::getPermissionsObject();

        $this->db = DBConnectorFactory::loadDriver();
    }

    public function landing() {
        
    }

    public function getUsers() {
        $cond = '';
        $user_string = '';
        $flag = 0;
        $roles_to_control = CommonFunctions::get_user_roles(false);    //get current user roles to control [recursion to end]
        if (!Session::is_smart_admin()) {
            $user_ids = array();
            if (!empty($roles_to_control)) {
                $current_roles = explode(',', $roles_to_control);
                //get users with roles in the roles to control
                $query_users = $this->db->query('select Role_ID,User_ID from tbl_common_users');
                while ($row = $this->db->assoc($query_users)) {
                    $role_array = explode(',', $row['Role_ID']);
                    if (!array_diff($role_array, $current_roles)) {
                        $user_ids[] = $row['User_ID'];
                    }
                }
            }
            if (count($user_ids) > 0) {
                $user_string = implode(',', $user_ids);
                $cond .= " and User_ID IN ({$user_string}) ";
            } else {
                $cond .= " and 1=2  ";
                $flag = 1;
            }
        }
        if ($_GET['is_actual'] == 0) {
            $cond .= $flag == 1 ? '' : '  and (Is_Hidden = 0 or isnull(Employee_ID))';
        }
        if (isset($_GET['is_actual']) ) {
            $cond .=  '  and is_actual_user = '.$_GET['is_actual'] .'    ';
        }

        $columns = array('User_Name', 'Role_Name', 'User_Full_Name',
            array('db' => 'is_admin', 'dt' => 3, 'formatter' => function($d) {
                    return ($d == 0 ? CommonLanguage::getMessage('no') : CommonLanguage::getMessage('yes'));
                }),
            array('db' => 'User_ID', 'dt' => 4, 'formatter' => function( $d, $row ) {
                    $common = [
                        ["title" => CommonLanguage::getMessage($row[6] == 1 ? "disable" : "enable"),
                            "class" => "enable_disable_user",
                            "data-target" => "#enable-disable-modal",
                            "attr" => "data-id={$row[6]}",
                            "permission" => $_GET['is_actual'] == 0 ? "disable_enable_user" : "disable_enable_actual_user",
                            "icon" => "fa-" . ($row[6] == 1 ? 'lock' : 'unlock')
                        ]
                    ];
                    //                             if (smc_session()['default_setting']['activate_smart_diner'] == 1) {
                    $secret_code = ["title" => CommonLanguage::getMessage("change_secret_code"),
                        "class" => "change_secret_code",
                        "icon" => "fa-key",
                        "data-target" => "#change-secret-code-modal",
                        "permission" => $_GET['is_actual'] == 0 ? "change_secret_code" : "change_actual_secret_code"
                    ];
                    $common[] = $secret_code;
                    //                             }
                    if (smc_session()['default_setting']['sync_type'] != 2) {
                        $common[] = ["title" => CommonLanguage::getMessage("Edit"),
                            "class" => "edit_user",
                            "data-target" => "#add-edit-user-modal",
                            "permission" => $_GET['is_actual'] == 0 ? "edit_user" : "edit_actual_user",
                            "icon" => "fa-pencil"
                        ];
                        $common[] = ["title" => CommonLanguage::getMessage("delete"),
                            "class" => "delete_user",
                            "permission" => $_GET['is_actual'] == 0 ? "delete_user" : "delete_actual_user",
                            "icon" => "fa-trash"
                        ];
                        $common[] = ["title" => CommonLanguage::getMessage("change_password"),
                            "class" => "change_password",
                            "icon" => "fa-key",
                            "data-target" => "#change-password-modal",
                            "permission" => $_GET['is_actual'] == 0 ? "change_user_password" : "change_actual_user_password"
                        ];
                    }
                    if (Session::is_smart_admin()) {
                        $secret_code = ["title" => CommonLanguage::getMessage("empty_unique_id"),
                            "class" => "empty_unique_id",
                            "icon" => "fa-trash"
                        ];
                        $common[] = $secret_code;
                    }
                    $html = Forms::action_snippet(["color" => "info-light", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => $common]);
                    return $html;
                }), 'Role_ID', 'Status_ID'
        );
        $key = 'User_ID';
        $table = 'view_users';
        $data = DataTable::complex($_GET, $table, $key, $columns, ' 1=1 ' . $cond);
        echo json_encode($data);
    }

    public function submitUser() {
        $submit = $this->_registry->user->setData($_POST)->submitUser();
        die(json_encode(is_numeric($submit[0]) ? [CommonLanguage::getMessage($_POST['user_id'] == 0 ? 'user_added' : 'user_updated'), 'success', CommonLanguage::getMessage('add_user_accounts') . '<a class=" btn bg-info-light text-white openFrame m-t-10" data-src ="ACC/UserAccAccounts?is_pop=1&is_new=1&id=' . $submit[0] . '">' . CommonLanguage::getMessage('user_accounts') . '</a>'] : [$submit[0], 'danger']));
    }

    public function add_Shift_Request() {
        if (isset($_POST['Shift_ID'])) {
            $RET = $this->_registry->user->setData($_POST)->updateShift($_POST['Shift_ID']);
        } else {
            $RET = $this->_registry->user->setData($_POST)->addShifts();
        }
        die(empty($RET) ? "ok" : $RET[0]);
    }
    public function update_system_template() {
            $RET = $this->_registry->user->setData($_POST)->update_system_template($_POST['template_id'],$_POST['template_text']);
        die(empty($RET) ? "ok" : $RET[0]);
    }
    public function empty_system() {
        $RET = $this->_registry->user->setData($_POST)->empty_system($_POST['empty_type'],$_POST['invoice_id']);
        die(empty($RET) ? "ok" : $RET[0]);
    }

    public function update_system_expiry_date() {
        $RET = $this->_registry->user->setData($_POST)->update_system_expiry_date($_POST['system_expiry_date']);
        die(empty($RET) ? "ok" : $RET[0]);
    }

    public function add_update_system_note() {
        $RET = $this->_registry->user->setData($_POST)->add_update_system_note($_POST['system_version'],$_POST['system_note'],$_POST['select_version']);
        die(empty($RET) ? "ok" : $RET[0]);
    }

    public function add_update_template_branches() {
        $RET = $this->_registry->user->setData($_POST)->add_update_template_branches($_POST['template_key'],$_POST['template_name'],$_POST['template_text'],$_POST['branch_id'],$_POST['template_id']);
        die(empty($RET) ? "ok" : $RET[0]);
    }

    public function get_system_version() {
        $submit = $this->_registry->user->setData($_POST)->get_system_version();
        die(json_encode($submit[0]));
    }


    public function viewUserShifts() {
        if (isset($_GET['GetShiftID'])) {
            $id = $_GET['GetShiftID'];
            $result = $this->_registry->user->viewUserShiftsDetails($id);
            $days = $this->_registry->worktimes->viewUnOrWorkingDays(1);
            die(json_encode([$result, $days]));
        }
        if (isset($_POST["GetID"])) { // to update Status of Shift and delete 
            $delete_shift = $this->_registry->user->deleteShift($_POST["GetID"]);
            die(empty($delete_shift) ? "OK" : $delete_shift[0]);
        }
        $columns = array(
            array('db' => 'Shift_Name', 'dt' => 0),
            //            array('db' => 'Working_Day_ID', 'dt' => 1,"formatter" => function($d,$row) {
            //
            //                return $row[5];
            //
            //            }),
            array('db' => 'Working_Day_ID', 'dt' => 1, "formatter" => function($d,$row) {
                if($row[3]=='fx'){
                    $days = json_decode($d, true);
                    $string_arrays = '';
                    for ($i = 0; $i < count($days); $i++) {
                        $val = $days[$i];
                        $string_arrays .= CommonLanguage::getMessage($val['day_id'] == 1 ? 'Monday' : ($val['day_id'] == 2 ? 'Tuesday' : ($val['day_id'] == 3 ? 'Wednesday' : ($val['day_id'] == 4 ? 'Thursday' : ($val['day_id'] == 5 ? 'Friday' : ($val['day_id'] == 6 ? 'Saturday' : 'Sunday'))))));
                        $string_arrays .= ": " . str_replace(array('AM', 'PM'), array('ص', 'م'), $val['Shift_From'] . " &#8703; " . $val['Shift_To']);
                        if ($i < count($days) - 1) {
                            $string_arrays .= '<br/>';
                        }
                    };
                    return $string_arrays;
                }
            }
                 ),
            array('db' => 'Shift_ID', 'dt' => 2, 'formatter' => function( $d ) {
                $html = Forms::action_snippet(["color" => "success", "isDropDown" => true, "data_id" => $d,
                                               "ActionOption" => [
                                                   ["title" => CommonLanguage::getMessage("delete"),
                                                    "class" => "Delete",
                                                    "icon" => "fa-trash",
                                                    "permission" => "Delete_user_Shift"
                                                   ],
                                                   ["title" => CommonLanguage::getMessage("Edit"),
                                                    "class" => "Edit",
                                                    "icon" => "fa-pencil",
                                                    "permission" => "Edit_user_Shift",
                                                    "href" => "Settings/add_shift_time/{$d}"
                                                   ]
                                               ]]);
                return $html;
            }
                 ),array('db' => 'shift_type', 'dt' => 3)
        );
        $key = 'Shift_ID';
        $table = 'view_user_shifts';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }
    public function enableDisableUser() {
        $submit = $this->_registry->user->setData($_POST)->enableDisableUser();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage($_POST['status_id'] == 0 ? 'user_enabled_success' : 'user_disabled_success'), 'success'] : [$submit[0], 'danger']));
    }
    public function get_system_template() {
        $submit = $this->_registry->user->setData($_POST)->get_system_template();
        die(json_encode($submit[0]));
    }

    


    public function submitRolePermissions() {
        $submit = $this->_registry->role_permission->setData($_POST)->submitRolePermissions();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage($_POST['Role_ID'] == 0 ? 'role_permissions_added' : 'role_permissions_updated'), 'success'] : [$submit[0] == 'unauthorized_edit_role' ? CommonLanguage::getMessage('unauthorized_edit_role') : $submit[0], 'danger']));
    }

    public function deleteUser() {
        $delete_user = $this->_registry->user->deleteUser($_GET['user_id']);
        die(empty($delete_user) ? "ok" : "error");
    }

    

    public function deleteRolePermation() {
        if (isset($_GET["GetRoleID"])) { // to update Status of delete 
            $logged_id = Session::getUserID();
            $Role_ID = $_GET["GetRoleID"];
            $delete_role = $this->_registry->user->deleteRolePermation($Role_ID);
            die(empty($delete_role) ? "OK" : CommonLanguage::getMessage($delete_role[0]));
        }
    }

    public function getUserData() {
        $data['user'] = CommonFunctions::CommonView('view_users', ['User_ID'], [$_GET['user_id']]);
        $data['role'] = $this->_registry->role->getUserRoles($data['user'][0]['Role_ID']);
        $data['control_role'] = '';
        if (!empty($data['user'][0]['control_role_id']))
            $data['control_role'] = $this->_registry->role->getUserRoles($data['user'][0]['control_role_id']);
        die(json_encode($data));
    }

    public function getRoles() {
        $roles_to_control = CommonFunctions::get_user_roles(false); //get current user roles to control [recursion to end]
        $columns = array('Role_Name', 'parent_role_name',
            array('db' => 'Role_ID', 'dt' => 2, 'formatter' => function( $d ) {
                $actions = [
                    //                                                                ["title" => CommonLanguage::getMessage("delete"),
                    //                                                                 "class" => "delete_user",
                    //                                                                 "permission" => "deleteUser",
                    //                                                                 "icon" => "fa-trash"
                    // 
                    [
                        "title" => CommonLanguage::getMessage("Edit"),
                        "class" => "edit_role_permissions",
                        "data-target" => "#add-edit-role-permissions-modal",
                        "permission" => "edit_role_permissions",
                        "attr" => "data-type='edit'",
                        "icon" => "fa-pencil"
                    ],
                    [
                        "title" => CommonLanguage::getMessage("Delete"),
                        "class" => "delete_role_permissions",
                         "permission" => "delete_role_permissions",
                         "icon" => "fa-trash"
                    ]
                ];
                    if ($d != 1) {
                        $actions[] = ["title" => CommonLanguage::getMessage("copy"),
                            "class" => "copy_role_permissions",
                            "data-target" => "#add-edit-role-permissions-modal",
                            "permission" => "copy_role_permissions",
                            "attr" => "data-type='copy'",
                            "icon" => "fa-copy"
                        ];
                    }
                    $html = Forms::action_snippet(["color" => "info-light", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => $actions
                    ]);
                    return smc_session()['default_setting']['sync_type'] != 2 ? $html : '<span>' . CommonLanguage::getMessage('noauthactions') . '</span>';
                })
        );
        $key = 'Role_ID';
        $table = 'view_roles';
        $condition = Session::is_smart_admin() ? '' : (!empty($roles_to_control) ? " Role_ID IN ({$roles_to_control})" : "1=2");
        $data = DataTable::complex($_GET, $table, $key, $columns, $condition);
        echo json_encode($data);
    }

    public function getComputersTrusted() {
        $columns = array('computer_name',
            array('db' => 'entry_id', 'dt' => 1, 'formatter' => function( $d ) {
                    $html = Forms::action_snippet(["color" => "info-light", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => [
                                    ["title" => CommonLanguage::getMessage("delete"),
                                        "class" => "delete_trusted_computer",
                                        "permission" => "delete_trusted_computer",
                                        "icon" => "fa-trash"
                                    ],
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        "class" => "edit_trusted_computer",
                                        "data-target" => "#add-edit-computer-trusted-modal",
                                        "permission" => "edit_trusted_computer",
                                        "icon" => "fa-pencil"
                                    ]]
                    ]);
                    return $html;
                })
        );
        $key = 'entry_id';
        $table = 'tbl_computer_trusted';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function getRootRolesParents() {
        $_GET['role_id'] = $_GET['role_id'] == 0 ? 1 : $_GET['role_id'];
        $data['parent'] = $this->_registry->permission->setData($_GET)->getRootRolesParents();
        $data['tab_content'] = $this->_registry->permission->setData($_GET)->getTabContent($data['parent']);
        die(json_encode($data));
    }

    public function getPermissionsByRole() {
        $data['main'] = CommonFunctions::CommonView('view_roles', ['Role_ID'], [$_GET['role_id']]);
        $data['perm'] = $this->_registry->role->getPermissionsByRoleID($_GET['role_id']);
        die(json_encode($data));
    }

    public function submitPassword() {
        $submit = $this->_registry->user->setData($_POST)->submitPassword();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function submitSecretCode() {
        $submit = $this->_registry->user->setData($_POST)->submitSecretCode();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function submitTrustedComputer() {
        $submit = $this->_registry->user->setData($_POST)->submitTrustedComputer();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function deleteTrustedComputer() {
        $delete = $this->_registry->user->setData($_GET)->deleteTrustedComputer();
        die(empty($delete) ? "ok" : "error");
    }

    public function empty_unique_id_ajax() {
        $edit = $this->_registry->user->empty_unique_id($_POST['user_id']);
        die(empty($edit) ? 'OK' : 'error');
    }

    public function submitDefaultSetting() {
        $submit = $this->_registry->user->setData($_POST)->submitDefaultSetting();
        if (empty($submit)) {
            smc_session()['default_setting'][$_POST['setting_name']] = $_POST['setting_value'];
            die(json_encode([CommonLanguage::getMessage('Submitted_Successfully'), 'success']));
        }
        die(json_encode([$submit[0], 'danger']));
    }

    public function deletSpecificImage() {
        $submit = $this->_registry->setting_class->setData($_GET)->deletSpecificImage();
        die(json_encode($submit ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function submitAccountSetting() {
        $submit = $this->_registry->user->setData($_POST)->submitAccountSetting();
        if (empty($submit)) {
            smc_session()['account_setting'][$_POST['setting_name']] = $_POST['setting_value'];
            die(json_encode([CommonLanguage::getMessage('Submitted_Successfully'), 'success']));
        }
        die(json_encode([$submit[0], 'danger']));
    }

    public function enableDisableItem() {
        $submit = $this->_registry->setting_class->setData($_POST)->enableDisableItem();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function getSystemSetting() {
        $_GET['customers'] = array();
        $_GET['currency'] = array();
        $_GET['prod_cat'] = array();
        $_GET['price'] = array();
        $_GET['org_branch'] = array();
        $_GET['depot'] = array();
        $_GET['cash_pay_acc'] = array();
        $_GET['check_pay_acc'] = array();
        $_GET['deals_stage'] = array();
        $currency_query = $this->db->query('select Currency_ID as id,Currency_Name as text  from tbl_common_currency');
        while ($currency_row = $this->db->assoc($currency_query)) {
            $_GET['currency'][$currency_row['id']] = $currency_row;
        }
        $customers_query = $this->db->query('select Customer_ID as id,Customer_Name as text  from tbl_customers');
        while ($customers_row = $this->db->assoc($customers_query)) {
            $_GET['customers'][$customers_row['id']] = $customers_row;
        }
        $category_query = $this->db->query('select Cat_ID as id,Cat_Name as text from tbl_product_cat');
        while ($category_row = $this->db->assoc($category_query)) {
            $_GET['prod_cat'][$category_row['id']] = $category_row;
        }
        $price_query = $this->db->query('select Class_ID as id,Class_Name as text from tbl_pricing_class');
        while ($price_row = $this->db->assoc($price_query)) {
            $_GET['price'][$price_row['id']] = $price_row;
        }
        $branch_query = $this->db->query('select branch_id as id,branch_name as text from tbl_organization_branches');
        while ($branch_row = $this->db->assoc($branch_query)) {
            $_GET['org_branch'][$branch_row['id']] = $branch_row;
        }
        $depot_query = $this->db->query('select Depot_ID as id,Depot_Name as text from tbl_stock_depot_warehouse');
        while ($depot_row = $this->db->assoc($depot_query)) {
            $_GET['depot'][$depot_row['id']] = $depot_row;
        }
        $country_query = $this->db->query('select Country_ID as id,Country_Name as text from tbl_all_countries');
        while ($country_row = $this->db->assoc($country_query)) {
            $_GET['country'][$country_row['id']] = $country_row;
        }
        $city_query = $this->db->query('select ID as id,Name as text from tbl_all_cities');
        while ($city_row = $this->db->assoc($city_query)) {
            $_GET['city'][$city_row['id']] = $city_row;
        }
        $deals_stage_query = $this->db->query('select stage_id as id,stage_title as text from tbl_deals_stage');
        while ($deals_stage_row = $this->db->assoc($deals_stage_query)) {
            $_GET['deals_stage'][$deals_stage_row['id']] = $deals_stage_row;
        }
        $cash_query = $this->db->query('SELECT Account_ID as id,
                                          concat(Account_Name," - ",Account_Code) as text,
                                          main_type,sub_type,main_id,
                                          Account_Code,
                                          job_required
                                    FROM 
                                        tbl_chart_of_accounts
                                        WHERE Status_ID = 1  AND main_type="pay" and concat(",",sub_type,",") like "%,cash,%" ');
        while ($cash_row = $this->db->assoc($cash_query)) {
            $_GET['cash_pay_acc'][$cash_row['id']] = $cash_row;
        }
        $cheque_query = $this->db->query('SELECT Account_ID as id,
                                          concat(Account_Name," - ",Account_Code) as text,
                                          main_type,sub_type,main_id,
                                          Account_Code,
                                          job_required
                                    FROM 
                                        tbl_chart_of_accounts
                                        WHERE Status_ID = 1  AND main_type="pay" and concat(",",sub_type,",") like "%,check,%" ');
        while ($cheque_row = $this->db->assoc($cheque_query)) {
            $_GET['check_pay_acc'][$cheque_row['id']] = $cheque_row;
        }
        $condition = ($_GET['setting_search'] != '' ? "  and setting_name LIKE '%" . $_GET['setting_search'] . "%' " : "") . (!Session::is_smart_admin() ? " and is_private = 0" : "");
        $columns = array('setting_name',
            array('db' => 'setting_name', 'dt' => 1, 'formatter' => function( $d ) {
                    return CommonLanguage::getMessage('setting_' . $d);
                }),
            array('db' => 'setting_name', 'dt' => 2, 'formatter' => function( $d, $row ) {
                    $setting_type = explode("##", $row[4]);
                    if ($setting_type[0] == 'table' && !empty($row[5])) {
                        if ($setting_type[1] == 's')
                            $setting_value = $_GET[$setting_type[2]][$row[5]]['text'];
                        else {
                            $setting_value_array = explode(",", $row[5]);
                            $setting_multiple_select = array();
                            foreach ($setting_value_array as $setting)
                                $setting_multiple_select[] = $_GET[$setting_type[2]][$setting];
                            $setting_value = $setting_multiple_select;
                        }
                    } else
                        $setting_value = '';
                    return Forms::build_setting_row($d, $row[4], $row[5], $setting_value);
                }),
            array('db' => 'setting_id', 'dt' => 3, 'formatter' => function( $d, $row) {
                    $type = explode('##', $row[4]);
                    return '<button  data-type ="' . $type[0] . '" data-id="' . $d . '" data-content="' . $row[0] . '" class="btn bg-info-light text-white submit-default-setting" >' . CommonLanguage::getMessage('Save') . '</button>';
                }), 'setting_type', 'setting_value'
        );
        $key = 'setting_id';
        $table = 'tbl_default_settings';
        $data = DataTable::complex($_GET, $table, $key, $columns, ' 1=1 ' . $condition);
        echo json_encode($data);
    }

    public function getAccountSetting() {
        $_GET['chart_of_accounts'] = array();
        $account_query = $this->db->query('select Account_ID as id,Account_Name as text from tbl_chart_of_accounts');
        while ($account_row = $this->db->assoc($account_query)) {
            $_GET['chart_of_accounts'][$account_row['id']] = $account_row;
        }
        $condition = ($_GET['setting_search'] != '' ? "  and acc_setting_name LIKE '%" . $_GET['setting_search'] . "%' " : "");
        $columns = array('acc_setting_name',
            array('db' => 'acc_setting_name', 'dt' => 1, 'formatter' => function( $d ) {
                    return CommonLanguage::getMessage('account_' . $d);
                }),
            array('db' => 'acc_setting_name', 'dt' => 2, 'formatter' => function( $d, $row ) {
                    $setting_type = explode("##", $row[4]);
                    if ($setting_type[0] == 'table' && !empty($row[5])) {
                        if ($setting_type[1] == 's')
                            $setting_value = $_GET[$setting_type[2]][$row[5]]['text'];
                        else {
                            $setting_value_array = explode(",", $row[5]);
                            $setting_multiple_select = array();
                            foreach ($setting_value_array as $setting)
                                $setting_multiple_select[] = $_GET[$setting_type[2]][$setting];
                            $setting_value = $setting_multiple_select;
                        }
                    } else
                        $setting_value = '';
                    return Forms::build_setting_row($d, $row[4], $row[5], $setting_value);
                }),
            array('db' => 'id', 'dt' => 3, 'formatter' => function( $d, $row) {
                    $type = explode('##', $row[4]);
                    return '<button data-type ="' . $type[0] . '" data-id="' . $d . '" data-content="' . $row[0] . '" class="btn bg-info-light text-white submit-account-setting" >' . CommonLanguage::getMessage('Save') . '</button>';
                }), 'setting_type', 'acc_setting_value'
        );
        $key = 'id';
        $table = 'tbl_account_setting';
        $data = DataTable::complex($_GET, $table, $key, $columns, ' 1=1 ' . $condition);
        echo json_encode($data);
    }

    public function add_edit_web_api_user() {
        $submit = $this->_registry->user->setData($_POST)->add_edit_web_api_user();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function enable_disable_api_user() {
        $submit = $this->_registry->user->setData($_POST)->enable_disable_api_user();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage($_POST['status_id'] == 0 ? 'user_enabled_success' : 'user_disabled_success'), 'success'] : [$submit[0], 'danger']));
    }

    public function web_api_user_ajax() {
        $cond = '';
        $columns = array('title', 'username', 'Class_Name', 'Depot_Name',
            array('db' => 'user_id', 'formatter' => function( $d, $row ) {
                    $common = [["title" => CommonLanguage::getMessage("Edit"),
                    "class" => "edit_user",
                    "data-target" => "#add_user_modal",
                    "permission" => "edit_web_api_users",
                    "icon" => "fa-pencil"]
                        , ["title" => CommonLanguage::getMessage("delete"),
                            "class" => "delete_user",
                            "permission" => "delete_web_api_users",
                            "icon" => "fa-trash"
                        ]
                    ];
                    $html = Forms::action_snippet(["color" => "info-light", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => $common]);
                    return $html;
                })
        );
        $key = 'user_id';
        $table = 'web_api_users';
        $data = DataTable::complex($_GET, $table, $key, $columns, ' 1=1 ' . $cond);
        echo json_encode($data);
    }

    public function get_web_api_user() {
        $data = $this->_registry->user->get_web_api_user($_GET['user_id']);
        die(json_encode($data));
    }

    public function delete_web_api_user() {
        $delete = $this->_registry->user->delete_web_api_user($_GET['user_id']);
        die(empty($delete) ? 'ok' : $delete[0]);
    }

    public function getDevices() {
        $columns = array('device_name', 'device_ip',
            array('db' => 'is_active', 'dt' => 2, 'formatter' => function( $d, $row, $excel ) {
                    return $excel ? CommonLanguage::getMessage($d == 1 ? 'enabled' : 'disabled') : '<span class="label label-' . ($d == 1 ? 'success' : 'danger') . '">' . CommonLanguage::getMessage($d == 1 ? 'enabled' : 'disabled') . '</span>';
                }),
            array('db' => 'device_id', 'dt' => 3, 'formatter' => function( $d ) {
                    $html = Forms::action_snippet(["color" => "info-light", "isDropDown" => true, "data_id" => $d,
                                "ActionOption" => [
                                    ["title" => CommonLanguage::getMessage("Edit"),
                                        "class" => "edit",
                                        "data-target" => "#device_modal",
                                        "permission" => "edit_device",
                                        "icon" => "fa-pencil"
                                    ],
                                    ["title" => CommonLanguage::getMessage("delete"),
                                        "class" => "delete",
                                        "permission" => "delete_device",
                                        "icon" => "fa-trash"
                                    ]
                                ]
                    ]);
                    return $html;
                })
        );
        $key = 'device_id';
        $table = 'devices';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function submitDevice() {
        $submit = $this->_registry->setting_class->setData($_POST)->submitDevice();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function getDeviceData() {
        $data = CommonFunctions::CommonView('devices', ['device_id'], [$_GET['device_id']])[0];
        die(json_encode($data));
    }

    public function deleteDevice() {
        $delete = $this->_registry->setting_class->setData($_GET)->deleteDevice();
        die(empty($delete) ? "ok" : $delete[0]);
    }

    public function submitRegion() {
        $submit = $this->_registry->setting_class->setData($_POST)->submitRegion();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function deleteRegion() {
        $delete = $this->_registry->setting_class->setData($_GET)->deleteRegion();
        die(empty($delete) ? "ok" : $delete[0]);
    }

    public function getRegions() {
        $columns = array('region_name',
            array('db' => 'region_id', 'formatter' => function( $d ) {
                    $html = Forms::action_snippet(
                                    ["color" => "info-light",
                                        "isDropDown" => true,
                                        "data_id" => $d,
                                        "ActionOption" => [
                                            ["title" => CommonLanguage::getMessage("Edit"),
                                                "class" => "edit",
                                                "data-target" => "#region_modal",
                                                "permission" => "edit_region",
                                                "icon" => "fa-pencil"
                                            ],
                                            ["title" => CommonLanguage::getMessage("delete"),
                                                "class" => "delete",
                                                "permission" => "delete_region",
                                                "icon" => "fa-trash"
                                            ]
                                        ]
                    ]);
                    return $html;
                })
        );
        $key = 'region_id';
        $table = 'tbl_regions';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function getUserSetting() {
        $_GET['blocks'] = array();
        $department_query = $this->db->query('select block_id as id,block_name as text  from tbl_subscription_block where parent_id = 0');
        while ($department_row = $this->db->assoc($department_query)) {
            $_GET['blocks'][$department_row['id']] = $department_row;
        }
        $_GET['customer_groups'] = array();
        $customer_group_query = $this->db->query('select group_id as id,group_name as text  from tbl_general_groups where group_type = "cust"');
        while ($customer_group_row = $this->db->assoc($customer_group_query)) {
            $_GET['customer_groups'][$customer_group_row['id']] = $customer_group_row;
        } 
        $_GET['notification_types'] = array();
        $notification_type_query = $this->db->query('select notification_type_id as id,notification_type_name as text  from tbl_notification_type');
        while ($notification_type_row = $this->db->assoc($notification_type_query)) {
            $_GET['notification_types'][$notification_type_row['id']] = $notification_type_row;
        }
        $cond = '';
        if (empty($_GET['user_options']))
            $cond .= ' and 1=2 ';
        $user_options_arr = empty($_GET['user_options']) ? array() : $_GET['user_options'];

        $crnt_col_no = 0;
        $col_no_aftr_options = $crnt_col_no + count($user_options_arr);
        $columns = array(
            array('db' => 'User_Full_Name', "formatter" => function($d, $row) {
                    return '<span class="user_full_name" data-user-id="' . $row['User_ID'] . '">' . $d . '</span>';
                })
        );
        foreach ($user_options_arr as $user_option) {
            $columns[] = array('db' => 'User_ID', 'dt' => ++$crnt_col_no, "formatter" => function($d, $row) use($user_option, $col_no_aftr_options) {
                    if ($user_option == 1) {
                        if (!empty($row['block_ids'])) {
                            $value_array = explode(",", $row['block_ids']);
                            $multiple_select = array();
                            foreach ($value_array as $val)
                                $multiple_select[] = $_GET['blocks'][$val];
                            $value = json_encode($multiple_select);
                        } else
                            $value = '';
                        return "<input type='hidden' class='full-width' name='block_ids'  data-content-multiple='" . (empty($value) ? '' : $value ) . "'/>";
                    } else if ($user_option == 2){
                        if (!empty($row['customer_group_ids'])) {
                            $value_array = explode(",", $row['customer_group_ids']);
                            $multiple_select = array();
                            foreach ($value_array as $val)
                                $multiple_select[] = $_GET['customer_groups'][$val];
                            $value = json_encode($multiple_select);
                        } else
                            $value = '';
                        return "<input type='hidden' class='full-width' name='customer_group_ids'  data-content-multiple='" . (empty($value) ? '' : $value ) . "'/>";
                    }else {
                          if (!empty($row['notification_type_ids'])) {
                            $value_array = explode(",", $row['notification_type_ids']);
                            $multiple_select = array();
                            foreach ($value_array as $val)
                                $multiple_select[] = $_GET['notification_types'][$val];
                            $value = json_encode($multiple_select);
                        } else
                            $value = '';
                        return "<input type='hidden' class='full-width' name='notification_type_ids'  data-content-multiple='" . (empty($value) ? '' : $value ) . "'/>";
                    }
                });
        }
        $columns[] = array('db' => 'User_ID', 'dt' => ++$crnt_col_no);
        $columns[] = array('db' => 'block_ids', 'dt' => ++$crnt_col_no);
        $columns[] = array('db' => 'customer_group_ids', 'dt' => ++$crnt_col_no);
        $columns[] = array('db' => 'notification_type_ids', 'dt' => ++$crnt_col_no);

        $key = 'User_ID';
        $table = 'tbl_common_users';

        $data = DataTable::complex($_GET, $table, $key, $columns, ' 1=1 ' . $cond);

        echo json_encode($data);
    }

    public function submitUserSetting() {
        $submit = $this->_registry->setting_class->setData($_POST)->submitUserSetting();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
     public function submit_lock() {
        $submit = $this->_registry->setting_class->setData($_POST)->submit_lock();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function delete_lock_data() {
        $delete = $this->_registry->setting_class->setData($_GET)->delete_lock_data();
        die(empty($delete) ? "ok" : $delete[0]);
    }

    public function lock_data_ajax() {
        $columns = array('lock_date',
            array('db' => 'lock_id', 'formatter' => function( $d ) {
                    $html = Forms::action_snippet(
                                    ["color" => "info-light",
                                        "isDropDown" => true,
                                        "data_id" => $d,
                                        "ActionOption" => [
                                            ["title" => CommonLanguage::getMessage("Edit"),
                                                "class" => "edit",
                                                "data-target" => "#lock_modal",
                                                "permission" => "edit_lock_data",
                                                "icon" => "fa-pencil"
                                            ],
                                            ["title" => CommonLanguage::getMessage("delete"),
                                                "class" => "delete",
                                                "permission" => "delete_lock_data",
                                                "icon" => "fa-trash"
                                            ]
                                        ]
                    ]);
                    return $html;
                })
        );
        $key = 'lock_id';
        $table = 'tbl_lock_data';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }
    public function getTemplateBranchesList()
    {
        $cond = '1=1 ';
        if($this->controller_permission->hasPermission('Branches')){
            $cond .= !empty($_GET['search_branch_id']) ? ' and branch_id ="' . ($_GET['search_branch_id']) . '"' : '';
        }else{
            $cond .= ' and branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '"'  ;
        }

        $cond .= !empty($_GET['template_key']) ? ' and template_key ="' . ($_GET['template_key']) . '"' : '';

        $columns = array('template_id', 
            array('db' => 'branch_id', 'dt' => 1, 'formatter' => function ($d) {
                $branch_name = CommonBusiness::getBranchByBranchId($d);
                return $branch_name['branch_name'];
            }), 'template_name', 'template_key',
            array('db' => 'template_id', 'dt' => 4, 'formatter' => function ($d) {
                $html = Forms::action_snippet([
                    "color" => "info-light", "isDropDown" => true, "data_id" => $d,
                    "ActionOption" => [
                        [
                            "title" => CommonLanguage::getMessage("Edit"),
                            "class" => "edit_trusted_computer",
                            "href" => "Settings/template_branches/{$d}",
                            "permission" => "edit_template",
                            "icon" => "fa-pencil"
                        ],
                        [
                            "title" => CommonLanguage::getMessage("delete"),
                            "class" => "delete_template",
                            "permission" => "delete_template",
                            "icon" => "fa-trash"
                        ],
                        [
                            "title" => CommonLanguage::getMessage("attribute_list"),
                            "class" => "attribute_list",
                            "href" => "Settings/attribute_list/{$d}",
                            "permission" => "attribute_list",
                            "icon" => "fa-pencil"
                        ]

                    ]
                ]);
                return $html;
            })
        );
        $columns[] = 'status';
        $columns[] = 'copies';
        $key = 'template_id';
        $table = 'tbl_print_template';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond, null, null, 'ORDER BY template_id DESC');
        echo json_encode($data);
    }
    public function deleteTemplate() {
        $delete = $this->_registry->user->setData($_POST)->deleteTemplate();
        die(empty($delete) ? 'OK' : $delete[0]);
    }
    public function deleteAttributeTemplate() {
        $delete = $this->_registry->user->setData($_POST)->deleteAttributeTemplate();
        die(empty($delete) ? 'OK' : 'error');
    }
    public function submitTemplateAttribute() {
        $submit = $this->_registry->user->setData($_POST)->submitTemplateAttribute();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function getTemplateAttributeList()
    {
        $cond = '1=1 ';
        $cond .= !empty($_GET['template_id']) ? ' and  template_id = "' . ($_GET['template_id']) . '" ' : '';
        $cond .= !empty($_GET['search_branch_id']) ? ' and branch_id ="' . ($_GET['search_branch_id']) . '" ' : '' ;

        $columns = array('attribute_id', 
            array('db' => 'attribute_id', 'dt' => 1, 'formatter' => function ($d) {
                $template_info = CommonBusiness::getTempableInfoByTempableId($d);
                return $template_info;
            }), 'attribute_key', 'attribute_value',
            array('db' => 'attribute_id', 'dt' => 4, 'formatter' => function ($d) {
                $html = Forms::action_snippet([
                    "color" => "info-light", "isDropDown" => false, "data_id" => $d,
                    "ActionOption" => [
                        
                        [
                            "title" => CommonLanguage::getMessage("delete"),
                            "class" => "delete_attribute",
                            "permission" => "delete_template_attribute",
                            "icon" => "fa-trash"
                        ]

                    ]
                ]);
                return $html;
            })
        );
        $key = 'attribute_id';
        $table = 'tbl_template_attribute';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond, null, null, 'ORDER BY attribute_id DESC');
        echo json_encode($data);
    }


}
