<?php

class Session {

    public static function create(array $UserInformation) {
        smc_session()['user_logged_id'] = $UserInformation['User_ID'];
        smc_session()['user_logged_username'] = $UserInformation['User_Name'];
        smc_session()['user_role_id'] = $UserInformation['Role_ID'];
        smc_session()['control_role_id'] = $UserInformation['control_role_id'];
        smc_session()['login_device'] = $UserInformation['login_device'];
        if (empty($UserInformation['User_Full_Name']))
            $UserInformation['User_Full_Name'] = $UserInformation['User_FirstName'] . ' ' . $UserInformation['User_LastName'];
        smc_session()['user_logged_full_name'] = $UserInformation['User_Full_Name'];
        smc_session()['permissions'] = $UserInformation['permissions'];
        smc_session()['login_page'] = empty($UserInformation['login_page']) ? 'main' : $UserInformation['login_page'];
        smc_session()['user_details'] = User::getUserDetails();
        smc_session()['user_is_admin'] = smc_session()['user_details']['is_admin'];
        smc_session()['user_department_id'] = smc_session()['user_details']['Branch_ID'];
        smc_session()['user_group_ids'] = Session::getUserGroupIds();
        smc_session()['user_accounts'] = User::getUserAccDetails($UserInformation['User_ID']);
        $user_accounts_data = Session::getUserAccounts(smc_session()['user_logged_id']);
        smc_session()['Cash_Account'] = $user_accounts_data['Cash_Account'];
        smc_session()['Cheque_Account'] = $user_accounts_data['Cheque_Account'];
        smc_session()['Shipping_Account'] = $user_accounts_data['purchase_shipping'];
        smc_session()['Other_Account'] = $user_accounts_data['Other_Account'];
        smc_session()['Sales_Account'] = $user_accounts_data['sales_account'];
        smc_session()['Purchase_Account'] = $user_accounts_data['purchase_account'];
        smc_session()['Deposit_Account'] = $user_accounts_data['Deposit_Account'];
        smc_session()['Withdrawal_Account'] = $user_accounts_data['Withdrawal_Account'];
        smc_session()['reminder_end_day'] = empty($UserInformation['reminder_end_day']) ? 0 : 1;
        smc_session()['lang_code'] = $UserInformation['Language_Code'];
        smc_session()['block_ids'] = $UserInformation['block_ids'];
        smc_session()['customer_group_ids'] = $UserInformation['customer_group_ids'];
        smc_session()['notification_type'] = $UserInformation['notification_type_ids'];
        //
        self::create2();
    }

    //here sessions that are not related to user, so we can get it even if not login
    public static function create2() {
        //just to don't get error when check it later, in case if not logged in | if login then already filled above
        if (empty(smc_session()['user_logged_id'])) {
            smc_session()['lang_code'] = 'en';
            smc_session()['reminder_end_day'] = 0;
            smc_session()['user_logged_id'] = null;
        }
        $current_year_data = Session::getCurrentYearData();
        smc_session()['current_year_id'] = $current_year_data['current_year_id'];
        smc_session()['current_year'] = $current_year_data['current_year'];
        smc_session()['start_date'] = $current_year_data['start_date'];
        smc_session()['end_date'] = $current_year_data['end_date'];
        smc_session()['year_closed'] = $current_year_data['is_closed'];
        smc_session()['start_date_act'] = $current_year_data['start_date'];
        smc_session()['end_date_act'] = $current_year_data['end_date'];
        smc_session()['year_closed_act'] = $current_year_data['is_act_closed'];
        smc_session()['current_year_id_actual'] = $current_year_data['current_year_id'];
        smc_session()['current_year_actual'] = $current_year_data['current_year'];
        smc_session()['stock_method'] = Session::getStockMethod();
        smc_session()['Is_Cash_Default'] = Session::returnCashType();
        $default_depot = Session::getDefaultDepot();
        smc_session()['default_depot_id'] = $default_depot['Depot_ID'];
        smc_session()['default_depot_name'] = $default_depot['Depot_Name'];
        smc_session()['org_detail'] = Session::organization_details();
        smc_session()['account_setting'] = Session::getAccountSetting();
        $general_settings = Session::getGeneralSetting();
        smc_session()['general_setting'] = $general_settings;
        $default_settings = Session::getDefaultSetting();
        smc_session()['default_setting'] = $default_settings;
        smc_session()['allow_purchase_vat_edit'] = $default_settings['allow_purchase_vat_edit'];
        smc_session()['customer_code_in_app'] = $default_settings['customer_code_in_app'];
        smc_session()['transfer_from_current_branch_only'] = $default_settings['transfer_from_current_branch_only'];
        smc_session()['stop_user_prefix'] = $default_settings['stop_user_prefix'];
        smc_session()['stop_branch_prefix'] = $default_settings['stop_branch_prefix'];
        smc_session()['print_pos_order'] = $default_settings['print_pos_order'];
        smc_session()['activate_scale'] = $default_settings['activate_scale'];
        smc_session()['negative_sales'] = $default_settings['negative_sales'];
        smc_session()['sumatra_print'] = $default_settings['sumatra_print'];
        smc_session()['plu_as_code'] = $default_settings['plu_as_code'];
        smc_session()['vat_percent'] = $default_settings['vat_percent'];
        smc_session()['auto_generate_code'] = $default_settings['auto_generate_code'];
        smc_session()['change_pos_currency'] = $default_settings['change_pos_currency'];
        smc_session()['default_branch_id'] = $default_settings['default_branch_id'];
        smc_session()['default_cat_table'] = $default_settings['default_cat_table'];
        smc_session()['default_cat_delivery'] = $default_settings['default_cat_delivery'];
        smc_session()['activate_pos_select_cat'] = $default_settings['activate_pos_select_cat'];
        $default_branch = Session::getDefaultBranch();
        smc_session()['default_branch_name'] = $default_branch['branch_name'];
        smc_session()['default_branch_prefix'] = $default_branch['branch_prefix'];
        $default_class = Session::getDefaultPricingClassID();
        smc_session()['pricing_class_id'] = $default_class['Class_ID'];
        smc_session()['pricing_class_name'] = $default_class['Class_Name'];
        smc_session()['pricing_class_currency'] = $default_class['Currency_ID'];
        smc_session()['pricing_class_currency_symbol'] = $default_class['Currency_Symbol'];
        smc_session()['class_tax'] = $default_class['tax_amount'];
        smc_session()['class_is_ttc'] = $default_class['is_ttc'];
        $local_currency = Session::getLocalCurrency();
        smc_session()['default_currency'] = Session::getDefaultCurrency();
        smc_session()['local_currency'] = $local_currency['local_currency'];
        smc_session()['local_currency_symbol'] = $local_currency['Currency_Symbol'];
        smc_session()['local_currency_code'] = $local_currency['Currency_Code'];
        smc_session()['local_currency_round'] = $local_currency['currency_round'];
        smc_session()['local_currency_name'] = $local_currency['Currency_Name'];
        smc_session()['second_currency'] = Session::getSecondCurrency();
        smc_session()['default_overtime'] = Session::getDefaultOvertimeDay();
        smc_session()['default_school_max_no_childreen'] = Session::getDefaultNumChildreen();
        smc_session()['default_school_max_value_grant'] = Session::getDefaultValueSchoolGrant();
        smc_session()['datatable_header'] = Forms::build_print_template('datatable_print_header')['html'];
        smc_session()['datatable_header'] = str_replace("org_logo/invoice_logo.jpg",smc_session()['org_detail']['org_logo'],smc_session()['datatable_header']);
        smc_session()['datatable_message_top'] = Forms::build_print_template('datatable_message_top')['html'];
        smc_session()['datatable_message_bottom'] = Forms::build_print_template('datatable_message_bottom')['html'];
        smc_session()['system_currencies'] = Session::get_system_currencies();
        smc_session()['default_country'] = Session::get_default_country();
        smc_session()['default_city'] = Session::get_default_city();
        smc_session()['datatable_header_temp'] = Session::get_datatable_header_msg();
        smc_session()['last_lock_date'] = Session::get_last_lock_date();
        smc_session()['last_close_vat'] = Session::get_last_close_vat();
    }

    public static function get_system_currencies() {
        $db = DBConnectorFactory::loadDriver();
        $data = array();
        
        $query = $db->query('SELECT * FROM tbl_common_currency ');
        while ($row = $db->assoc($query)) {
            $data[$row['Currency_ID']] = $row;
        }
        //
        $query = $db->query('SELECT * FROM tbl_common_currency ');
        while ($row = $db->assoc($query)) {
            if (!isset($data[$row['Currency_ID']]))
                $data[$row['Currency_ID']] = $row;
        }
        return $data;
    }

    public static function returnCashType() {
        $db = DBConnectorFactory::loadDriver();
        $query = $db->query('SELECT Is_Cash_Default FROM tbl_organization');
        $is_cash_default = $db->assoc($query)['Is_Cash_Default'];
        return $is_cash_default;
    }

    public static function getUserID() {
        return empty(smc_session()['user_logged_id']) ? null : smc_session()['user_logged_id'];
    }

    public static function getSalesAccount() {
        return smc_session()['Sales_Account'];
    }

    public static function getCurrentYearData() {
        $db = DBConnectorFactory::loadDriver();
        $query = $db->query('SELECT * FROM tbl_common_current_year WHERE is_current = 1');
        $current_year = $db->assoc($query);
        return $current_year;
    }

//    public static function getCurrentYearDataActual() {
//        $db = DBConnectorFactory::loadDriver();
//        $query = $db->query('SELECT current_year, current_year_id,start_date,end_date,is_closed FROM tbl_common_current_year_actual WHERE is_current = 1');
//        $current_year = $db->assoc($query);
//        return $current_year;
//    }
    public static function getCurrentYearID($flag = 0) {
        return ($flag == 1 ? smc_session()['current_year_id_actual'] : smc_session()['current_year_id']);
    }

    public static function getCurrentYearRange() {
        return ['start_date' => smc_session()['start_date'], 'end_date' => smc_session()['end_date'], 'year_closed' => smc_session()['year_closed']];
    }

    public static function getActCurrentYearRange() {
        return ['start_date_act' => smc_session()['start_date_act'], 'end_date_act' => smc_session()['end_date_act'], 'year_closed_act' => smc_session()['year_closed_act']];
    }

    public static function getCurrentYear() {
        return smc_session()['current_year'];
    }

    public static function getCurrentYearIDActual() {
        return smc_session()['current_year_id_actual'];
    }

    public static function getCurrentYearActual() {
        return smc_session()['current_year_actual'];
    }

    public static function getStockMethod() {
        $db = DBConnectorFactory::loadDriver();
        $method = $db->query('SELECT Method_ID FROM tbl_stock_default_pricing_method WHERE Default_Method_ID = 1');
        $method_row = $db->assoc($method);
        return $method_row['Method_ID'];
    }

    public static function stock_method() {
        return smc_session()['stock_method'];
    }

    public static function getOrgInvoiceType() {
        //should be edited to get organization invoice type
        return smc_session()['Is_Cash_Default'];
    }

    public static function getUserPreferences() {
        return ((empty(smc_session()) || empty(smc_session()['lang_code'])) ? 'en' : smc_session()['lang_code']);
    }

    public static function getUserDetails() {
        return smc_session()['user_details'];
    }

    public static function getUsername() {
        return ucwords(smc_session()['user_logged_username']);
    }

    public static function getFullName() {
        return smc_session()['user_logged_full_name'];
    }

    public static function getPermissionsObject() {
        static $permission = null;
        if (empty($permission))
            $permission = new Permissions(self::getUserID());
        return $permission;
    }

    public static function isAlive() {
        if (isset(smc_session()['user_logged_id']))
            return true;
        return false;
    }

    public static function kill($id = null) {
        //session_destroy();
        smc_destroy_session();
        if (empty(smc_session()['login_page']) || smc_session()['login_page'] == 'main') {
            header('Refresh: 0; url=' . SITE_LINK . 'smc');
        } else {
            header('Refresh: 0; url=' . SITE_LINK . 'pin');
        }
        exit;
    }

    public static function getYearsInfo() {
        $data = array();
        $db = DBConnectorFactory::loadDriver();
        $query = $db->query('SELECT * FROM tbl_common_current_year ');
        while ($row = $db->assoc($query)) {
            $data[] = $row;
        }
        return $data;
    }

    public static function getOtherAccount() {
        return smc_session()['Other_Account'];
    }

    public static function getCashAccount() {
        return smc_session()['Cash_Account'];
    }

    public static function getShippingAccount() {
        return smc_session()['Shipping_Account'];
    }

    public static function getDepositAccount() {
        return smc_session()['Deposit_Account'];
    }

    public static function getWithDrawalAccount() {
        return smc_session()['Withdrawal_Account'];
    }

    public static function getUserAccounts($user_id) {
        $db = DBConnectorFactory::loadDriver();
        $query = $db->query('SELECT * FROM tbl_users_accounting_accounts WHERE User_ID = "' . $user_id . '"');
        $data = $db->assoc($query);
        return $data;
    }

    public static function getDefaultSetting() {
        $db = DBConnectorFactory::loadDriver();
        $data = array();
        $query = $db->query('SELECT * FROM tbl_default_settings ');
        while ($row = $db->assoc($query)) {
            $data[$row['setting_name']] = $row['setting_value'];
        }
        return $data;
    }

    public static function getGeneralSetting() {
        $db = DBConnectorFactory::loadDriver();
        $data = array();
        $query = $db->query('SELECT * FROM tbl_general_settings ');
        while ($row = $db->assoc($query)) {
            $data[$row['setting_key']] = $row['setting_text'];
        }
        return $data;
    }

    public static function getDefaultOvertimeDay() {
        $status = self::getDefaultSetting()['default_overtime'];
        return $status;
    }

    public static function getAccountSetting() {
        $db = DBConnectorFactory::loadDriver();
        $data = array();
        $query = $db->query('SELECT * FROM tbl_account_setting ');
        while ($row = $db->assoc($query)) {
            $data[$row['acc_setting_name']] = $row['acc_setting_value'];
        }
        return $data;
    }

    public static function getDefaultPricingClassID() {
        $db = DBConnectorFactory::loadDriver();
        $class_id = self::getDefaultSetting()['pricing_class_id'];
        $query = $db->query('select Class_ID,Class_Name,Currency_ID,Currency_Symbol,tax_amount,is_ttc from tbl_pricing_class join tbl_common_currency using(Currency_ID) where Class_ID = "' . $class_id . '"');
        return $db->assoc($query);
    }

    public static function getDefaultDepot() {
        $db = DBConnectorFactory::loadDriver();
        $depot_id = self::getDefaultSetting()['default_depot'];
        $query = $db->query('select Depot_ID,concat(Depot_Code," - ",Depot_Name) as Depot_Name from tbl_stock_depot_warehouse where Depot_ID = "' . $depot_id . '"');
        return $db->assoc($query);
    }

    public static function getDefaultBranch() {
        $db = DBConnectorFactory::loadDriver();
        $branch_id = smc_session()['default_branch_id'];
        $query = $db->query('select branch_id,branch_name,branch_prefix from tbl_organization_branches where branch_id = "' . $branch_id . '"');
        return $db->assoc($query);
    }

    public static function get_default_country() {
        $db = DBConnectorFactory::loadDriver();
        $country_id = smc_session()['default_setting']['default_country_id'];
        $query = $db->query('select * from tbl_all_countries where Country_ID = "' . $country_id . '"');
        return $db->assoc($query);
    }

    public static function get_default_city() {
        $db = DBConnectorFactory::loadDriver();
        $city_id = smc_session()['default_setting']['default_city_id'];
        $query = $db->query('select * from tbl_all_cities where ID = "' . $city_id . '"');
        return $db->assoc($query);
    }

    public static function getLocalCurrency() {
        $db = DBConnectorFactory::loadDriver();
        $query = $db->query('SELECT s.setting_value as local_currency,c.Currency_Symbol,c.Currency_Code,c.currency_round ,c.Currency_Name
            FROM tbl_default_settings s join tbl_common_currency c on c.Currency_ID = s.setting_value where s.setting_name="local_currency"');
        $row = $db->assoc($query);
        return $row;
    }

    public static function getDefaultCurrency() {
        $db = DBConnectorFactory::loadDriver();
        $query = $db->query('SELECT def.Currency_ID,currency.Currency_Name,currency.Currency_Symbol,currency.Currency_Code 
        from tbl_default_currency def
        inner join tbl_common_currency currency on def.Currency_ID = currency.Currency_ID
        WHERE def.id="1"');
        $row = $db->assoc($query);
        return $row;
    }

    public static function getSecondCurrency() {
        $db = DBConnectorFactory::loadDriver();
        $query = $db->query('SELECT s.setting_value as id,c.Currency_Symbol as symbol,
            c.Currency_Code as code,c.currency_round as round,c.Currency_Name as name 
            FROM tbl_default_settings s join tbl_common_currency c on c.Currency_ID = s.setting_value where s.setting_name="second_currency"');
        $row = $db->assoc($query);
        return $row;
    }

    public static function organization_details() {
        $db = DBConnectorFactory::loadDriver();
        $query = $db->query('SELECT
                                       o.Organization_Name,
                                        o.Organization_Phone,
                                        o.org_logo,
                                        o.Organization_Commercial_Registry,
                                        CONCAT(ct.Name,", ",p.Organization_Street) AS Org_Address,
                                        p.Organization_Country
                                    FROM
                                        tbl_organization o
                                    LEFT JOIN
                                        tbl_organization_postal_address p
                                    ON
                                        p.Organization_ID = o.Organization_ID
                                    LEFT JOIN
                                        tbl_all_cities ct
                                    ON
                                        p.Organization_City = ct.ID
                ');
        $row = $db->assoc($query);
        return $row;
    }

    public static function getDefaultNumChildreen() {
        $status = self::getDefaultSetting()['default_school_max_no_childreen'];
        return $status;
    }

    public static function getDefaultValueSchoolGrant() {
        $status = self::getDefaultSetting()['default_school_max_value_grant'];
        return $status;
    }

    public static function getUserGroupIds() {
        $group_ids = '';
        $db = DBConnectorFactory::loadDriver();
        $group = $db->query("SELECT group_id FROM tbl_group_user WHERE FIND_IN_SET('" . smc_session()['user_logged_id'] . "', user_ids)");
        while ($group_row = $db->assoc($group))
            $group_ids .= (empty($group_ids) ? '' : ',') . $group_row['group_id'];
        return $group_ids;
    }

    public static function is_smart_admin() {
        if (!empty(smc_session()['user_logged_username']) && smc_session()['user_logged_username'] == 'admin')
            return true;
        return false;
    }

    public static function get_datatable_header_msg() {
        $db = DBConnectorFactory::loadDriver();
        $data = array();
        $query = $db->query('select template_text from tbl_print_template 
            where template_key="datatable_header_msg" ');
        $row = $db->assoc($query)['template_text'];
        $templates = explode('###', $row);
        foreach ($templates as $template) {
            if (!empty($template)) {
                $temp_text = explode('#%#', $template);
                $data[$temp_text[0]] = $temp_text[1];
            }
        }
        return $data;
    }
    public static function get_last_lock_date(){
        $db = DBConnectorFactory::loadDriver();
        $date ='';
        $query = $db->query('select lock_date from tbl_lock_data order by lock_date desc limit 1');
        $row = $db->assoc($query);
        if(!empty($row))
            $date = $row['lock_date'];
        return $date;
    }
    public static function get_last_close_vat(){
        $db = DBConnectorFactory::loadDriver();
        $date ='';
        $query = $db->query('select Closing_VAT_Date from tbl_accounting_closing_vat order by Closing_VAT_Date desc limit 1');
        $row = $db->assoc($query);
        if(!empty($row))
            $date = $row['Closing_VAT_Date'];
        return $date;
    }
    public static function user_check_login()
    {
        if (isset(smc_session()['user_details']['u_user_shifts_id']) && smc_session()['user_details']['u_user_shifts_id'] != 0) {
            $db = DBConnectorFactory::loadDriver();
            $query = $db->query('SELECT * From tbl_user_shifts Where user_shifts_id = "' . smc_session()['user_details']['u_user_shifts_id'] . '"');
            $row = $db->assoc($query);
            $Working_Day_ID = json_decode($row['Working_Day_ID'], true);
            $Working_Days_Arr = array();

            if (!empty($Working_Day_ID)) {
                foreach ($Working_Day_ID as $Working_Day_Row)
                    $Working_Days_Arr[$Working_Day_Row['day_id']] = array('from' => date('H:i', strtotime($Working_Day_Row['Shift_From'])), 'to' => date('H:i', strtotime($Working_Day_Row['Shift_To'])));
            }
            $today_day_name = date('l');
            $query_day = $db->query('SELECT * FROM `tbl_hrm_working_days` Where Working_Day_Name = "' . $today_day_name . '"');
            $today_day_ID = $db->assoc($query_day)['Working_Day_ID'];
            $from_time = $Working_Days_Arr[$today_day_ID]['from'];
            $to_time = $Working_Days_Arr[$today_day_ID]['to'];
            $curl = curl_init();
    
            if (!empty(smc_session()['default_setting']['default_time_zone'])) {
                $default_timezone_set =smc_session()['default_setting']['default_time_zone'];
            }else{
                $default_timezone_set = 'Asia/Beirut';
            
            }
            // OPTIONS:
            curl_setopt($curl, CURLOPT_URL, 'http://worldtimeapi.org/api/timezone/'.$default_timezone_set);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'APIKEY: 111111111111111111111',
            ));
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            // EXECUTE:
            $result = curl_exec($curl);
            /*if (!$result) {
                die("Connection Failure");
            }*/
            curl_close($curl);
            $make_call = $result;
            $response = json_decode($make_call, true);
            $time = $response['datetime'];
            $time_now = date("H:i",strtotime($time));
            $today = date("Y-m-d",strtotime($time));
            if($today != date("Y-m-d"))
                return false;
            if ($time_now >=  $from_time && $time_now <= $to_time)
                return true;
            else return false;
        } else return true;
    }

}
