<?php

include 'requires.php';


class idOrderController
{

    const DOC_FZ = 1,
          DOC_MM = 9,
          DOC_PZ = 10,
          DOC_RW = 13,
          DOC_ZD = 15;

    public function indexAction()
    {

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


        $magazynyIds = [];
        $docTypesIds = [2, 21];

        $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');

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

        $filters = [
            'magazynyIds' => $magazynyIds,
            'dateFrom' => $dateFrom,
            'dateTo' => $dateTo,
        ];


        $where = '';


        $documents = [];

        if(isset($_POST['renderTable']) && $_POST['renderTable'] == 1) {

            $documents = $this->buildDocumentsArray($filters);

        }

        $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'];

        }

        echo $twig->render('idorder/index.html.twig', [
            'magazynyIds' => $magazynyIds,
            'filters' => $filters,
            'magazyny' => $magazyny,
            'magazynyNazwy' => $magazynyNazwy,
            'documents' => $documents
            ]);

    }

    private function buildDocumentsArray($filters){

        $db = new connectionController;
        $pdo = $db->getPdo();

        $magazynyIds = $filters['magazynyIds'];

        $orderIds = $pdo->query("SELECT DISTINCT pw.pwd_Tekst10 FROM dbo.pw_Dane pw
                                               WHERE pw.pwd_Tekst10 is not null");
        $orderIds = $orderIds->fetchAll();

        $documents = [];
        foreach ($orderIds as $orderId){

            $oId = $orderId['pwd_Tekst10'];

            $objects = $pdo->query("SELECT d.* FROM dbo.dok__Dokument d 
                                              LEFT JOIN dbo.pw_Dane pw ON pw.pwd_IdObiektu = d.dok_Id
                                              WHERE pw.pwd_Tekst10 = '".$oId."' ");
            $objects = $objects->fetchAll();

            foreach($objects as $object){
                $documents[$oId][$object['dok_Typ']] = $object;
            }

        }

        return $documents;
    }
}


?>
