<?php

class SelfService_AdminProductsGridController extends Am_Mvc_Controller_Pages
{
    public function checkAdminPermissions(Admin $admin)
    {
        return $admin->hasPermission(Bootstrap_SelfService::ADMIN_PERM_CONFIG_ID);
    }

    function initPages()
    {
        $this->addPage([$this, 'createInPage'], 'index', ___('Bring Credits'));
        $this->addPage([$this, 'createOutPage'], 'out', ___('Purchased with Credits'));
    }

    public function createInPage()
    {
        $ds = new Am_Query($this->getDi()->selfserviceTypeProductTable);
        $ds->leftJoin('?_product', 'p', 'p.product_id=t.product_id')
            ->leftJoin('?_billing_plan', 'b', 'b.plan_id=t.billing_plan_id')
            ->addWhere('relation=?', 'in')
            ->addField('CONCAT(p.title,": ", b.title)','title');

        $grid = new Am_Grid_Editable('_ss', ___('Self-Service Store Configuration'), $ds, $this->getRequest(), $this->view, $this->getDi());
        $grid->addField('title', ___('Product / Billing Plan'));
        $grid->addField('value', ___('Credits'), false)->setGetFunction(
            function($r, $g, $fn, $fo){
                return ___("On purchase: %d credits, on rebill: %d credits", $r->value, $r->value_second);
            });
        $grid->addField('expire', ___('Expire'));
        $grid->setForm([$this, 'createInForm']);

        $grid->addCallback(Am_Grid_Editable::CB_VALUES_TO_FORM, [$this, 'valuesToFormIn']);
        $grid->addCallback(Am_Grid_Editable::CB_VALUES_FROM_FORM, [$this, 'valuesFromForm']);
        $grid->setFilter(new Am_Grid_Filter_Product);
        $grid->setRecordTitle(___('Product that bring credits'));
        $grid->setPermissionId(Bootstrap_SelfService::ADMIN_PERM_CONFIG_ID);
        return $grid;
    }

    public function createOutPage()
    {
        $ds = new Am_Query($this->getDi()->selfserviceTypeProductTable);
        $ds->leftJoin('?_product', 'p', 'p.product_id=t.product_id')
            ->leftJoin('?_billing_plan', 'b', 'b.plan_id=t.billing_plan_id')
            ->addWhere('relation=?', 'out')
            ->addField('CONCAT(p.title,": ", b.title)','title')
            ->addOrder('sort_order');

        $grid = new Am_Grid_Editable('_ss', ___('Self-Service Store Configuration'), $ds, $this->getRequest(), $this->view, $this->getDi());
        $grid->addField('title', ___('Product / Billing Plan'));
        $grid->addField('value', ___('Credits'), false)->setGetFunction(
            function($r, $g, $fn, $fo){
                return ___("To purchase: %d credits", $r->value);
            });
        $grid->setForm([$this, 'createOutForm']);

        $grid->addCallback(Am_Grid_Editable::CB_VALUES_TO_FORM, [$this, 'valuesToFormOut']);
        $grid->addCallback(Am_Grid_Editable::CB_VALUES_FROM_FORM, [$this, 'valuesFromForm']);
        $grid->setFilter(new Am_Grid_Filter_Product);
        $grid->setRecordTitle(___('Product that can be purchased with credits'));
        $grid->actionAdd(new Am_Grid_Action_Sort_Sss);
        $grid->setPermissionId(Bootstrap_SelfService::ADMIN_PERM_CONFIG_ID);
        return $grid;
    }

    function valuesToFormIn(& $ret, $record)
    {
        $ret['_id'] = isset($record->product_id) ? "{$record->product_id}-{$record->billing_plan_id}" : null;

        if($expire = @$record->expire)
        {
            preg_match('/^([0-9]*)?([a-z]+)$/', $expire, $m);
            $ret['_unit'] = $m[2];
            $ret['_period'] = $m[1];
        }
        if (!isset($ret['_period'])) {
            $ret['_unit'] = 'lifetime';
            $ret['_period'] = '';
        }
    }

    function valuesToFormOut(& $ret, $record)
    {
        $ret['_id'] = isset($record->product_id) ? "{$record->product_id}-{$record->billing_plan_id}" : null;
    }

    function valuesFromForm(& $values, $record)
    {
        list($record->product_id, $record->billing_plan_id) = explode('-', $values['_id']);
        $record->type_id = 1;
        $record->rollover = 2;

        switch ($values['relation']) {
            case 'in' :
                $values['_period'] = $values['_period'] ?: 1;
                if (in_array($values['_unit'], ['lifetime', 'product'])) {
                    $record->expire = $values['_unit'];
                } else {
                    $record->expire = "{$values['_period']}{$values['_unit']}";
                }
                break;
            case 'out' :
                $record->expire = null;
                $record->value_second = 0;
                break;
        }
    }

    function createInForm()
    {
        $form = new Am_Form_Admin();

        $form->addHtml()
            ->setHtml(___('Product that bring credits'));

        $form->addSelect('_id', ['class' => 'am-combobox-fixed'])
            ->setLabel(___('Product / Billing Plan'))
            ->loadOptions($this->getDi()->billingPlanTable->getProductPlanOptions());

        $form->addHidden('relation')->setValue('in');

        $gr = $form->addGroup(null, ['id' => 'pt-value'])
            ->setLabel(___("On purchase"));
        $gr->setSeparator(' ');
        $gr->addHtml()->setHtml('<span class="product-type-sign">+</span>');
        $gr->addInteger('value')->addRule('required');
        $gr->addHtml()->setHtml(___('credits'));

        $gr = $form->addGroup()
            ->setLabel(___("On Rebill"));
        $gr->setSeparator(' ');
        $gr->addHtml()->setHtml('<span class="product-type-sign">+</span>');
        $gr->addInteger('value_second');
        $gr->addHtml()->setHtml(___('credits'));

        $gr = $form->addGroup()
            ->setLabel(___("Expire credits"));
        $gr->setSeparator(' ');
        $gr->addInteger('_period');
        $gr->addSelect('_unit')
            ->loadOptions([
                'd' => ___('Days'),
                'm' => ___('Months'),
                'y' => ___('Years'),
                'lifetime' => ___('Lifetime'),
                'product' => ___('Product Expiration Date')
            ]);
        $form->addScript()
                ->setScript(<<<CUT
jQuery('[name=_unit]').change(function(){
    jQuery('[name=_period]').toggle(!['lifetime', 'product'].includes(jQuery(this).val()))
}).change();
CUT
            );

        return $form;
    }

    function createOutForm()
    {
        $form = new Am_Form_Admin();

        $form->addHtml()
            ->setHtml(___('Product that can be purchased with credits'));

        $form->addSelect('_id', ['class' => 'am-combobox-fixed'])
            ->setLabel(___('Product / Billing Plan'))
            ->loadOptions($this->getDi()->billingPlanTable->getProductPlanOptions());

        $form->addHidden('relation')->setValue('out');

        $gr = $form->addGroup(null, ['id' => 'pt-value'])
            ->setLabel(___("To purchase"));
        $gr->setSeparator(' ');
        $gr->addHtml()->setHtml('<span class="product-type-sign">&minus;</span>');
        $gr->addInteger('value')->addRule('required');
        $gr->addHtml()->setHtml(___('credits'));

        return $form;
    }
}

class Am_Grid_Action_Sort_Sss extends Am_Grid_Action_Sort_Abstract
{
    protected function setSortBetween($item, $after, $before)
    {
        $this->_simpleSort($this->grid->getDi()->selfserviceTypeProductTable, $item, $after, $before, "relation");
    }
}

class Am_Grid_Filter_Product extends Am_Grid_Filter_Abstract
{
    protected function applyFilter()
    {
        $query = $this->grid->getDataSource();
        if ($s = @$this->vars['filter']['text']) {
            $query->add(new Am_Query_Condition_Field('title', 'LIKE', '%' . $s . '%', 'p'))
                ->_or(new Am_Query_Condition_Field('product_id', '=', $s, 'p'));
        }
        if ($category_id = @$this->vars['filter']['category_id']) {
            $query->leftJoin("?_product_product_category", "ppc", "p.product_id=ppc.product_id");
            $query->addWhere("ppc.product_category_id=?d", $category_id);
        }

        if (@$this->vars['filter']['dont_show_disabled']) {
            $query->addWhere("is_disabled=0");
        }
    }

    public function renderInputs()
    {
        $options = ['' => '-' . ___('Filter by Category') . '-'];
        $options = $options +
            Am_Di::getInstance()->productCategoryTable->getAdminSelectOptions(
                [ProductCategoryTable::COUNT => true]);
        $options = Am_Html::renderOptions(
                $options,
                @$this->vars['filter']['category_id']
        );
        $out = sprintf('<select onchange="this.form.submit()" name="_ss_filter[category_id]">%s</select>&nbsp;' . PHP_EOL, $options);
        $this->attributes['value'] = (string) @$this->vars['filter']['text'];
        $out .= $this->renderInputText('filter[text]');
        $out .= '<br />' . $this->renderShowDisabled();
        return $out;
    }

    public function renderShowDisabled()
    {
        return sprintf('<label>
                <input type="hidden" name="%s_filter[dont_show_disabled]" value="0" />
                <input type="checkbox" name="%s_filter[dont_show_disabled]" value="1" %s /> %s</label>',
            $this->grid->getId(), $this->grid->getId(),
            (@$this->vars['filter']['dont_show_disabled'] == 1 ? 'checked' : ''),
            Am_Html::escape(___('do not show disabled products'))
        );
    }
}