<?php

/**
 * this script will send to main server the invoices, .. as ftp file then call a script on main server that
 * will insert the uploaded ftp file to the server database and return the success inserted ids so here
 * in the branch we update them to is send to main.
 */
require_once 'common.php';
require_once 'data__db_to_arr_functions.php';
require_once 'branch__data_to_server_functions.php';
//
if (!check_ping_ip())
    die('Error, server is offline');
//
$data = array();
//
$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!');
//
$delete_after_sync = get_settings('activate_delete_records_after_sync');
$data['branch_id'] = $branch_id;
$data['depot_id'] = $depot_id;
$data['__data_type'] = 'upld';
$data['__time_before'] = date('Y-m-d H:i:s', strtotime("-2 minutes"));
//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);
//get delete log
fill_arr_frm_db__delete_log($data);
//get updated users
fill_arr_frm_db__users($data);
//get end of shift/day
fill_arr_frm_db__end_shift_day($data);
/**
 * save the data in temp file and upload it ftp to main server
 */
$file_ext = 'smc_brnch_data';
$content_data = json_encode($data);
//if long file then compress it
if (mb_strlen($content_data) > 100000) {
    $file_ext = 'cmprs_brnch_data';
    $content_data = gzencode($content_data, 9);
}
$temp_file = sys_get_temp_dir() . '/' . uniqid() . microtime(true) . '.' . $file_ext;
file_put_contents($temp_file, $content_data);
$ftp_file_name = $branch_id . '____' . date('Y_m_d_H_i_s__') . uniqid() . '.' . $file_ext;
server_ftp_put_file($temp_file, '/branch_new', $ftp_file_name);
server_ftp_close();
unlink($temp_file);
$message = "";
//run a script in main server to insert that data which will return the successfull inserted id's
//and move the file from branch_new to branch_archive folder so we don't execute it again.
$tmp_result_arr = sync_get_contents(extend_debug_url(SERVER_trusto_URL . 'sync/server__data_from_branch.php?tmp_branch_id=' . $branch_id));
$result_arr = json_decode($tmp_result_arr, true);
if (is_null($result_arr))    //if error in return json encode
    $message .= "<div><h1>JSON Error::</h1>{$tmp_result_arr}</div><hr/>";
if (!empty($result_arr['succ_ids'])) {
//    fill_trusto_session();
    if (!empty($result_arr['succ_ids']['invoices'])) {
        $db_rslt = $db->query_execute("update tbl_invoices set is_main_transfer = '1' where Invoice_ID_Auto in ({$result_arr['succ_ids']['invoices']}) ");
        $message .= "<br/>Effected Sales Invoices: " . $db->query_result_count($db_rslt);
    }
    if (!empty($result_arr['succ_ids']['return'])) {
        $db_rslt = $db->query_execute("update tbl_accounting_return_invoices set is_main_transfer = '1' where Return_Invoice_ID in ({$result_arr['succ_ids']['return']}) ");
        $message .= "<br/>Effected Return Invoices: " . $db->query_result_count($db_rslt);
    }
    if (!empty($result_arr['succ_ids']['transfers'])) {
        $db_rslt = $db->query_execute("update tbl_stock_request set is_main_transfer = '1' where Request_ID in ({$result_arr['succ_ids']['transfers']}) ");
        $message .= "<br/>Effected Transfers: " . $db->query_result_count($db_rslt);
    }
//    if (!empty($result_arr['succ_ids']['pay_rec'])) {
//        $db_rslt = $db->query_execute("update tbl_payments_on_accounts set is_main_transfer = '1' where Payment_Auto_ID in ({$result_arr['succ_ids']['pay_rec']}) ");
//        $message .= "<br/>Effected Payment/Receipt: " . $db->query_result_count($db_rslt);
//    }
    if (!empty($result_arr['succ_ids']['pay_rec'])) {
        $db_rslt = $db->query_execute("update tbl_payment_receipt set is_main_transfer = '1' where pay_rec_id in ({$result_arr['succ_ids']['pay_rec']}) ");
        $message .= "<br/>Effected Payment/Receipt: " . $db->query_result_count($db_rslt);
    }
    if (!empty($result_arr['succ_ids']['dep_with'])) {
        $db_rslt = $db->query_execute("update tbl_accounting_bank_deposit_withdrawal set is_main_transfer = '1' where Deposit_WithDrawal_ID in ({$result_arr['succ_ids']['dep_with']}) ");
        $message .= "<br/>Effected Deposit/Withdrawal: " . $db->query_result_count($db_rslt);
    }
    if (!empty($result_arr['succ_ids']['cash_drawer_full'])) {
        $db_rslt = $db->query_execute("update tbl_cash_drawer_amount set is_main_transfer = '2' where cash_drawer_amount_id in ({$result_arr['succ_ids']['cash_drawer_full']}) ");
        $message .= "<br/>Effected Cash Drawer: " . $db->query_result_count($db_rslt);
    }
    if (!empty($result_arr['succ_ids']['cash_drawer_login_only'])) {
        $db_rslt = $db->query_execute("update tbl_cash_drawer_amount set is_main_transfer = '1' where cash_drawer_amount_id in ({$result_arr['succ_ids']['cash_drawer_login_only']}) ");
        $message .= "<br/>Effected Cash Drwaer Login Only: " . $db->query_result_count($db_rslt);
    }
    if (!empty($result_arr['succ_ids']['pos_customers_ids'])) {
        $inserted_pos_cust_count = 0;
        foreach ($result_arr['succ_ids']['pos_customers_ids'] as $offline_cust_id => $online_cust_id) {
            $db_rslt = $db->query_execute("update tbl_pos_customers set is_main_transfer = 1, online_customer_id = ? 
                where customer_id = ? ", array($online_cust_id, $offline_cust_id));
            $inserted_pos_cust_count += $db->query_result_count($db_rslt);
        }
        $message .= "<br/>Effected Pos Customer IDs: " . $inserted_pos_cust_count;
    }
    if (!empty($result_arr['succ_ids']['delete_log'])) {
        $db_rslt = $db->query_execute("update tbl_main_log set is_main_transfer = '1' where log_id in ({$result_arr['succ_ids']['delete_log']}) ");
        $message .= "<br/>Effected Delete Log: " . $db->query_result_count($db_rslt);
    }
    if (!empty($result_arr['succ_ids']['users'])) {
        $db_rslt = $db->query_execute("update tbl_common_users set is_main_transfer = '1' where User_ID in ({$result_arr['succ_ids']['users']}) ");
        $message .= "<br/>Effected Users: " . $db->query_result_count($db_rslt);
    }
    if (!empty($result_arr['succ_ids']['end_shift_day'])) {
        $db_rslt = $db->query_execute("update tbl_end_of_shift set is_main_transfer = '1' where shift_id in ({$result_arr['succ_ids']['end_shift_day']}) ");
        $message .= "<br/>Effected end of shift/day: " . $db->query_result_count($db_rslt);
    }
}
//delete needed records if activated depend on specific criteria like sync, ..
if ($delete_after_sync == 1) {
    //      
    $delete_inv = delete_invoices();
    if (!empty($delete_inv))
        $message .= "<br/>Effected Sales Invoices: " . implode('<br/>', $delete_inv);
    //
    $delete_rtrn = delete_returns();
    if (!empty($delete_rtrn))
        $message .= "<br/>Effected Return Invoices: " . implode('<br/>', $delete_rtrn);
    //
    $delete_rec = delete_receipts();
    if (!empty($delete_rec))
        $message .= "<br/>Effected Payment/Receipt: " . implode('<br/>', $delete_rec);
    //
    $delete_dp_wd = delete_dep_with();
    if (!empty($delete_dp_wd))
        $message .= "<br/>Effected Deposit/Withdrawal: " . implode('<br/>', $delete_dp_wd);
}

/**
 * here we insert at branch the records that inserted online like online invoices, road customers [inserted online or edited, created at different branch]
 */
$succ_ids = array();
$succ_ids['pos_customers'] = array();
$succ_ids['online_invoices'] = array();
$succ_ids['online_transfers'] = array();
$succ_ids['online_pospond_invoices'] = array();
if (!empty($result_arr['succ_data'])) {
    fill_trusto_session();
    if (!empty($result_arr['succ_data']['pos_online_customers'])) {
        $tmp_cust_ids = insert_online_customers($branch_id, $result_arr['succ_data']['pos_online_customers']);
        $succ_ids['pos_customers'] = $tmp_cust_ids;
    }
    if ($result_arr['succ_data']['online_invoices']) {
        $tmp_inv_ids = insert_online_invoices($branch_id, $result_arr['succ_data']['online_invoices'], $result_arr['succ_data']['online_inv_cust_ids']);
        $succ_ids['online_invoices'] = $tmp_inv_ids;
    }
    if ($result_arr['succ_data']['online_transfers']) {
        $tmp_trans_ids = insert_online_transfers($branch_id, $result_arr['succ_data']['online_transfers']);
        $succ_ids['online_transfers'] = $tmp_trans_ids;
    }
    if ($result_arr['succ_data']['online_pospond_invoices']) {
        $tmp_inv_ids = insert_online_pospond_invoices($branch_id, $result_arr['succ_data']['online_pospond_invoices']);
        $succ_ids['online_pospond_invoices'] = array_merge($succ_ids['online_pospond_invoices'], $tmp_inv_ids);
    }
}
//$online_invoices_str = '';
//if (!empty($succ_ids['online_invoices']))
//    $online_invoices_str = implode(',', $succ_ids['online_invoices']);
$online_pospond_invoices_str = '';
if (!empty($succ_ids['online_pospond_invoices']))
    $online_pospond_invoices_str = implode(',', $succ_ids['online_pospond_invoices']);
//
$tmp_online_result_arr = sync_get_contents(extend_debug_url(SERVER_trusto_URL . 'sync/server__data_from_branch.php'), array(
    'action' => 'branch_response'
    , 'succ_cust_ids' => $succ_ids['pos_customers']
    , 'succ_pospond_invoices_ids' => $online_pospond_invoices_str
//    , 'succ_invoice_ids' => $online_invoices_str
    , 'succ_invoice_ids' => $succ_ids['online_invoices']
    , 'succ_transfer_ids' => $succ_ids['online_transfers']
    , 'branch_id' => $branch_id)
);
$online_result_arr = json_decode($tmp_online_result_arr, true);
if (is_null($online_result_arr))    //if error in return json encode
    $message .= "<div><h1>JSON Error::</h1>{$tmp_online_result_arr}</div><hr/>";
/**
 * 
 */
echo 'Data Exported from this Branch & Send to server and imported successfully..<br/><br/>';
if (check_is_debug())
    echo $message . "<br/><br/>";
//if (check_is_debug())
$debug_msg = "<hr/><pre>Debug:<br/>{$result_arr['debug']}<hr/>{$online_result_arr['debug']}<br></pre><hr/><hr/>";
create_sync_log_file('brnch_dt_to_srvr', $message . "<br/><br/><hr/>" . $debug_msg, $branch_id);
die($debug_msg);
//