<?php
$db = $GLOBALS['db'];
global $app_list_strings;

if (!isset($_GET['source'])) {
    $_GET['source'] = '';
}
if (!isset($_GET['date'])) {
    $_GET['date'] = date('Y-m', strtotime('-1 month'));
}

if (!isset($_GET['type'])) {
    $_GET['type'] = '';
}

if (isset($_GET['ajax'])) {
    switch ($_GET['ajax']) {
        case 'exportToRewizor':
            exportToRewizor($_GET['source'], $_GET['date'], $_GET['type']);
            break;
    }
} else {
    show();
}
function show()
{
    $smarty = new Sugar_Smarty();
    $inv = getInvoices($_GET['source'], $_GET['date'], $_GET['type']);
    $total_netto = 0;
    $total_brutto = 0;
    $total_vat = 0;
    foreach ($inv as $invoice) {
        $total_netto += $invoice['total_netto'];
        $total_brutto += $invoice['total_brutto'];
        $total_vat += $invoice['total_vat'];
    }
    // format totals with 2 decimals
    $total_netto = number_format($total_netto, 2, '.', '');
    $total_brutto = number_format($total_brutto, 2, '.', '');
    $total_vat = number_format($total_vat, 2, '.', '');
    $smarty->assign("data", $inv);
    $smarty->assign("totalNetto", $total_netto);
    $smarty->assign("totalBrutto", $total_brutto);
    $smarty->assign("totalVat", $total_vat);
    $smarty->assign("sources", getSources());
    $smarty->assign("source", $_GET['source']);
    $smarty->assign("dates", getDates());
    $smarty->assign("date", $_GET['date']);
    $smarty->assign("type", $_GET['type']);
    echo $smarty->display(getcwd() . '/modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/ecommerceInvoicesListView.tpl');
}

function getInvoices($source, $date, $type)
{
    $db = $GLOBALS['db'];
    if ($source =='') $source = '%';
    $date .= '%';
    $query = "SELECT i.*, wz.document_no AS wz_document_no, wz.id AS wz_id FROM ecommerce_invoices AS i 
        LEFT JOIN ecmstockdocouts AS wz on wz.id = i.ecmstockdocout_id 
    ";
    $query .= " WHERE i.origin LIKE '$source' AND i.register_date LIKE '$date'";
    if ($type !='') {
        $query.=" AND i.type='$type'";
    }
    $query .= " ORDER BY i.register_date";
    $result = $db->query($query);
    $invoices = array();
    while ($row = $db->fetchByAssoc($result)) {
        // format date in row register_date from mysql format into d.m.Y
        $row['register_date'] = date('d.m.Y', strtotime($row['register_date']));
        $row['sell_date'] = date('d.m.Y', strtotime($row['sell_date']));
        $row['products'] = getInvoicProducts($row['id']);
        $invoices[] = $row;
    }
    return $invoices;
}
function getInvoicProducts($invoiceId) {
    $db = $GLOBALS['db'];
    $query = sprintf("SELECT p.id, p.code, p.name, ip.price_netto, ip.price_brutto, ip.quantity, ip.code as ecommerce_code, ip.vat_value FROM ecommerce_invoices_products as ip INNER JOIN ecmproducts AS p ON ip.ecmproduct_id = p.id WHERE ip.invoice_id='%s'", $invoiceId);
    $result = $db->query($query);
    $products = array();
    while ($row = $db->fetchByAssoc($result)) {
        $row['vat_value'] =str_replace(".00","",$row['vat_value']);
        $products[] = $row;
    }
    return $products;
}
function getDates()
{
    $dates = array();
    $date = new DateTime();
    $dates[] = $date->format('Y-m');
    while ($date->format('Y-m') != '2024-01') {
        $date->modify('-1 month');
        $dates[] = $date->format('Y-m');
    }
    return $dates;
}
function getSources() {
    $db = $GLOBALS['db'];
    $sources = array();
    $res = $db->query("SELECT DISTINCT origin FROM ecommerce_invoices");
    while ($row = $db->fetchByAssoc($res)) {
        $sources[]= $row['origin'];
    }
    return $sources;
}

function exportToRewizor($source, $date, $type)
{
    $smarty = new Sugar_Smarty();
    $invoices = getInvoices($source, $date, $type);
    foreach ($invoices as &$i) {
        $i['register_date'] = date("Ymd000000",strtotime($i['register_date']));
        $i['sell_date'] = date("Ymd000000",strtotime($i['sell_date']));
        // create 20 characters length hash from parent_name
        $i['parent_hash'] = substr(md5($i['parent_name']), 0, 20);
        $i['parent_short_name'] = substr($i['parent_name'], 0, 40);
        if ($type == 'correcting') {
            $db = $GLOBALS['db'];
            $fv = $db->fetchByAssoc($db->query(sprintf("SELECT document_no, register_date FROM ecommerce_invoices WHERE id='%s'", $i['corrected_invoice_id'])));
            $i['corrected_document_no'] = $fv['document_no'];
            $i['corrected_register_date'] = date("Ymd000000",strtotime(date('d.m.Y', strtotime($fv['register_date']))));
        }
    }

    $smarty->assign("data", $invoices);
    if ($type == 'normal') {
    $result =  $smarty->display(getcwd() . '/modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/rewizor.tpl');
    } else {
        $result =  $smarty->display(getcwd() . '/modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/rewizor_fvkor.tpl');
    }
    // encode result as ansi
    echo $result;
    //echo mb_convert_encoding($result, 'ANSI', 'UTF-8');
}

function brecho($var)
{
    echo '<pre>';
    print_r($var);
    echo '</pre>';
}