<?php

/**
 * this script will get data from main server like customers, accounts, products, ..
 * fill them in a file then send the  path to the branch, so the branch get the file using
 * ftp import it and after that call here back with the path to delete that file..
 */
require_once 'common.php';
//
$tmp_dir = '/temp_dir/';
$data_dir = __DIR__ . '/data_files';
//
if (empty($_GET['branch_id']))
    die('Error, No Branch Set!');
$branch_id = $_GET['branch_id'];
//
if (empty($_GET['depot_id']))
    die('Error, No Depot Set!');
$depot_id = $_GET['depot_id'];
//

if (isset($_GET['is_finish_zip']) && $_GET['is_finish_zip'] == '1') {
    if (!empty($_GET['path']) && substr($_GET['path'], 0, mb_strlen($tmp_dir)) == $tmp_dir && file_exists($data_dir . $_GET['path']))
        unlink($data_dir . $_GET['path']);
    die('Done, File Deleted Successfully..');   //must exit and not continue to below
}
//
//if (isset($_GET['is_finish_data']) && $_GET['is_finish_data'] == '1') {
//    if (!empty($_POST['succ_ids'])) {
//        if (!empty($_POST['succ_ids']['transfers'])) {
//            //if the depot id is [tranfer_from] and is_main_transfer is:: [if 3 set it 1] [if 0 set it 2]  
//            //if the depot id is [tranfer_to] and is_main_transfer is:: [if 2 set it 1] [if 0 set it 3]  
//            $db->query_execute("update tbl_stock_request set is_main_transfer = if(is_main_transfer = '0', '2', '1') where 
//                to_branch_id = '{$branch_id}' and Request_ID in ({$_POST['succ_ids']['transfers']}) ");
//            $db->query_execute("update tbl_stock_request set is_main_transfer = if(is_main_transfer = '0', '3', '1') where 
//                Request_From in (" . get_depot_by_branch($branch_id) . ") and Request_ID in ({$_POST['succ_ids']['transfers']}) ");
//            //after update above if already from and to is for same branch then make it is main transfer 1
//            /* $db->query_execute("update tbl_stock_request set is_main_transfer = '1' where is_main_transfer = '2'
//              and Request_From in (" . get_depot_by_branch($branch_id) . ") and Request_ID in ({$_POST['succ_ids']['transfers']}) ");
//              $db->query_execute("update tbl_stock_request set is_main_transfer = '1' where is_main_transfer = '3'
//              and is_main_transfer = '1' and Request_ID in ({$_POST['succ_ids']['transfers']}) "); */
//        }
//    }
//    die('Done, Data Updated Successfully..');   //must exit and not continue to below
//}
//
$data = array();
$data['branch_id'] = $branch_id;
$data['depot_id'] = $depot_id;
/**
 * here we get all data related to customers, suppliers, accounts, proucts, prices, currencies,..
 */
$db_tables_to_export = array('tbl_chart_of_accounts', 'tbl_common_currency', 'tbl_currencies_rate'
    , 'tbl_customers', 'tbl_default_currency', 'tbl_item_price_by_classes', 'tbl_pricing_class'
    , 'tbl_products_link', 'tbl_product_options', 'tbl_product_option_details', 'tbl_product_cat'
    , 'tbl_stock_products', 'tbl_stock_suppliers', 'tbl_stock_uom'
    , 'tbl_uom_conversions', 'tbl_cash_drawer_accounts', 'tbl_common_roles', 'tbl_common_role_permission'
    , 'tbl_common_permission', 'tbl_common_users', 'tbl_users_accounting_accounts'
    , 'tbl_organization_branches', 'tbl_stock_depot_warehouse', 'tbl_product_shelf'
    , 'tbl_product_criteria', 'tbl_product_criteria_detail', 'tbl_printers', 'tbl_accounting_jobs'
    , 'tbl_projects', 'tbl_customer_supplier_contacts'
);
//
if (empty($db_tables_to_export))
    die('Error, No Tables to Export!');
//
$db_tables_str = null;
foreach ($db_tables_to_export as $db_table)
    $db_tables_str .= ' ' . my_escapeshellarg($db_table);
//
$file_name = $branch_id . '____' . date('Y-m-d_H-i-s__') . uniqid();
$tmp_sql_file = sys_get_temp_dir() . "/{$file_name}.smc_srvr_data";
exec('(' . my_escapeshellarg(get_mysqldump_path()) . ' -h ' . my_escapeshellarg(DB_HOST) . ' -u ' . my_escapeshellarg(DB_USER) . ' --password=' . my_escapeshellarg(DB_PASS) . ' ' . my_escapeshellarg(DB_NAME) . ' ' . $db_tables_str . ' --add-drop-table > ' . my_escapeshellarg($tmp_sql_file) . ') 2>&1', $output, $return_var);
if ($return_var != 0) {   //0 is ok
    $sql_msg = 'MysqlDump Export Error, ' . implode("<br/>", $output);
    create_sync_log_file('srvr_dt_to_brnch__error', $sql_msg, $branch_id);
    die($sql_msg);
}
//for mysql 5.7 we can just add for above exec mysqldump flag: --skip-definer  to remove definer
//for linux we can direclty from above exec: mysqldump ... | sed -e 's/DEFINER=`[^`]*`@`[^`]*`/ /g' > file.sql
$tmp_sql_contents = file_get_contents($tmp_sql_file);
//definer can be ex: DEFINER=`user`@`localhost` or DEFINER= 'user'@'%'
//for that here first after definer check ' *' means match space between zero & infinity then '=' equal character then optional space
//then search for ' or ` then any character different then ' and different ` then '@' character then same as before '@'
$tmp_sql_contents = preg_replace("/DEFINER *= *[`'][^`']*[`']@[`'][^`']*[`']/sim", '', $tmp_sql_contents);
//The /*!40014 ... */ syntax is a conditional comment that will be executed on MySQL 4.0.14 and later
$tmp_sql_contents = " /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; " . $tmp_sql_contents . " /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; ";
file_put_contents($tmp_sql_file, $tmp_sql_contents);
unset($tmp_sql_contents);
/**
 * get confirm request [transfers] that want to send them to the branches
 * if created directly here in the server initially the is_main_transfer variable will be 0
 * if it is moved only to the [transfer_from] branch or already created there and sync to here it will be 2
 * if created on this server and moved only to [transfer_to] branch it will be 3
 * if it is moved to both side [transfer_from, transfer_to] branches then it will be 1
 */
//$data['transfers'] = array();
//$stmt = $db->query_execute("SELECT * FROM tbl_stock_request where Status_ID = 3  and is_main_transfer <> '1'
//        and ( (to_branch_id = '{$branch_id}' and is_main_transfer <> '2') || (Request_From in (" . get_depot_by_branch($branch_id) . ") and is_main_transfer <> '3') )
//    order by Request_ID asc");
//$tmp_trnsfr_ids = '';
//while ($row = $db->query_fetch($stmt)) {
//    $data['transfers'][$row['Request_ID']] = $row;
//    $tmp_trnsfr_ids .= (empty($tmp_trnsfr_ids) ? '' : ',') . $row['Request_ID'];
//}
////get request details
//if (!empty($tmp_trnsfr_ids)) {
//    $tmp_entry_ids = '';
//    $stmt = $db->query_execute("SELECT Request_ID, Product_ID,Request_UOM as UOM_ID,Current_Quantity as Request_Qty FROM tbl_stock_request_details where Request_ID in ({$tmp_trnsfr_ids}) order by Entry_ID asc");
//    while ($row = $db->query_fetch($stmt)) {
//        $data['transfers'][$row['Request_ID']]['Products'][$row['Entry_ID']] = $row;
//        $tmp_entry_ids .= (empty($tmp_entry_ids) ? '' : ',') . $row['Entry_ID'];
//    }
//    if (!empty($tmp_entry_ids)) {
//        $stmt = $db->query_execute("select criteria.*, details.Request_ID from tbl_request_product_criteria criteria
//            inner join tbl_stock_request_details details on details.Entry_ID = criteria.Entry_ID
//        where criteria.Entry_ID IN({$tmp_entry_ids})");
//        while ($row = $db->query_fetch($stmt))
//            $data['transfers'][$row['Request_ID']]['Products'][$row['Entry_ID']]['criteria_details'][] = $row;
//    }
//}

//$data['customer_contacts'] = array();
//$stmt = $db->query_execute("SELECT * FROM tbl_customer_supplier_contacts where type_id = 1");
//while ($row = $db->query_fetch($stmt)) {
//    $data['customer_contacts'][$row['main_id']][] = $row;
//}
/**
 * zip the sql and other files and send the path back to the branch
 */
$zip = new ZipArchive();
$zip_file = $tmp_dir . $file_name . '.zip';
if ($zip->open($data_dir . $zip_file, ZipArchive::CREATE) !== true) {
    $zip_msg = 'Could not Create Zip File.';
    create_sync_log_file('srvr_dt_to_brnch__error', $zip_msg, $branch_id);
    die($zip_msg);
}
$zip->addFile($tmp_sql_file, 'sql_tables_data.smc_srvr_data');
$zip->addFromString('json_array_data.smc_srvr_data', json_encode($data));
$zip->close();
//we send the path starting from the current directory, not full path since as ftp we must start from ftp user home dir.
create_sync_log_file('srvr_dt_to_brnch', "Zip File '{$zip_file}' send successfully to branch.", $branch_id);
die(json_encode(array('zip_file' => $zip_file)));
//
