<?php
if(empty($_GET['is_danger']))
    exit;
//set_time_limit(0);
//ignore_user_abort(true);    //bypass browser abort
////ini_set('memory_limit', '512M');

$start = microtime(true);
require_once 'sync/common.php';
fill_trusto_session();
//
$products_arr = array();
$stmt = $db->query_execute("SELECT Product_ID from tbl_stock_products");
while ($row = $db->query_fetch($stmt))
    $products_arr[$row['Product_ID']] = $row['Product_ID'];
//$customers_arr = array();
//$stmt = $db->query_execute("SELECT Customer_ID from tbl_customers");
//while ($row = $db->query_fetch($stmt))
//    $customers_arr[$row['Customer_ID']] = $row['Customer_ID'];
$max_customer_id = 26622;
/**
 * get invoices
 */
$invoices = array();
$pay_prefix_arr = array('Cash', 'Check', 'Card', 'shipping', 'sales');
$stmt = $db->query_execute("SELECT i.*,c.Customer_ID as Customer_ID, c.Customer_Name,ac.Account_ID as Customer_Account,
    cc.Currency_Symbol as CurrencySymbole FROM tbl_invoices i 
        inner join tbl_customers c on c.Customer_ID = concat('\"',FLOOR(RAND() * {$max_customer_id}),'\"') /*i.Customer_ID*/
        inner join tbl_chart_of_accounts ac on ac.main_id = c.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
    order by RAND() limit 50");
$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;
    }
    $row['Invoice_Date'] = date('Y-m-d', strtotime(mt_rand(-100, 0).' day'));
    $invoices[$row['Invoice_ID_Auto']] = $row;
    $tmp_inv_ids .= (empty($tmp_inv_ids) ? '' : ',') . $row['Invoice_ID_Auto'];
}
//get invoices details | payment, shipping details
if (!empty($tmp_inv_ids)) {
    $stmt = $db->query_execute("SELECT Product_ID,UOM_ID,Item_Quantity_Current as Item_Quantity,
        Product_Discount as Item_Discount,Product_Net_Price as Item_Price,Product_Total_Price,Invoice_ID_Auto,vat_percent,vat_amount as vat_val
        FROM tbl_invoice_products_details where Invoice_ID_Auto in ({$tmp_inv_ids}) order by Entery_ID asc");
    $filled_inv_ids = array();
    while ($row = $db->query_fetch($stmt)) {
        $invoices[$row['Invoice_ID_Auto']]['Products'][] = $row;
        $rand_prices = array(750, 150, 2250, 77508250, 4500, 6800, 75150, 4750, 1250, 250, 500, 31250, 5000);
        if ($row['Invoice_ID_Auto'] % 5 == 0 && $row['Invoice_ID_Auto'] % 6 == 0 && !isset($filled_inv_ids[$row['Invoice_ID_Auto']])) {
            $filled_inv_ids[$row['Invoice_ID_Auto']] = $row['Invoice_ID_Auto'];
            for ($i = 0; $i < mt_rand(0, 500); $i++) {
                $tmp_row = array(
                    'Product_ID' => array_rand($products_arr), 'UOM_ID' => 1, 'Item_Quantity' => mt_rand(1, 50), 'Item_Discount' => 0
                    , 'Item_Price' => array_rand($rand_prices), 'Invoice_ID_Auto' => $row['Invoice_ID_Auto'], 'vat_percent' => 0, 'vat_val' => 0
                );
                $tmp_row['Product_Total_Price'] = $tmp_row['Item_Price'] * $tmp_row['Item_Quantity'];
                $invoices[$row['Invoice_ID_Auto']]['Products'][] = $tmp_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','inv') 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';
        //
        $invoices[$row['main_id']][$pay_prfx . '_Amount'] = $row['Transaction_Amount'];
        $invoices[$row['main_id']][$pay_prfx . '_Account'] = $row['Account_ID'];
    }
}

$succ_inv_nb = 0;
$inv_nb_arr = array();
//echo "<pre>" . print_r($invoices, true);exit;
insert_invoices($invoices);

//insert invoices and return the success invoice ids
function insert_invoices($invoices) {
    global $db, $succ_inv_nb, $inv_nb_arr;
    if (!empty($invoices)) {
        $invoice = new Invoice;
        //start transaction
        foreach ($invoices as $inv_id => $inv_row) {
            if (empty($inv_row['Products']))
                continue;
            if (!isset($inv_nb_arr[$inv_row['invoice_prefix']]))
                $inv_nb_arr[$inv_row['invoice_prefix']] = $invoice->getMaxInvoice($inv_row['invoice_prefix'], $is_actual = 0);
            else
                $inv_nb_arr[$inv_row['invoice_prefix']] ++;
            $inv_row['Invoice_Currency_Rate'] = $inv_row['current_rate'];
            $inv_row['shipping'] = $inv_row['Invoice_Shipping'];
            $inv_row['shipping_account'] = $inv_row['shipping_Account'];
            $inv_row['Account_Code'] = $inv_row['sales_Account'];
            $inv_row['Invoice_Number'] = $inv_nb_arr[$inv_row['invoice_prefix']];
            $inv_row['is_data_collector'] = 0;
            $inv_row['pending_status'] = 4;
//            $inv_row['app_user_id'] = $inv_row['Logged_ID'];
//            $inv_row['invoice_app_id'] = $inv_row['Invoice_ID_Auto'];
//            $check_invoice = $db->query_execute('select Invoice_ID_Auto from tbl_invoices where invoice_app_id = ? and app_user_id = ?', array($inv_id, $inv_row['Logged_ID']));
//            if ($db->query_result_count($check_invoice) == 0) {
            $insert = $invoice->setdata($inv_row)->insertSalesInvoice();
            if (is_numeric($insert[0]))
                $succ_inv_nb++;
//                $succ_ids[] = $inv_id;
//            } else
//                $succ_ids[] = $inv_id;
            else
                echo print_r($insert, true);
        }
        //end transaction
    }
//    return $succ_ids;
}

$result = '<br/><b>{' . $_GET['i'] . '}</b> | Start: ' . date('Y-m-d H:i:s', $start) . '<br/>End: ' . date('Y-m-d H:i:s') . ' === Time In Minutes: ' . round(((microtime(true) - $start) / 60), 2);
$result .= '<br/>Done.. ' . $succ_inv_nb . ' Invoices Inserted..<br/>';
$result .= '====================================================================================<br/>';
echo $result;
file_put_contents("uploads\\tmp\\test_dummy_data.html", $result, FILE_APPEND);
echo '<script>setTimeout(function(){ window.location = "' . basename(__FILE__) . '?is_danger=1&i=' . (empty($_GET['i']) ? 1 : $_GET['i'] + 1) . '"; }, 5000)</script>';
