<?php

/**
 * Created by PhpStorm.
 * User: leos
 * Date: 8/4/17
 * Time: 2:34 PM.
 */

use KupShop\KupShopBundle\Util\StringUtil;
use Query\Operator;

$main_class = 'Filters';

class Filters extends Window
{
    protected $tableName = 'admin_filters';
    protected $nameField = 'name';

    public function get_vars()
    {
        $vars = parent::get_vars();
        $data = &$vars['body']['data'];

        if ($ls = getVal('ls')) {
            // Uložit aktuální filtr (jako novy nebo prepsat existujici)
            // ls - current query string = aktuální filtr
            parse_str($ls, $parameters); // parse query string into parameters
            if ($order = $parameters['order'] ?? null) {
                // 'order' odstranit z query string, ulozit zvlast (sort)
                unset($parameters['order']);
                $orderParam = [
                    'sort' => trim($order, '-'),
                    'direction' => StringUtil::startsWith($order, '-') ? 'DESC' : 'ASC',
                ];
                $data['sort'] = json_encode($orderParam);
            }
            if ($adminFilter = $parameters['adminFilter'] ?? null) {
                // misto ulozenych parametru query string obsahuje ID existujiciho filtru (adminFilter)
                // parameters musime zkopirovat z filtru s ID=adminFilter
                unset($parameters['adminFilter']);
                $list = sqlQueryBuilder()->select('list')->from('admin_filters')
                    ->andWhere(Operator::equals(['id' => $adminFilter]))
                    ->execute()->fetchColumn();
                if ($list) {
                    parse_str($list, $parameters);
                }
            }

            // Nechci ukladat stranku do filtru
            unset($parameters['page']);

            $data['list'] = http_build_query($parameters); // Rebuilt query string
            $data['parameters'] = json_encode(array_filter($parameters));
        } elseif ($ls = $data['list'] ?? null) {
            parse_str($ls, $parameters);
            $data['parameters'] = json_encode(array_filter($parameters));
        }

        if (getVal('acn') == 'edit') {
            $data['admin'] = $this->getQueryBuilder()
                ->select('login')
                ->from('admins', 'a')
                ->where('id = :id')
                ->setParameters(['id' => $data['id_admin']])
                ->execute()->fetchColumn();
        } elseif (getVal('acn') == 'add' && $this->isDuplicate() != 1) {
            $data['type'] = getVal('pg');
            if (preg_match_all('/[0-9]{1,2}[\\\.][0-9]{1,2}[\\\.][0-9]{4}/', $data['list'], $matches)) {
                $today = new DateTime();
                $today->setTime(0, 0, 0, 0);
                $format = Settings::getDateFormat();
                foreach ($matches[0] as $match) {
                    $date = DateTime::createFromFormat($format, $match);
                    if ($date) {
                        $date->setTime(0, 0, 0, 0);
                        $diff = $today->diff($date);
                        $data['dates'][$match] = ($diff->invert ? -$diff->days : $diff->days);
                    }
                }
            }
        } elseif ($this->isDuplicate() == 1) {
            $data['id_admin'] = false;
        }

        return $vars;
    }

    public function getData()
    {
        global $adminID;
        $data = parent::getData();

        if (getVal('Submit') && getVal('acn') == 'add') {
            $data['id_admin'] = ($adminID == 0) ? null : $adminID;
            $rel_date = getVal('rel_date', null, []);
            foreach ($rel_date as $date => $diff) {
                $data['list'] = str_replace('='.$date, '={DATE:'.$diff.'}', $data['list']);
            }
        }

        return $data;
    }

    public function handleUpdate()
    {
        global $adminID;
        $data = $this->getData();
        $admin = ($adminID == 0) ? null : $adminID;
        $globalOld = $this->getObject()['global'];

        if (empty($data['name'])) {
            $error = 'Název je povinný!';
            redirect("launch.php?s={$this->getName()}.php&acn=add&pg=".($data['type'] ?? '').'&ls='.urlencode($data['list'] ?? '').'&ErrStr='.urlencode($error));
        }

        if (!empty($data['default_filter']) && $data['default_filter'] == 'Y') {
            $global = $data['global'] ?? $globalOld;

            $delete = sqlQueryBuilder()->update('admin_filters')
                    ->set('default_filter', '"N"')
                    ->where(Operator::equals(['type' => $data['type']]));
            if ($global === 'N') {
                $delete->andWhere(Operator::equalsNullable(['id_admin' => $admin]));
            }
            $delete->andWhere(Operator::equals(['global' => $global]))
                    ->execute();
        }

        if ($globalOld === 'Y' && $data['global'] === 'N') {
            sqlQueryBuilder()->update('admin_filters')
                ->set('id_admin', (empty($admin)) ? 'null' : $admin)
                ->where(Operator::equals(['id' => $this->getID()]))
                ->execute();
        }

        parent::handleUpdate();

        return true;
    }
}
