<?php

include 'requires.php';


class chartController
{

    public function indexAction()
    {

        $db = new connectionController;
        $pdo = $db->getPdo();
        $tw = new twigController;
        $twig = $tw->getTwig();



        $sprzedazWmagazynie = [];
        $filterName = '';
        $filterSymbol = '';
        $magazynyIds = [];
        $docTypesIds = [2, 21];
        $towary = [];
        $today = new DateTime('now');
        $dateFrom = (isset($_POST['dateFrom'])) ? $_POST['dateFrom'] : $today->format('Y-m-d');
        $dateTo = (isset($_POST['dateTo'])) ? $_POST['dateTo'] : $today->modify('+7 days')->format('Y-m-d');
        $grupa = (isset($_POST['grupa'])) ? $_POST['grupa'] : 0;
        $cecha = (isset($_POST['cecha'])) ? $_POST['cecha'] : 0;


        $label = '';
        $sprzedaz = 0;
        $stan = 0;

        if(isset($_POST['sMagazyny'])){
            $magazynyIds = array_merge($magazynyIds, $_POST['sMagazyny']);
        }
        if(isset($_POST['sTypy'])){
            $docTypesIds =$_POST['sTypy'];
        }

        $where = '';

        if($grupa > 0){
            $where .= "AND t.tw_IdGrupa = ".$_POST['grupa']." ";
        }
        if($cecha > 0){
           $where .= "AND c.cht_IdCecha = ".$_POST['cecha']." ";
        }


        if(isset($_POST['nameText']) && strlen($_POST['nameText']) > 0){
            $filterName = $_POST['nameText'];
            if($_POST['nameHow'] == 1){
                $where .= "AND t.tw_Nazwa LIKE '%".$_POST['nameText']."%'";
            }
            elseif($_POST['nameHow'] == 2){
                $where .= "AND t.tw_Nazwa LIKE '".$_POST['nameText']."%'";
            }
        }
        if(isset($_POST['symbolText']) && strlen($_POST['symbolText']) > 0){
            $filterSymbol = $_POST['symbolText'];
            if($_POST['symbolHow'] == 1){
                $where .= "AND t.tw_Symbol LIKE '%".$_POST['symbolText']."%'";
            }
            elseif($_POST['symbolHow'] == 2){
                $where .= "AND t.tw_Symbol LIKE '".$_POST['symbolText']."%'";
            }
        }
        if(isset($_POST['renderTable']) && $_POST['renderTable'] == 1) {

            $objects = $pdo->query("SELECT t.*, s.*, c.* FROM dbo.tw__Towar t 
                                    LEFT JOIN dbo.tw_Stan s ON t.tw_Id = s.st_TowId 
                                    LEFT JOIN dbo.tw_CechaTw c ON c.cht_IdTowar = t.tw_Id
                                    WHERE s.st_MagId IN(".implode(',', $magazynyIds).") ".$where." ORDER BY t.tw_Nazwa ");
            $objects = $objects->fetchAll();

            $objectsIds = [];
            foreach ($objects as $object){
                $objectsIds[] = $object['tw_Id'];
            }


            if(count($objectsIds) > 0){


                $begin = new DateTime( $dateFrom );
                $end = new DateTime( $dateTo );
                $end = $end->modify( '+1 day' );

                $interval = new DateInterval('P1D');
                $daterange = new DatePeriod($begin, $interval ,$end);

                $label = [];
                $sprzedaz = [];
                $stan = [];
                $i = 0;
                foreach($daterange as $date){

                    $dateString = $date->format("Y-m-d");
                    $dateStringForQuantity = $date->format("Ymd");

                    if (!array_key_exists($dateString, $sprzedaz)) {
                        $sprzedaz[$i] = 0;
                        $stan[$i] = 0;
                    }

                    $label[] = $dateString;

                    $pozycje = $pdo->query("SELECT p.*, d.* FROM dbo.dok_Pozycja p 
                                          LEFT JOIN dbo.dok__Dokument d ON p.ob_DokHanId = d.dok_Id
                                          WHERE p.ob_TowId IN(".implode(',', array_unique($objectsIds)).") AND d.dok_Typ IN(".implode(',', $docTypesIds).") AND d.dok_DataWyst BETWEEN '$dateString' AND '$dateString' AND d.dok_MagId IN(" . implode(',', $magazynyIds) . ") ");
                    $pozycje = $pozycje->fetchAll();


                    $sumStan = $pdo->query("select sum(A.mr_ilosc-isnull(R.mr_ilosc,0)) 
 As ilosc
 from 	dok_magruch A 
 inner join tw__towar T on A.mr_TowId = T.tw_Id 
 inner join vwDokMagWart W on A.mr_SeriaId = W.mw_SeriaId  
left join ((select isnull( sum( C.mr_ilosc ), 0 ) mr_ilosc, C.mr_doId from dok_magruch C where C.mr_data<='$dateStringForQuantity' group by C.mr_doId)) R on R.mr_DoId = A.mr_id 
		 where 	W.mw_pozid in 
		 (SELECT TOP 1 T.mw_pozid  FROM vwDokMagWart T  WHERE T.mw_SeriaId = W.mw_seriaid and T.mw_data<='$dateStringForQuantity'  ORDER BY mw_data DESC, mw_pozid DESC) and  A.mr_TowId IN (".implode(',', array_unique($objectsIds)).") AND A.mr_magid IN (" . implode(',', $magazynyIds) . ") and A.mr_data<='$dateStringForQuantity' and  A.mr_ilosc > isnull(R.mr_ilosc,0) 
");
                    $sumStan = $sumStan->fetch();


                    $sprzedazWmagazynie = [];

                    foreach ($pozycje as $pozycja) {
                        $sprzedaz[$i] += $pozycja['ob_IloscMag'];

                    }

                    $stan[$i] = floatval($sumStan['ilosc']);


                    $i++;
                }
            }

        }


        $magazyny = $pdo->query("SELECT m.* FROM dbo.sl_Magazyn m ");
        $magazyny = $magazyny->fetchAll();

        $magazynyNazwy = [];

        foreach($magazyny as $magazyn){

            $magazynyNazwy[$magazyn['mag_Id']] = $magazyn['mag_Symbol'];

        }

        $cechy = $pdo->query("SELECT c.* FROM dbo.sl_CechaTw c");
        $cechy = $cechy->fetchAll();

        $grupy = $pdo->query("SELECT g.* FROM dbo.sl_GrupaTw g");
        $grupy = $grupy->fetchAll();


        $filters = [
            'magazynyIds' => $magazynyIds,
            'nameText' => $filterName,
            'nameHow' => (isset($_POST['nameHow'])) ? $_POST['nameHow'] : 1,
            'symbolText' => $filterSymbol,
            'symbolHow' => (isset($_POST['symbolHow'])) ? $_POST['symbolHow'] : 1,
            'docTypesIds' => $docTypesIds,
            'dateFrom' => $dateFrom,
            'dateTo' => $dateTo,
            'grupa' => $grupa,
            'cecha' => $cecha
        ];

        echo $twig->render('chart/index.html.twig', ['towary' => $towary,
            'magazynyIds' => $magazynyIds,
            'dTypy' => $this->getDocTypes(),
            'filters' => $filters,
            'magazyny' => $magazyny,
            'magazynyNazwy' => $magazynyNazwy,
            'cechy' => $cechy,
            'grupy' => $grupy,
            'label' => $label,
            'sprzedaz' => $sprzedaz,
            'stan' => $stan
            ]);

    }

    private function getDocTypes(){

        $docTypes[1] = ['short' => 'FS', 'name' => 'Faktura VAT sprzedaży', 'id' => 2];
        //$docTypes[2] = ['short' => 'FSzal', 'name' => 'Faktura sprzedaży zaliczkowa', 'id' => ];
        //$docTypes[3] = ['short' => 'FSz', 'name' => 'Faktura sprzedaży zbiorcza', 'id' => ];
        $docTypes[4] = ['short' => 'FM', 'name' => 'Faktura sprzedaży marżą', 'id' => 62];
        $docTypes[5] = ['short' => 'RS', 'name' => 'Rachunek sprzedaży', 'id' => 4];
        $docTypes[6] = ['short' => 'KFS', 'name' => 'Korekta faktury VAT sprzedaży', 'id' => 6];
        //$docTypes[7] = ['short' => 'KFSn', 'name' => 'Korekta faktury sprzedaży do nieistniejącego', 'id' => ];
        //$docTypes[8] = ['short' => 'KFSzc', 'name' => 'Korekta faktury sprzedaży zaliczkowej', 'id' => ];
        $docTypes[9] = ['short' => 'KFM', 'name' => 'Korekta faktury VAT marżą', 'id' => 67];
        //$docTypes[10] = ['short' => 'KFMn', 'name' => 'Korekta faktury marża do nieistniejącego', 'id' => ];
        //$docTypes[11] = ['short' => 'FSd', 'name' => 'Faktura sprzedaży detaliczna', 'id' => ];
        $docTypes[12] = ['short' => 'PA', 'name' => 'Paragon', 'id' => 21];
        //$docTypes[13] = ['short' => 'PAi', 'name' => 'Paragon imienny', 'id' => ];
        //$docTypes[14] = ['short' => 'PAf', 'name' => 'Paragoon fiskalny', 'id' => ];
        //$docTypes[15] = ['short' => 'PAk', 'name' => 'Paragon odebrany z kasy', 'id' => ];
        $docTypes[16] = ['short' => 'ZW', 'name' => 'Zwrot ze sprzedaży detalicznej', 'id' => 14];
        //$docTypes[17] = ['short' => 'ZWn', 'name' => 'Zwrot do nieistniejącego', 'id' => ];


        return $docTypes;

    }

}


?>
