<?php

require_once 'common.php';
$__data_type = 'upld';
require_once 'data__db_from_arr_functions.php';
//
ob_start(); //Turn on output buffering, so if there is error to stop echo it..
//

/**
 * here we loop in branch data files that contains invoices,.. and insert them to this main server
 * then return array with the successfully inserted record ids
 */
$succ_ids = array();
$succ_data = array();
$branch_new_path = __DIR__ . '/data_files/branch_new/';
$branch_archive_path = __DIR__ . '/data_files/branch_archive/';
$message = '';
$time_before_few_min = date('Y-m-d H:i:s', strtotime("-2 minutes"));
/**
 * here return after online records [invoices, road customer, ..] inserted locally & here we received the response
 */
if (!empty($_POST['action']) && $_POST['action'] == 'branch_response') {
    //
    if (!empty($_POST['succ_cust_ids'])) {
        $online_customer_count = 0;
        foreach ($_POST['succ_cust_ids'] as $online_cust_id => $offline_cust_id) {
            $db_rslt = $db->query_execute("insert into tbl_pos_customers_sync
                (offline_customer_id,online_customer_id,branch_id,is_sync) 
                values(?,?,?,1) on duplicate key update is_sync=1
                ", [&$offline_cust_id, &$online_cust_id, &$_POST['branch_id']]);
            $online_customer_count += $db->query_result_count($db_rslt);
        }
        $message .= "<br/>Effected Online Customer IDs Only: " . $online_customer_count;
    }
    //
    if (!empty($_POST['succ_invoice_ids'])) {
        foreach ($_POST['succ_invoice_ids'] as $online_inv_id => $offline_inv_id) {
            $db_rslt = $db->query_execute("update tbl_invoices set is_branch_transfer = 1,
                invoice_app_id = ?,app_branch_id=? ,app_user_id = created_logged_id
            where Invoice_ID_Auto =?", [&$offline_inv_id, &$_POST['branch_id'], &$online_inv_id]);
        }
        $message .= "<br/>Effected Online Invoices Only: " . $db->query_result_count($db_rslt);
    }
    //
    if (!empty($_POST['succ_transfer_ids'])) {
        foreach ($_POST['succ_invoice_ids'] as $online_inv_id => $offline_inv_id) {
            $db_rslt = $db->query_execute("update tbl_stock_request set is_branch_transfer = 1,
                invoice_app_id = ?,app_branch_id=? ,app_user_id = created_logged_id
            where Invoice_ID_Auto =?", [&$offline_inv_id, &$_POST['branch_id'], &$online_inv_id]);
        }
        $message .= "<br/>Effected Online Invoices Only: " . $db->query_result_count($db_rslt);
    }

    if (!empty($_POST['succ_transfer_ids'])) {
        $success_transfer_ids = implode(',', array_keys($_POST['succ_transfer_ids']));
        //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 = '{$_POST['branch_id']}' and Request_ID in ({$success_transfer_ids}) ");
        $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($_POST['branch_id']) . ") and Request_ID in ({$success_transfer_ids}) ");
        //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
    //
    if (!empty($_POST['succ_pospond_invoices_ids'])) {
        $db_rslt = $db->query_execute("update tbl_invoices set is_postponed_change = 0
            where Invoice_ID_Auto in (" . $_POST['succ_pospond_invoices_ids'] . ")");
        $message .= "<br/>Effected Online Postponed Invoices Only: " . $db->query_result_count($db_rslt);
    }
    //if (!check_is_debug())
    $message .= ob_get_contents();    //if we want to get the already echo contents of the output buffer
    ob_end_clean(); //to Clean/erase the output buffer and turn off output buffering
    //ob_end_flush(); //Flush/echo the output buffer and turn off output buffering
    //so now we already erase any error/notice/warning and we now can echo the result we want
    if (!empty($message))
        create_sync_log_file('srvr_dt_frm_brnch_rspns', $message, $_POST['branch_id']);
    die(json_encode(array('debug' => $message)));
}

//
fill_trusto_session();

//
$succ_ids['pos_customers_ids'] = array();
$succ_ids['invoices'] = array();
$succ_ids['return'] = array();
$succ_ids['transfers'] = array();
$succ_ids['pay_rec'] = array();
$succ_ids['cash_drawer_login_only'] = array();
$succ_ids['cash_drawer_full'] = array();
$succ_ids['dep_with'] = array();
$succ_ids['delete_log'] = array();
$succ_ids['users'] = array();
$succ_ids['end_shift_day'] = array();
$succ_data['pos_online_customers'] = array();
$succ_data['online_invoices'] = array();
$succ_data['online_pospond_invoices'] = array();
$succ_data['online_transfers'] = array();
//
$tmp_branch_id = empty($_GET['tmp_branch_id']) ? 0 : $_GET['tmp_branch_id'];
//
 foreach (glob($branch_new_path . '*.{smc_brnch_data,cmprs_brnch_data}', GLOB_BRACE) as $file_path) {
     $data = file_get_contents($file_path);
    //if compressed data uncompress it
    if (pathinfo($file_path, PATHINFO_EXTENSION) == 'cmprs_brnch_data')
        $data = gzdecode($data);
    $data = json_decode($data, true);

    if (isset($data['branch_id']) && $tmp_branch_id == $data['branch_id']) {
        $branch_id = $data['branch_id'];
        $message .= "<br/><h1 style='border:1px solid black;padding:5px;margin:5px 0px;'>Branch ID: {$branch_id}</h1><br/>";

        //insert customers first since offline/online customer ids used in insert invoices below
        $tmp_cust_ids = insert_db_frm_arr__pos_customers($branch_id, $data['pos_customers']);
        //important here to use + operator not array merge since need to keep the index
        $succ_ids['pos_customers_ids'] = $succ_ids['pos_customers_ids'] + $tmp_cust_ids;
        //
        $tmp_inv_ids = insert_db_frm_arr__invoices($branch_id, $data['invoices'], $data['onlin_oflin_cstmr_ids']);
        $succ_ids['invoices'] = array_merge($succ_ids['invoices'], $tmp_inv_ids);
        //
        $tmp_ret_ids = insert_db_frm_arr__return_invoices($branch_id, $data['return']);
        $succ_ids['return'] = array_merge($succ_ids['return'], $tmp_ret_ids);
        //
        if (!empty($data['depot_id'])) {
            $depot_id = $data['depot_id'];
            $tmp_trnsfr_ids = insert_db_frm_arr__transfers($branch_id, $depot_id, $data['transfers']);
            $succ_ids['transfers'] = array_merge($succ_ids['transfers'], $tmp_trnsfr_ids);
        }
        //
        $tmp_pay_rec_ids = insert_db_frm_arr__payments_receipts($branch_id, $data['pay_rec'], $data['onlin_oflin_cstmr_ids']);
        $succ_ids['pay_rec'] = array_merge($succ_ids['pay_rec'], $tmp_pay_rec_ids);
        //
        $tmp_dep_with_ids = insert_db_frm_arr__deposit_withdrawal($branch_id, $data['dep_with']);
        $succ_ids['dep_with'] = array_merge($succ_ids['dep_with'], $tmp_dep_with_ids);
        //
        $tmp_cash_drawer_ids = insert_db_frm_arr__cashdrawer($branch_id, $data['cash_drawer']);
        $succ_ids['cash_drawer_full'] = array_merge($succ_ids['cash_drawer_full'], $tmp_cash_drawer_ids['full']);
        $succ_ids['cash_drawer_login_only'] = array_merge($succ_ids['cash_drawer_login_only'], $tmp_cash_drawer_ids['login_only']);
        //
        $tmp_delete_log_ids = insert_db_frm_arr__delete_log($branch_id, $data['delete_log']);
        $succ_ids['delete_log'] = array_merge($succ_ids['delete_log'], $tmp_delete_log_ids);
        //
        $tmp_users_ids = insert_db_frm_arr__users($branch_id, $data['users']);
        $succ_ids['users'] = array_merge($succ_ids['users'], $tmp_users_ids);
        //
        $tmp_shift_ids = insert_db_frm_arr__end_shift_day($branch_id, $data['end_shift_day']);
        $succ_ids['end_shift_day'] = array_merge($succ_ids['end_shift_day'], $tmp_shift_ids);
        //
        //move the file to the archive after inert it successfully
        //we put it here inside condition so if file for another branch, keep it
        rename($file_path, $branch_archive_path . basename($file_path));
    }
}

/**
 * delete old archive files from archive
 */
$all_elements = array();
//since maybe new files like from seconds or minutes created & used for now,..
//we need it to at least keep today file ex: 86400 means delete all filed before 24 hour
$old_time = time() - 86400;
$dir_elements = scandir($branch_archive_path, 0);
if (is_array($dir_elements)) {
    foreach ($dir_elements as $element) {
        if ($element != '.' && $element != '..') {
            $full_element = $branch_archive_path . DIRECTORY_SEPARATOR . $element;
            if (is_writable($full_element) && filemtime($full_element) < $old_time)
                unlink($full_element);
        }
    }
}

/**
 * get online pos customers that are related to the current branch and are not synced
 */

$stmt = $db->query_execute("select * from tbl_pos_customers c 
        left join tbl_pos_customers_sync cs on (cs.online_customer_id = c.customer_id and branch_id = ?)
    where ifnull(is_sync,0) <> 1 ", array($tmp_branch_id));
while ($row = $db->query_fetch($stmt)) {
    $row['online_customer_id'] = $row['customer_id'];
    $row['is_main_transfer'] = 1;
    $succ_data['pos_online_customers'][] = $row;
}
/**
 * get online invoices (orders)
 */
//online_inv_cust_ids array used on branch to get offline customer ids 
$succ_data['online_inv_cust_ids'] = array();
$inv_ids_to_sync = array();
$pay_prefix_arr = array('Cash', 'Check', 'Card', 'shipping');
$stmt = $db->query_execute("SELECT i.*,c.Customer_Name,ac.Account_ID as Customer_Account,i.Account_ID as Account_Code,
    cc.Currency_Symbol as CurrencySymbole,cs.offline_customer_id,i.pos_customer_id FROM tbl_invoices i 
        inner join tbl_customers c on c.Customer_ID = i.Customer_ID 
        inner join tbl_chart_of_accounts ac on ac.main_id = i.Customer_ID and ac.main_type = 'cust' and ac.sub_type='main' 
        inner join tbl_common_currency cc on cc.Currency_ID = i.Invoice_Currency
        left join tbl_pos_customers_sync cs on cs.online_customer_id = i.pos_customer_id and cs.branch_id = i.branch_id
    where is_branch_transfer = '0' and i.branch_id = ? and i.app_branch_id = 0
        and i.date_time < '{$time_before_few_min}' order by Invoice_ID_Auto asc ", array($tmp_branch_id));
$tmp_inv_ids = '';
while ($row = $db->query_fetch($stmt)) {
    foreach ($pay_prefix_arr as $pay_prfx) {
        $row[$pay_prfx . '_Amount'] = 0;
        $row[$pay_prfx . '_Account'] = null;
    }
    //remove number to re-generate it locally at branch
    $inv_ids_to_sync[] = $row['Invoice_ID_Auto'];
    unset($row['invoice_prefix']);
    unset($row['Invoice_ID']);
    unset($row['is_postponed_change']);
    $succ_data['online_invoices'][$row['Invoice_ID_Auto']] = $row;
    if (!empty($row['pos_customer_id']))
        $succ_data['online_inv_cust_ids'][$row['pos_customer_id']] = (empty($row['offline_customer_id']) ? '' : $row['offline_customer_id']);
    $tmp_inv_ids .= (empty($tmp_inv_ids) ? '' : ',') . $row['Invoice_ID_Auto'];
}
//get invoices details | payment, shipping details
if (!empty($tmp_inv_ids)) {
    $tmp_entry_ids = '';
    $stmt = $db->query_execute("SELECT *,Item_Quantity_Current as Item_Quantity,
        Product_Discount as Item_Discount,Product_Net_Price as Item_Price,vat_amount as vat_val
        FROM tbl_invoice_products_details where Invoice_ID_Auto in ({$tmp_inv_ids}) order by Entery_ID asc");
    while ($row = $db->query_fetch($stmt)) {
        $succ_data['online_invoices'][$row['Invoice_ID_Auto']]['Products'][$row['Entery_ID']] = $row;
        $tmp_entry_ids .= (empty($tmp_entry_ids) ? '' : ',') . $row['Entery_ID'];
    }
    if (!empty($tmp_entry_ids)) {
        $stmt = $db->query_execute("select details.Invoice_ID_Auto,criteria.* 
                                    from tbl_invoice_product_criteria criteria
                                    inner join tbl_invoice_products_details details on details.Entery_ID = criteria.Entery_ID
                                    where criteria.Entery_ID IN({$tmp_entry_ids})");
        while ($row = $db->query_fetch($stmt)) {
            $succ_data['online_invoices'][$row['Invoice_ID_Auto']]['Products'][$row['Entery_ID']]['criteria_details'][] = $row;
        }
        $stmt = $db->query_execute("select invoices.Invoice_ID_Auto,options.UOM_ID as uom_id,options.product_id
                ,options.option_quantity as qty,invoices.Invoice_ID_Auto,options.option_id,options.invoice_detail_id 
                                    from tbl_invoice_product_options options
                                    inner join tbl_invoice_products_details details on details.Entery_ID = options.invoice_detail_id
                                    inner join tbl_invoices invoices on invoices.Invoice_ID_Auto = details.Invoice_ID_Auto
                                    where options.invoice_detail_id IN({$tmp_entry_ids})");
        while ($row = $db->query_fetch($stmt)) {
            $succ_data['online_invoices'][$row['Invoice_ID_Auto']]['Products'][$row['invoice_detail_id']]['options_arr'][] = $row;
        }
    }
    //
    $stmt = $db->query_execute("SELECT Transaction_Amount, Transaction_Reference, Account_ID, main_id  FROM tbl_accounting_transactions
        where main_type = 'inv' and Transaction_Reference in ('check', 'cash', 'credit', 'ship') and main_id in ({$tmp_inv_ids}) ");
    while ($row = $db->query_fetch($stmt)) {
        $pay_prfx = 'Cash';
        if ($row['Transaction_Reference'] == 'check')
            $pay_prfx = 'Check';
        elseif ($row['Transaction_Reference'] == 'credit')
            $pay_prfx = 'Card';
        elseif ($row['Transaction_Reference'] == 'ship')
            $pay_prfx = 'shipping';
//        elseif ($row['Transaction_Reference'] == 'inv')
//            $pay_prfx = 'sales';
        //
        $succ_data['online_invoices'][$row['main_id']][$pay_prfx . '_Amount'] = $row['Transaction_Amount'];
        $succ_data['online_invoices'][$row['main_id']][$pay_prfx . '_Account'] = $row['Account_ID'];
    }
}

/**
 * get online transfers
 *  
 * 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
 */

if(isset($_POST['branch_id'])){
$stmt = $db->query_execute("SELECT * FROM tbl_stock_request where Status_ID in (1,3)  and is_main_transfer <> '1'
        and ( (to_branch_id = '{$_POST['branch_id']}' and is_main_transfer <> '2') || (Request_From in (" . get_depot_by_branch($_POST['branch_id']) . ") and is_main_transfer <> '3') )
    order by Request_ID asc");
$tmp_trnsfr_ids = '';
while ($row = $db->query_fetch($stmt)) {
    $succ_data['online_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)) {
        $succ_data['online_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))
            $succ_data['online_transfers'][$row['Request_ID']]['Products'][$row['Entry_ID']]['criteria_details'][] = $row;
    }
}
/**
 * get online online postpond invoices that are related to the current branch and are not synced
 */

$inv_postponed_cond = " ";
if (!empty($inv_ids_to_sync))
    $inv_postponed_cond .= " and Invoice_ID_Auto not in (" . implode(',', $inv_ids_to_sync) . ") ";
$stmt = $db->query_execute("select * from tbl_invoices i where is_postponed_change = '1' and i.branch_id = ? 
    " . $inv_postponed_cond . " and i.date_time < '{$time_before_few_min}' order by Invoice_ID_Auto asc ", array($tmp_branch_id));
while ($row = $db->query_fetch($stmt)) {
    $row['is_main_transfer'] = 1;
    $row['is_postponed_change'] = 0;
    $succ_data['online_pospond_invoices'][] = $row;
}
//

foreach ($succ_ids as $key => $succ_data_arr)
    if ($key != 'pos_customers_ids')    //we need to keep it array
        $succ_ids[$key] = implode(',', $succ_data_arr);
//if (!check_is_debug())
$message .= ob_get_contents();    //if we want to get the already echo contents of the output buffer
ob_end_clean(); //to Clean/erase the output buffer and turn off output buffering
//ob_end_flush(); //Flush/echo the output buffer and turn off output buffering
//so now we already erase any error/notice/warning and we now can echo the result we want
create_sync_log_file('srvr_dt_frm_brnch', $message, $tmp_branch_id);

die(json_encode(array('succ_ids' => $succ_ids, 'debug' => $message, 'succ_data' => $succ_data)));
//
