<?php

ini_set('memory_limit', '-1');
ini_set('max_execution_time', '-1');

if (!defined('sugarEntry') || !sugarEntry)
    die('Not A Valid Entry Point');

function getStocksList() {
    $db = $GLOBALS['db'];
    $queryStocks = "SELECT id, name FROM ecmstocks WHERE deleted= 0";
    $rowsStocks = $db->query($queryStocks);
    $stocks = array();
    while ($rowStocks = $db->fetchByAssoc($rowsStocks)) {
        $stocks [$rowStocks ["id"]] = $rowStocks ["name"];
    }
    return $stocks;
}

function getStockIndexList() {
    $db = $GLOBALS['db'];
    $queryStockIndex = "SELECT id, name FROM ecmproductstockindexs;";
    $rowsStockIndex = $db->query($queryStockIndex);
    $StockIndexList = array();
    while ($rowStocksIndex = $db->fetchByAssoc($rowsStockIndex)) {
        $StockIndexList [$rowStocksIndex ["id"]] = $rowStocksIndex ["name"];
    }
    return $StockIndexList;
}

function getKartotekaMaterialowaQuery($unknow) {
    if (!isset($unknow) || count($unknow) == 0 || (in_array('', $unknow))) {
        
    } else {
        if (in_array('NULL', $unknow) && count($unknow) == 1) {
            $query .= " AND doc.ecmproductstockindex_id IS NULL ";
        } else if (in_array('NULL', $unknow) && count($unknow) > 1) {
            $queryUnknow = " (";
            foreach ($unknow as $key => $value) {
                if ($value != 'NULL') {
                    $queryUnknow .= "'" . $value . "',";
                }
            }
            $queryUnknow = rtrim($queryUnknow, ",");
            $queryUnknow .= ") ";
            $query .= " AND (doc.ecmproductstockindex_id IS NULL OR doc.ecmproductstockindex_id IN " . $queryUnknow . ") ";
        } else {
            $queryUnknow = " (";
            foreach ($unknow as $key => $value) {
                $queryUnknow .= "'" . $value . "',";
            }
            $queryUnknow = rtrim($queryUnknow, ",");
            $queryUnknow .= ") ";
            $query .= " AND doc.ecmproductstockindex_id IN " . $queryUnknow . " ";
        }
    }
    return $query;
}

// Tworzy kawałek zapytania dla magazynów
// np: ('magazyn1','magazyn2',...)
function getStockQuery($stockSelected) {
    if (isset($stockSelected) && count($stockSelected) > 0) {
        $queryStockSelected = " (";
        foreach ($stockSelected as $key => $value) {
            $queryStockSelected .= "'" . $value . "',";
        }
        $queryStockSelected = rtrim($queryStockSelected, ",");
        $queryStockSelected .= ") ";
    } else {
        $stockList = getStocksList();
        $queryStockSelected = " (";
        foreach ($stockList as $key => $value) {
            $queryStockSelected .= "'" . $key . "',";
        }
        $queryStockSelected = rtrim($queryStockSelected, ",");
        $queryStockSelected .= ") ";
    }
    return $queryStockSelected;
}

function getDataRwPwKs($documentsSelected, $stockSelected, $date_from, $date_to, $stockIndexSelected) {
    if (!isset($documentsSelected) && isset($stockSelected) && isset($date_from) && isset($date_to)) {
        return null;
    }
    $db = $GLOBALS['db'];
    global $app_list_strings;
    $documentsList = array(// dokumenty
        'EcmStockDocInsideOuts' => 'RW',
        'EcmStockDocInsideIns' => 'PW',
        'EcmStockDocMoves' => 'MM',
        'EcmStockDocCorrects' => 'KS',
        'EcmStockDocIns' => 'PZ',
        'EcmStockDocOuts' => 'WZ',
        'EcmInvoiceOuts' => "FK",
        'EcmReceipts' => 'Paragon'
    );

    $query = "SELECT "
            . "doc.id AS docid, "
            . "doc.ecmproductstockindex_name AS docstockindex, "
            . "doc.name AS docname, "
            . "DATE_FORMAT(doc.register_date,'%d.%m.%Y') AS docregister_date, "
            . "doc.document_no AS docdocument_no, "
            . "doc.stock_id AS docstock_id, "
            . "o.type AS otype, "
            . "o.quantity AS oquantity, "
            . "o.price AS oprice, "
            . "o.product_id AS oproduct_id, "
            . "o.product_name AS oproduct_name, "
            . "o.product_code as oproduct_code, "
            . "p.unit_id as punit_id  "
            . "FROM "
            . "ecmstockoperations o, "
            . "ecmproducts p, "
            . "" . strtolower($documentsSelected) . " doc "
            . "WHERE o.parent_id = doc.id "
            . "AND p.id = o.product_id "
            . "AND doc.deleted=0 "
            . "AND o.deleted=0 "
            . "AND doc.stock_id IN " . getStockQuery($stockSelected) . " "
            . "AND  doc.register_date >='" . $date_from . "' "
            . "AND doc.register_date <= '" . $date_to . "'";
    $query .= getKartotekaMaterialowaQuery($stockIndexSelected);
    $query .= " ORDER BY doc.register_date, o.counter, o.product_code, o.product_name, doc.name";
    $resultRows = $db->query($query);
    $stockList = getStocksList();
    while ($row = $db->fetchByAssoc($resultRows)) {
        $data['doc'][$row['docid']]['wartosc'] += $row['oquantity'] * $row['oprice'];
        $data['prod'][$row['oproduct_id']]['wartosc'] += $row['oquantity'] * $row['oprice'];
        $data['prod'][$row['oproduct_id']]['ilosc'] += $row['oquantity'];
        $data['prod'][$row['oproduct_id']]['kod'] = $row['oproduct_code'];
        $data['prod'][$row['oproduct_id']]['nazwa'] = $row['oproduct_name'];
        $data['prod'][$row['oproduct_id']]['id'] = $row['oproduct_id'];
        $data['prod'][$row['oproduct_id']]['data'] = $row['docregister_date'];
        $data['prod'][$row['oproduct_id']]['numer'] = $row['docdocument_no'];
        $data['prod'][$row['oproduct_id']]['kartoteka'] = $row['docstockindex'];
        $data['prod'][$row['oproduct_id']]['jm'] = $app_list_strings['ecmproducts_unit_dom'][$row['punit_id']];
        $data['doc'][$row['docid']]['magazyn'] = $stockList[$row['docstock_id']];
        $data['doc'][$row['docid']]['nazwa'] = $row['docname'];
        $data['doc'][$row['docid']]['typ'] = $documentsList[$documentsSelected];
        $data['doc'][$row['docid']]['id'] = $row['docid'];
        $data['doc'][$row['docid']]['data'] = $row['docregister_date'];
        $data['doc'][$row['docid']]['numer'] = $row['docdocument_no'];
        $data['doc'][$row['docid']]['kartoteka'] = $row['docstockindex'];
    }
    return $data;
}

function getDataMm($documentsSelected, $stockSelected, $date_from, $date_to, $mmSelected) {
    if (!isset($documentsSelected) && isset($stockSelected) && isset($date_from) && isset($date_to)) {
        return null;
    }
    $db = $GLOBALS['db'];
    global $app_list_strings;
    $documentsList = array(// dokumenty
        'EcmStockDocInsideOuts' => 'RW',
        'EcmStockDocInsideIns' => 'PW',
        'EcmStockDocMoves' => 'MM',
        'EcmStockDocCorrects' => 'KS',
        'EcmStockDocIns' => 'PZ',
        'EcmStockDocOuts' => 'WZ',
        'EcmInvoiceOuts' => "FK",
        'EcmReceipts' => 'Paragon'
    );

    $query = "SELECT "
            . "doc.id AS docid, "
            . "doc.ecmproductstockindex_name AS docstockindex, "
            . "doc.name AS docname, "
            . "DATE_FORMAT(doc.register_date,'%d.%m.%Y') AS docregister_date, "
            . "doc.document_no AS docdocument_no, "
            . "doc.stock_in_id AS docstock_in_id,"
            . "doc.stock_out_id AS docstock_id,"
            . "o.type AS otype, "
            . "o.quantity AS oquantity, "
            . "o.price AS oprice, "
            . "o.product_id AS oproduct_id, "
            . "o.product_name AS oproduct_name, "
            . "o.product_code as oproduct_code, "
            . "p.unit_id as punit_id  "
            . "FROM "
            . "ecmstockoperations o, "
            . "ecmproducts p, "
            . "" . strtolower($documentsSelected) . " doc "
            . "WHERE o.parent_id = doc.id "
            . "AND p.id = o.product_id "
            . "AND doc.deleted=0 "
            . "AND o.deleted=0 "
            . "AND doc.stock_out_id IN " . getStockQuery($stockSelected) . " "
            . "AND doc.stock_in_id IN " . getStockQuery($mmSelected) . " "
            . "AND  doc.register_date >='" . $date_from . "' "
            . "AND doc.register_date <= '" . $date_to . "'"
            . "AND o.type=0 "
            . "ORDER BY doc.register_date, o.counter, o.product_code, o.product_name, doc.name ";
    $resultRows = $db->query($query);

    $stockList = getStocksList();
    while ($row = $db->fetchByAssoc($resultRows)) {
        $data['doc'][$row['docid']]['wartosc'] += $row['oquantity'] * $row['oprice'];
        $data['prod'][$row['oproduct_id']]['wartosc'] += $row['oquantity'] * $row['oprice'];
        $data['prod'][$row['oproduct_id']]['ilosc'] += $row['oquantity'];
        $data['prod'][$row['oproduct_id']]['kod'] = $row['oproduct_code'];
        $data['prod'][$row['oproduct_id']]['nazwa'] = $row['oproduct_name'];
        $data['prod'][$row['oproduct_id']]['id'] = $row['oproduct_id'];
        $data['prod'][$row['oproduct_id']]['data'] = $row['docregister_date'];
        $data['prod'][$row['oproduct_id']]['numer'] = $row['docdocument_no'];
        $data['prod'][$row['oproduct_id']]['kartoteka'] = $row['docstockindex'];
        $data['prod'][$row['oproduct_id']]['jm'] = $app_list_strings['ecmproducts_unit_dom'][$row['punit_id']];
        $data['doc'][$row['docid']]['magazyn'] = $stockList[$row['docstock_id']];
        $data['doc'][$row['docid']]['magazynIn'] = $stockList[$row['docstock_in_id']];
        $data['doc'][$row['docid']]['nazwa'] = $row['docname'];
        $data['doc'][$row['docid']]['typ'] = $documentsList[$documentsSelected];
        $data['doc'][$row['docid']]['id'] = $row['docid'];
        $data['doc'][$row['docid']]['data'] = $row['docregister_date'];
        $data['doc'][$row['docid']]['numer'] = $row['docdocument_no'];
        $data['doc'][$row['docid']]['kartoteka'] = $row['docstockindex'];
    }
    return $data;
}

function getDataPzWzFk($documentsSelected, $stockSelected, $date_from, $date_to, $accountId, $accountName) {
    if (!isset($documentsSelected) && isset($stockSelected) && isset($date_from) && isset($date_to)) {
        return null;
    }
    $db = $GLOBALS['db'];
    global $app_list_strings;
    $documentsList = array(// dokumenty
        'EcmStockDocInsideOuts' => 'RW',
        'EcmStockDocInsideIns' => 'PW',
        'EcmStockDocMoves' => 'MM',
        'EcmStockDocCorrects' => 'KS',
        'EcmStockDocIns' => 'PZ',
        'EcmStockDocOuts' => 'WZ',
        'EcmInvoiceOuts' => "FK",
        'EcmReceipts' => 'Paragon'
    );

    $query = "SELECT "
            . "doc.id AS docid, "
            . "doc.name AS docname, "
            . "DATE_FORMAT(doc.register_date,'%d.%m.%Y') AS docregister_date, "
            . "doc.document_no AS docdocument_no, "
            . "doc.stock_id AS docstock_id, "
            . "o.type AS otype, "
            . "o.quantity AS oquantity, "
            . "o.price AS oprice, "
            . "o.product_id AS oproduct_id, "
            . "o.product_name AS oproduct_name, "
            . "o.product_code as oproduct_code, "
            . "doc.parent_id as docparent_id, "
            . "doc.parent_name as docparent_name, "
            . "p.unit_id as punit_id  "
            . "FROM "
            . "ecmstockoperations o, "
            . "ecmproducts p, "
            . "" . strtolower($documentsSelected) . " doc "
            . "WHERE o.parent_id = doc.id "
            . "AND p.id = o.product_id "
            . "AND doc.deleted=0 "
            . "AND o.deleted=0 ";
			if($documentsSelected=='EcmInvoiceOuts'){
				  $query .=  " AND doc.canceled=0 ";
			}
    if (isset($accountId) && strlen($accountId) > 0) {
        $query .= "AND doc.parent_id='" . $accountId . "' ";
    }
    $query.= "AND doc.stock_id IN " . getStockQuery($stockSelected) . " "
            . "AND  doc.register_date >='" . $date_from . "' "
            . "AND doc.register_date <= '" . $date_to . "'";
    $query .= " ORDER BY doc.register_date, o.counter, o.product_code, o.product_name, doc.name";
    $resultRows = $db->query($query);
    $stockList = getStocksList();
    while ($row = $db->fetchByAssoc($resultRows)) {

        $data['prod'][$row['oproduct_id']]['ilosc'] += $row['oquantity'];
        $data['prod'][$row['oproduct_id']]['kod'] = $row['oproduct_code'];
        $data['prod'][$row['oproduct_id']]['nazwa'] = $row['oproduct_name'];
        $data['prod'][$row['oproduct_id']]['id'] = $row['oproduct_id'];
        $data['prod'][$row['oproduct_id']]['data'] = $row['docregister_date'];
        $data['prod'][$row['oproduct_id']]['otype'] = $row['otype'];
        $data['prod'][$row['oproduct_id']]['numer'] = $row['docdocument_no'];
        $data['prod'][$row['oproduct_id']]['jm'] = $app_list_strings['ecmproducts_unit_dom'][$row['punit_id']];
        $data['doc'][$row['docid']]['magazyn'] = $stockList[$row['docstock_id']];
        $data['doc'][$row['docid']]['accountId'] = $row['docparent_id'];
        $data['doc'][$row['docid']]['accountNazwa'] = $row['docparent_name'];
        $data['doc'][$row['docid']]['nazwa'] = $row['docname'];
        $data['doc'][$row['docid']]['typ'] = $documentsList[$documentsSelected];
        $data['doc'][$row['docid']]['id'] = $row['docid'];
        $data['doc'][$row['docid']]['data'] = $row['docregister_date'];
        $data['doc'][$row['docid']]['numer'] = $row['docdocument_no'];
        if ($documentsSelected == 'EcmInvoiceOuts' && $row['otype'] == '0') {
            $data['doc'][$row['docid']]['wartosc'] -= $row['oquantity'] * $row['oprice'];
            $data['prod'][$row['oproduct_id']]['wartosc'] -= $row['oquantity'] * $row['oprice'];
			$data['doc'][$row['docid']]['typ'] = 'KF';
        } else {
            $data['doc'][$row['docid']]['wartosc'] += $row['oquantity'] * $row['oprice'];
            $data['prod'][$row['oproduct_id']]['wartosc'] += $row['oquantity'] * $row['oprice'];
            
        }
    }
    return $data;
}

// ***************************************************************************
//Pobieranie danych z filtrowania
if ($_REQUEST['date_from'] == '') {
    $_REQUEST['date_from'] = date('01.m.Y');
} else {
    $date_from = date('Y-m-d', strtotime($_REQUEST['date_from']));
}
if ($_REQUEST['date_to'] == '') {
    $_REQUEST['date_to'] = date('t.m.Y');
} else {
    $date_to = date('Y-m-d', strtotime($_REQUEST['date_to']));
}
$stockSelected = $_REQUEST['stockSelected'];
$documentsSelected = $_REQUEST['documentsSelected'];
$stockIndexSelected = $_REQUEST['stockIndexSelected'];
$viewSelected = $_REQUEST['viewSelected'];
$mmSelected = $_REQUEST['mmSelected'];
$accountId = $_REQUEST['accountId'];
$accountName = $_REQUEST['accountName'];
//Przygotowywanie innych potrzebnych zmiennych
$data = array();
$datatmp = array();
$db = $GLOBALS['db'];
global $mod_strings, $app_list_strings;
$stockList = getStocksList(); // magazyny
$stockIndexList = getStockIndexList(); //Kartoteki Materialowe
$documentsList = array(// dokumenty
    'EcmStockDocInsideOuts' => 'RW',
    'EcmStockDocInsideIns' => 'PW',
    'EcmStockDocMoves' => 'MM',
    'EcmStockDocCorrects' => 'KS',
    'EcmStockDocIns' => 'PZ',
    'EcmStockDocOuts' => 'WZ',
    'EcmInvoiceOuts' => "FK",
    'EcmReceipts' => 'Paragon'
);
$viewList = array(//Lista widokow
    'documents' => 'Dokumenty',
    'positions' => 'Pozycje',
);


//Pobieranie i przetwarzanie danych
if ($documentsSelected == 'EcmStockDocInsideOuts' || $documentsSelected == 'EcmStockDocInsideIns' || $documentsSelected == 'EcmStockDocCorrects') {
    $data = getDataRwPwKs($documentsSelected, $stockSelected, $date_from, $date_to, $stockIndexSelected);
} elseif ($documentsSelected == 'EcmStockDocMoves') {
    $data = getDataMm($documentsSelected, $stockSelected, $date_from, $date_to, $mmSelected);
} elseif ($documentsSelected == 'EcmStockDocIns' || $documentsSelected == 'EcmStockDocOuts' || $documentsSelected == 'EcmInvoiceOuts' || $documentsSelected == 'EcmReceipts') {
    $data = getDataPzWzFk($documentsSelected, $stockSelected, $date_from, $date_to, $accountId, $accountName);
}

// create & execute smarty
$smarty = new Sugar_Smarty ();
$smarty->assign("MOD", $mod_strings);
$smarty->assign("DATA", $data);
$smarty->assign("stocksList", $stockList);
$smarty->assign("stockSelected", $stockSelected);
$smarty->assign("documentList", $documentsList);
$smarty->assign("documentSelected", $documentsSelected);
$smarty->assign("stockIndexList", $stockIndexList);
$smarty->assign("stockIndexSelected", $stockIndexSelected);
$smarty->assign("viewList", $viewList);
$smarty->assign("viewSelected", $viewSelected);
$smarty->assign("date_from", $_REQUEST['date_from']);
$smarty->assign("date_to", $_REQUEST['date_to']);
$smarty->assign("aktualnaData", date("d.m.Y"));
$smarty->assign("mmSelected", $mmSelected);
$smarty->assign("accountId", $accountId);
$smarty->assign("accountName", htmlentities($accountName));
// Eksport do PDF
if ($_REQUEST['toPDF'] == '1') {
    if ($documentsSelected == 'EcmStockDocInsideOuts' || $documentsSelected == 'EcmStockDocInsideIns' || $documentsSelected == 'EcmStockDocCorrects') {
        $txt = 'Kartoteka materiaĆowa: ';
        if (isset($stockIndexSelected)) {
            if (count($stockIndexSelected) == count($stockIndexList) + 1) {
                $txt .= 'Wszystkie';
            } else {
                foreach ($stockIndexSelected as $key => $value) {
                    if ($value == 'NULL') {
                        $txt .= 'Bez kartoteki materiaĆowej ,';
                    } else {
                        $txt .= $stockIndexList[$value] . ' ,';
                    }
                }
            }
        } else {
            $txt .= 'Wszystkie';
        }
        $txt = rtrim($txt, ",");
    } elseif ($documentsSelected == 'EcmStockDocMoves') {
        $txt = 'Do magazynu: ';
        if (isset($mmSelected)) {
            if (count($mmSelected) == count($stockList)) {
                $txt .= 'Wszystkie';
            } else {
                foreach ($mmSelected as $key => $value) {
                    $txt .= $stockList[$value] . ' ,';
                }
            }
        } else {
            $txt .= 'Wszystkie';
        }
        $txt = rtrim($txt, ",");
    } elseif ($documentsSelected == 'EcmStockDocIns' || $documentsSelected == 'EcmStockDocOuts' || $documentsSelected == 'EcmInvoiceOuts' || $documentsSelected == 'EcmReceipts') {
        if (isset($accountName) && strlen($accountName) > 1) {
            $txt = 'Kontrahent: ' . $accountName;
        } else {
            $txt = 'Kontrahent: Wszyscy';
        }
    }

    include_once ("modules/EcmSysInfos/EcmSysInfo.php");
    $EcmSysInfo = new EcmSysInfo();
    $smarty->assign("nazwaFirmy", $EcmSysInfo->getName());
    $output = $smarty->fetch('modules/EcmReports/tpls/PDF/ReportStockDocMoves.tpl');

    include_once ("include/MPDF57/mpdf.php");
    unset($smarty);


    $p = new mPDF('', 'A4', null, 'helvetica', 10, 10, 26, 10, 5, 5);
    $p->setFooter('{PAGENO}');
    $p->setHTMLHeader('<div style="text-align: left; border-bottom: 1px solid #000000; font-weight: bold; font-size: 10pt;">
        <table>
            <tr>
                <td style="font-weight: bold; font-size: 9pt;">Obroty wg dokumentĂłw ' . $documentsList[$documentsSelected] . '</td>
            </tr>
            <tr>
                <td style="font-weight: bold; font-size: 9pt;">' . $EcmSysInfo->getName() . '</td>
            </tr>
            <tr>
                <td style="font-weight: bold; font-size: 9pt;">Data wygenerowania: ' . date("d.m.Y") . ' Okres: ' . $_REQUEST['date_from'] . ' do ' . $_REQUEST['date_to'] . '</td>
            </tr>
            <tr>
                <td style="font-weight: bold; font-size: 9pt;">' . $txt . ' </td>
            </tr>
        </table>
    </div>');

    $p->writeHTML($output);
    $p->Output("ObrotWgDokumentow_" . $documentsList[$documentsSelected] . "_" . $_REQUEST['date_from'] . "-" . $_REQUEST['date_to'].".pdf", "I");
} else {
    $smarty->display('modules/EcmReports/tpls/ReportStockDocMoves.tpl');
}
?>