<?php

require_once 'init.php';
require_once dirname(__DIR__) . '/autoload.smart.php';
//require dirname(__DIR__) . '/Includes/constants.php';
require_once LIBS_PATH . 'Common/db_standalone_class.php';
/** @property db_standalone $db */
$db = new db_standalone(null, DB_HOST, DB_USER, DB_PASS, DB_NAME);

/**
 * ==========================> Functions
 */
function server_ftp_connection($is_close_conn = false) {
    static $connection_id = null;
    if ($is_close_conn) {
        if (!is_null($connection_id)) {
            ftp_close($connection_id);
            $connection_id = null;
        }
        return null;
    }
    //
    if (is_null($connection_id)) {
        //here problem if server is ssl in some internet connections may get error when ftp get or put
        //like:  ftp_get(): TYPE is now 8-bit binary, for that we try first ftp ssl connect if gave error
        //at login then we try the normal connect..
        static $is_ssl = null;
        if (is_null($is_ssl))
            $is_ssl = function_exists('ftp_ssl_connect') ? true : false;
        if ($is_ssl)
            $connection_id = ftp_ssl_connect(FTP_SERVER);
        else
            $connection_id = ftp_connect(FTP_SERVER);
        //
        if (!$connection_id)
            die("Can't connect to FTP Server.<br/>");
        else {
            $ftp_is_login = @ftp_login($connection_id, FTP_USER, FTP_PASSWORD);
            if (!$ftp_is_login) {
                //here if login error it maybe beacuse wrong user/pass or if it is ssl connect 
                //error maybe like:  ftp_login(): SSL/TLS authentication not allowed 
                //for the if is_ssl then we try use non ssl connect
                if ($is_ssl) {
                    $is_ssl = false;
                    $connection_id = null;
                    return server_ftp_connection($is_close_conn);   //call it again after free connection
                }
                die("Login wrong for FTP Server.<br/>");
            } else {
                ftp_pasv($connection_id, true);
//                //no ftp check exist dir function, so we user chdir to check if exist or not 
//                if (!@ftp_chdir($connection_id, $ftp_remote_folder)) {
//                    ftp_mkdir($connection_id, $ftp_remote_folder);
//                    ftp_chdir($connection_id, $ftp_remote_folder);
//                }
                //return chdir to the root since we already in put below we put full path
                ftp_chdir($connection_id, '/');
            }
        }
    }
    return $connection_id;
}

//
function server_ftp_put_file($local_file, $ftp_dir, $ftp_file_name = null) {
    if (empty($ftp_file_name))
        $ftp_file_name = basename($local_file);
    if (!ftp_put(server_ftp_connection(), $ftp_dir . '/' . $ftp_file_name, $local_file, FTP_BINARY))
        die("Error Upload File to FTP Server.<br/>");
}

//
function server_ftp_get_file($ftp_file, $local_file) {
    if (!ftp_get(server_ftp_connection(), $local_file, $ftp_file, FTP_BINARY))
        die("Error Download File from FTP Server.<br/>");
}

//
function server_ftp_close() {
    server_ftp_connection($is_close_conn = true);
}

//
function get_settings($key) {
    global $db;
    static $setting_arr = null;
    if (is_null($setting_arr)) {
        $setting_arr = array();
        $stmt = $db->query_execute("select * from tbl_default_settings");
        while ($row = $db->query_fetch($stmt))
            $setting_arr[$row['setting_name']] = $row['setting_value'];
    }
    return (isset($setting_arr[$key]) ? $setting_arr[$key] : null);
}

//
function check_is_windows() {
    return strtoupper(substr(PHP_OS/* php_uname('s') */, 0, 3)) === 'WIN';
}

//
function my_escapeshellarg($arg) {
    //we don't use escapeshellarg as it also remove %, ! in windows
    //when an argument send it must be escaped this character for example since used in specific charactes: $ & ! \ [ ] < > `
    //so we must escape this character using '\' or quote them using " [double quote] in windows and ' [single quote] in unix
    if (check_is_windows())
        return '"' . str_replace('"', '\"', $arg) . '"';
    return "'" . str_replace("'", "\'", $arg) . "'";
}

//
function get_mysql_path() {
    return get_mysqldump_path(null, 'mysql');
}

//
function get_mysqldump_path($check_path = null, $exe_name = null) {
    if (empty($exe_name))
        $exe_name = 'mysqldump';
    $mysqldump_path = $exe_name;
    if (check_is_windows()) {
        if (strtolower(pathinfo($exe_name, PATHINFO_EXTENSION)) != 'exe')
            $exe_name .= '.exe';
        if (is_null($check_path))
            $check_path = dirname(dirname(__DIR__));
        $tmp_mysqldump_path = $check_path . '/mysql/bin/' . $exe_name;
        $is_found = false;
        if (file_exists($tmp_mysqldump_path)) { //for xampp
            $mysqldump_path = $tmp_mysqldump_path;
            $is_found = true;
        } else {   //for wamp ex: C:\wamp\bin\mysql\mysql5.6.17\bin
            $tmp_mysqldump_path = $check_path . '/bin/mysql/';
            if (file_exists($tmp_mysqldump_path) && is_dir($tmp_mysqldump_path)) {
                $dirs = glob($tmp_mysqldump_path . '*', GLOB_ONLYDIR);
                foreach ($dirs as $dir) {
                    $tmp_mysqldump_path = $dir . '/bin/' . $exe_name;
                    if (substr(basename($dir), 0, 5) == 'mysql' && file_exists($tmp_mysqldump_path)) {
                        $mysqldump_path = $tmp_mysqldump_path;
                        $is_found = true;
                        break;
                    }
                }
            }
        }
        if (!$is_found) {
            $tmp_check_path = dirname($check_path);
            if ($tmp_check_path != $check_path)
                $mysqldump_path = get_mysqldump_path($tmp_check_path, $exe_name);
        }
    }
    return $mysqldump_path;
}

//we need this ft. as needed like logged id, current year and others inside some method
function fill_trusto_session() {
    static $is_trusto_session = null;
    if (!is_null($is_trusto_session))
        return;
    //if already logged in, do nothing
    if (Session::isAlive() === true)
        return;
    //we simulate the call of login() inside 'libs\Common\Person.php'
    $usr_row = Person::get_login_row(" and User_Name like 'admin' ");

    if (empty($usr_row))
        die("Admin User Not Exist!");
    $row =$usr_row;  //convert index from assoc strings to numerical numebrs

    $serialized_permission = new Permissions($usr_row['User_ID'], true);

    $row['permissions'] = $serialized_permission->getPermissions();
    //
    Session::create($row);
    $is_trusto_session = true;
}

function check_ping_ip($ip = FTP_SERVER, $sec_timeout = 5) {
    $is_ping = CommonFunctions::check_ping_ip($ip, $sec_timeout);
    if (!$is_ping)
        return false;
    if ($ip == FTP_SERVER) //if we are just check online server
        return (sync_get_contents(SERVER_trusto_URL . "sync/init.php?smc__check_sync_conn=1") == 'ok');
    return $is_ping;
}

//
function get_depot_by_branch($branch_id) {
    global $db;
    $data = array();
    $stmt = $db->query_execute("SELECT Depot_ID from tbl_stock_depot_warehouse where branch_id = '" . $branch_id . "'");
    while ($dpt_row = $db->query_fetch($stmt)) {
        $data[] = $dpt_row['Depot_ID'];
    }
    return implode(',', $data);
}

//
function check_is_debug() {
    return (isset($_REQUEST['is_debug']) && $_REQUEST['is_debug'] == 1);
}

//
function extend_debug_url($url) {
    return $url . (check_is_debug() ? ((strpos($url, '?') === false ? '?' : '&') . 'is_debug=1') : '');
}

//
function create_sync_log_file($nm_prfx, $data, $branch_id = null) {
    $log_dir = upload_path . 'sync_log';
    if (!file_exists($log_dir))
        mkdir($log_dir);
    $log_dir .= '/' . date('Y_m_d');
    if (!file_exists($log_dir))
        mkdir($log_dir);
    file_put_contents($log_dir . '/log__' . (empty($branch_id) ? '' : ("id{$branch_id}__")) . $nm_prfx . '__' . date('Y_m_d__H_i_s') . '.html', $data);
}

function sync_get_contents($url, $post_arr = array()) {
    $postdata = '';
    if (!empty($post_arr))
        $postdata = http_build_query($post_arr);
    //
    $header_arr = array(
        'Content-type: application/x-www-form-urlencoded',
        'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng',
        'Accept-Language: en-US,en;q=0.9,ar;q=0.8',
        'Cache-Control: max-age=0',
        'Connection: keep-alive',
        'Host: ' . parse_url($url, PHP_URL_HOST),
        'Origin: ' . parse_url($url, PHP_URL_HOST),
        'Upgrade-Insecure-Requests: 1',
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'
    );
    //some times in some local server when try file get contents on large data or time it return failed for that if curl is activated we use it first
    if (extension_loaded('curl')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if (!empty($postdata)) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header_arr);
        $contents = curl_exec($ch);
        curl_close($ch);
    } else { //ini_get('allow_url_fopen')
        $opts = array('http' =>
            array(
                'method' => (empty($postdata) ? 'GET' : 'POST'),
                'header' => implode("\r\n", $header_arr),
                'content' => $postdata
            )
        );
        $context = stream_context_create($opts);
        $contents = file_get_contents($url, false, $context);
    }
    return $contents;
}
