<?php

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

    function indexAction()
    {
        $this->view->sstypes = $this->getDi()->selfserviceTypeTable->findBy();
        $this->view->display('self-service/admin/products.phtml');
    }

    function ajaxSaveAction()
    {
        $bp = $this->getDi()->billingPlanTable->load($this->_request->getInt('billing_plan_id'));
        if ($this->_request->getInt('product_id') != $bp->product_id)
            throw new Am_Exception_InputError("Billing plan does not match product");
        $type = $this->getDi()->selfserviceTypeTable->load($this->_request->getInt('type_id'));
        /* @var $type SelfserviceType */
        $rel = $this->getDi()->selfserviceTypeProductTable->findFirstBy([
            'billing_plan_id' => $bp->pk(),
            'type_id' => $type->pk(),
        ]);
        $relation = $this->_request->getFiltered('relation');

        $vars = $this->getRequest()->getParams();
        $vars['expire']['c'] = $vars['expire']['c'] ?: 1;
        if (in_array($vars['expire']['u'], ['lifetime', 'product'])) {
            $expire = $vars['expire']['u'];
        } else {
            $expire = "{$vars['expire']['c']}{$vars['expire']['u']}";
        }

        if ($rel) // relation exists, modify it
        {
            if ($relation == 'null') {
                $rel->delete();
            } else {
                $rel->relation = $relation;
                $rel->value = $this->_request->getInt('value');
                $rel->value_second = $this->_request->getInt('value_second');
                $rel->rollover = 2;
                $rel->expire = $relation == 'out' ? 'lifetime' : $expire;
                $rel->update();
            }
        } else {
            if ($relation != 'null')
            {
                $rel = $this->getDi()->selfserviceTypeProductTable->createRecord();
                $rel->type_id = $type->pk();
                $rel->product_id = $bp->product_id;
                $rel->billing_plan_id = $bp->pk();
                $rel->relation = $relation;
                $rel->value = $this->_request->getInt('value');
                $rel->value_second = $this->_request->getInt('value_second');
                $rel->rollover = 2;
                $rel->expire = $relation == 'out' ? 'lifetime' : $expire;
                $rel->insert();
            }
        }
        $this->_response->ajaxResponse(['ok' => true,]);
    }

    function ajaxSortAction()
    {
        $st = '';
        $sort = 1;
        if($this->getParam('order'))
        {
            foreach ($this->getParam('order') as $bp_id) {
                $st .= sprintf("WHEN %d THEN %d\n", $bp_id, $sort++);
            }
            $st = sprintf("sort_order = CASE (billing_plan_id) %s END", $st);
            $this->getDi()->db->query(<<<CUT
                UPDATE ?_selfservice_type_product
                    SET $st
                    WHERE relation = 'out'
CUT
                );
        }
        $this->_response->ajaxResponse(['ok' => true,]);
    }

    function ajaxTypeAction()
    {
        $type = $this->getDi()->selfserviceTypeTable->load($this->getParam('id'));
        $type->updateQuick('title', $this->getParam('title'));

        $this->_response->ajaxResponse(['ok' => true]);
    }
}