<?php

use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

$main_class = 'Margins';

class Margins extends Window
{
    public function get_vars()
    {
        $vars = parent::get_vars();

        $margins = sqlQueryBuilder()
            ->select('*')
            ->from('margins')
            ->orderBy('range_from')
            ->execute()
            ->fetchAll();

        $last = 0;

        foreach ($margins as &$margin) {
            if ($margin['range_from'] < $last) {
                $margin['bad_down_range'] = true;
            }

            $margin['pl_range_from'] = $margin['range_from'] * (100 + $margin['margin']) / 100;
            $margin['pl_range_to'] = $margin['range_to'] * (100 + $margin['margin']) / 100;

            $last = $margin['range_to'];
        }

        $vars['body']['data']['margins'] = $margins;

        return $vars;
    }

    public function handle()
    {
        $acn = getVal('acn');
        if ($acn) {
            $action = 'handle'.ucfirst($acn);
            if (method_exists($this, $action)) {
                call_user_func([$this, $action]);
            }
        }

        $data = getVal('data');
        $submit = getVal('Submit');

        if ($submit) {
            foreach ($data as $id => $margin) {
                if (!empty($margin['delete']) || empty($margin['range_to'])) {
                    if ($id > 0) {
                        $this->deleteSQL('margins', ['id' => $margin['id']]);
                    }
                    continue;
                }

                $margin['margin'] = floatval(str_replace([',', ' '], ['.', ''], $margin['margin']));

                if ($id < 0) {
                    $this->insertSQL('margins', $margin, ['id', 'delete']);
                } else {
                    $this->updateSQL('margins', $margin, ['id' => $margin['id']], ['id', 'delete']);
                }
            }

            $this->returnOK('Uloženo');
        }
    }

    public function handleRecalculateProducts()
    {
        $compute = ServiceContainer::getService('kupshop.margins.compute.compute');

        $compute->computeAll();

        $this->returnOK('Přepočítáno.');
    }

    public function hasRights($name = null)
    {
        switch ($name) {
            case Window::RIGHT_DUPLICATE:
            case Window::RIGHT_DELETE:
                return false;
            default:
                return parent::hasRights($name);
        }
    }
}
