<?php

/**
 * this script will call a script to main server that will fill an sql file containing products, customers,..
 * and will return the path for that file, so here we get the file using ftp, and import it and after that
 * re-call same script in the server to delete that created file.
 */
require_once 'common.php';
require_once 'branch__data_from_server_functions.php';
//
if (!check_ping_ip())
    die('Error, server is offline');
//
$branch_id = get_settings('default_branch_id');
if (empty($branch_id))
    die('Error, Undefined Branch ID!');
//
$depot_id = get_settings('default_depot');
if (empty($depot_id))
    die('Error, Undefined Default Depot ID!');
//
$server_data_link = extend_debug_url(SERVER_trusto_URL . "sync/server__data_to_branch.php?branch_id={$branch_id}&depot_id={$depot_id}");
//
$result_arr = sync_get_contents($server_data_link);
$result_arr = json_decode($result_arr, true);
if (empty($result_arr['zip_file']))
    die('Error, No Zip File Path!');
//
$local_zip_file = __DIR__ . '/data_files/temp_dir/' . basename($result_arr['zip_file']);
server_ftp_get_file($result_arr['zip_file'], $local_zip_file);
server_ftp_close();
//remove the zip file from server, no need for it anymore
$result_msg = sync_get_contents($server_data_link . "&is_finish_zip=1&path=" . urlencode($result_arr['zip_file']));
//

$zip = new ZipArchive();
if ($zip->open($local_zip_file) === true) {
//    for ($i = 0; $i < $zip->numFiles; $i++)
//        $filename = $zip->getNameIndex($i);
    //since there is only one file we can get it's name from index zero
 
    $tmp_sql_file = dirname($local_zip_file) . '/sql_tables_data.smc_srvr_data';    //$zip->getNameIndex(0);
    $tmp_data_file = dirname($local_zip_file) . '/json_array_data.smc_srvr_data';    //$zip->getNameIndex(1);
    $zip->extractTo(dirname($local_zip_file));
    $zip->close();
    
    //
    if (file_exists($tmp_sql_file) && filesize($tmp_sql_file) > 0) {
        //to check mysql options: https://dev.mysql.com/doc/refman/5.7/en/mysql-command-options.html
        exec('(' . my_escapeshellarg(get_mysql_path()) . ' -h ' . my_escapeshellarg(DB_HOST) . ' -u ' . my_escapeshellarg(DB_USER) . ' --password=' . my_escapeshellarg(DB_PASS) . ' --force --one-database ' . my_escapeshellarg(DB_NAME) . ' < ' . my_escapeshellarg($tmp_sql_file) . ') 2>&1', $output, $return_var);
        $db->query_execute("update tbl_common_users set Employee_ID = NULL, is_main_transfer = 1 ");
    }
    //

    $succ_ids = array();
    $data = json_decode(file_get_contents($tmp_data_file), true);
    //
//    $succ_ids['transfers'] = array();
//    if (!empty($data['transfers'])) {
//        fill_trusto_session();
//        $tmp_trnsfr_ids = insert_transfers($branch_id, $depot_id, $data['transfers']);
//        $succ_ids['transfers'] = array_merge($succ_ids['transfers'], $tmp_trnsfr_ids);
//    }
//    if (!empty($data['customer_contacts'])) {
//        fill_trusto_session();
//        $tmp_customer_contact_ids = insert_customer_contacts($branch_id, $data['customer_contacts']);
//        $succ_ids['customer_contacts'] = array_merge($succ_ids['customer_contacts'], $tmp_customer_contact_ids);
//    }
 
    foreach ($succ_ids as $key => $succ_data_arr)

        $succ_ids[$key] = implode(',', $succ_data_arr);
    sync_get_contents($server_data_link . "&is_finish_data=1", array('succ_ids' => $succ_ids));
    //remove the zip & sql file no need for them anymore
    unlink($local_zip_file);
    unlink($tmp_sql_file);
    unlink($tmp_data_file);
    if ($return_var != 0) {   //0 is ok
        $sql_err = 'Mysql Import Error, ' . implode("<br/>", $output);
        create_sync_log_file('brnch_dt_frm_srvr__error', $sql_err, $branch_id);
        die($sql_err);
    }
    
    //here the table product filled with the quantity from the main server whole/all warehouses so we must fill only current warehouses quantities
    $db->query_execute("update tbl_stock_products pro
            left join (SELECT `Location_Product_ID` as pro_id, sum(`Product_Depot_Quantity`) as pro_qty FROM `tbl_stock_product_location` group by `Location_Product_ID`) as pro_qty
                on pro.Product_ID = pro_qty.pro_id
            set pro.Product_Quantity = (if(isNull(pro_id), 0, pro_qty)) ");
}
//
$msg = 'Data Exported from the server received by the branch and imported successfully..';
create_sync_log_file('brnch_dt_frm_srvr', $msg, $branch_id);
die($msg);
//