<?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';
require_once 'data__db_to_arr_functions.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
}
//
$data = array();
//
$data['branch_id'] = $branch_id;
$data['depot_id'] = $depot_id;
$data['__data_type'] = 'rstr';
$data['__time_before'] = null;
//get invoices
fill_arr_frm_db__invoices($data);
//get return invoices
fill_arr_frm_db__return_invoices($data);
//get transfers, only confirmed [status 3] one and not yet transfered 
fill_arr_frm_db__transfers($data);
//get payments/receipt 
fill_arr_frm_db__payments_receipts($data);
//get deposit/withdrawal
fill_arr_frm_db__deposit_withdrawal($data);
//get cash drawer data
fill_arr_frm_db__cashdrawer($data);
//get pos customers
fill_arr_frm_db__pos_customers($data);
/**
 * zip the data and send the path back to the branch
 */
$file_name = $branch_id . '____' . date('Y-m-d_H-i-s__') . uniqid();
//
$zip = new ZipArchive();
$zip_file = $tmp_dir . $file_name . '.zip';
if ($zip->open($data_dir . $zip_file, ZipArchive::CREATE) !== true) {
    create_sync_log_file('brnch_dt_frm_srvr__error', $sql_err, $branch_id);
    die("Could not Create Zip File.");
}
$zip->addFromString('json_array_data.smc_srvr_rstr_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_rstr_to_brnch', "Zip File '{$zip_file}' send successfully to branch.", $branch_id);
die(json_encode(array('zip_file' => $zip_file)));
//