<?php

require_once 'common.php';
//
$stngs_stmt = $db->query_execute("SELECT setting_value FROM `tbl_default_settings` WHERE `setting_name` LIKE 'server_hotel_url' ");
$settings_row = $db->query_fetch($stngs_stmt);
$server_hotel_url = $settings_row['setting_value'];
//
$old_external_charges = array();
$new_external_charges = array();
//
$stmt = $db->query_execute("select Invoice_ID_Auto as invoice_id_auto, reservation_id,Invoice_Net_Total as amount, 
                        concat_ws('',invoice_prefix,Invoice_ID) as note, Invoice_Date as date, Invoice_Currency, is_hotel_sync
                    from tbl_invoices  
                        where ((reservation_id is not null  and is_hotel_sync = 0) or (is_hotel_sync = 2)) ");
while ($row = $db->query_fetch($stmt)) {
    if (!empty($row['reservation_id']))
        $new_external_charges[] = $row;
    if ($row['is_hotel_sync'] == 2)
        $old_external_charges[] = $row['invoice_id_auto'];
}
if (!empty($new_external_charges) || !empty($old_external_charges)) {
    $data = sync_get_contents($server_hotel_url . '/api/data_from_pos.php', array('old_external_charges' => $old_external_charges,
        'new_external_charges' => $new_external_charges));
    $result_arr = json_decode($data, true);
    $inv_ids = "";
    if (!empty($result_arr['data_old_invoice_ids_string']))
        $inv_ids = $result_arr['data_old_invoice_ids_string'];
    if (!empty($result_arr['data_new_invoice_ids']))
        $inv_ids .= (empty($inv_ids) ? "" : ",") . implode(",", $result_arr['data_new_invoice_ids']);
    if (!empty($inv_ids)) {
        $db->query_execute("update tbl_invoices set is_hotel_sync = if(isNULL(reservation_id), 0, 1) where Invoice_ID_Auto in ({$inv_ids}) ".(!empty($result_arr['err_new_invoice_ids']) ? ' and Invoice_ID_Auto not in ('.implode(",",$result_arr['err_new_invoice_ids']).') ' : '')." ");
    }
    echo '<pre>';
    print_r($result_arr);
} else {
    die('No data to sync');
}