<?php

abstract class Am_Grid_Action_SelfService extends Am_Grid_Action_Abstract
{
    protected $type = self::NORECORD;
    protected $user = null;

    public function run()
    {
        $form = $this->getForm();

        if ($form->isSubmitted() && $form->validate()) {
            $this->doRun($form->getValue());
            $this->grid->redirectBack();
        } else {
            echo $this->renderTitle();
            echo $form;
        }
    }

    function setUser(User $user)
    {
        $this->user = $user;
    }

    abstract protected function doRun($values);

    protected function getForm()
    {
        $form = new Am_Form_Admin('self-service');

        $options = $this->grid->getDi()->selfserviceTypeTable->getOptions();
        $type_id = $form->addSelect('type_id')
            ->setLabel(___('Credit Type'))
            ->loadOptions($options);

        if (count($options) == 1) {
            reset($options);
            $type_id->setValue(key($options));
            $type_id->persistentFreeze(true);
            $type_id->toggleFrozen(true);
        }

        $value = $form->addInteger('value', ['autofocus'=>'autofocus'])
                ->setLabel(___('Value'))
                ->setId('ss-value');

        $value->setValue(0);
        $value->addRule('required');

        $form->addText('description', ['class' => 'am-el-wide'])
            ->setLabel(___('Comment'));

        $form->addScript()
            ->setScript("jQuery('#ss-value').focus()[0].select()");

        foreach ($this->grid->getVariablesList() as $k)
        {
            $form->addHidden($this->grid->getId() . '_' . $k)->setValue($this->grid->getRequest()->get($k, ""));
        }
        $form->addSaveButton();

        $form->setDataSources([$this->grid->getCompleteRequest()]);
        return $form;
    }
}

class Am_Grid_Action_SelfService_Credit extends Am_Grid_Action_SelfService
{
    protected function doRun($values)
    {
        $this->grid->getDi()->selfserviceHistoryTable
            ->credit($this->user, $values['value'], $values['type_id'], $values['description']);
    }
}

class Am_Grid_Action_SelfService_Debit extends Am_Grid_Action_SelfService
{
    protected function doRun($values)
    {
        $this->grid->getDi()->selfserviceHistoryTable
            ->debit($this->user, $values['value'], $values['type_id'], $values['description']);
    }
}

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

    public function  preDispatch()
    {
        $this->user_id = $this->getInt('user_id');
        parent::preDispatch();
    }

    function infoAction()
    {
        $this->setActiveMenu('users-browse');
        $ds = new Am_Query($this->getDi()->selfserviceHistoryTable);
        $ds->addWhere('user_id=?d', $this->getParam('user_id'));
        $ds->addOrder('dattm', true);

        $grid = new Am_Grid_Editable('_ss', ___('Self-Service'), $ds, $this->_request, $this->view);
        $grid->setPermissionId(Bootstrap_SelfService::ADMIN_PERM_ID);
        $grid->actionsClear();

        $user = $this->getDi()->userTable->load($this->user_id);

        $grid->actionAdd(new Am_Grid_Action_SelfService_Credit(null, ___('Credit')))->setUser($user);
        $grid->actionAdd(new Am_Grid_Action_SelfService_Debit(null, ___('Debit')))->setUser($user);

        $grid->addField(new Am_Grid_Field_Date('dattm', ___('Date')))->setFormatDate();
        $grid->addField('value', ___('Credits'), null, 'right');
        $grid->addField('description', ___('Description'));

        $grid->addCallback(Am_Grid_ReadOnly::CB_RENDER_TABLE, function(& $out, $g) use ($user) {
            $out = sprintf("<div style='text-align:right; margin-top:-2em; padding-bottom:.5em'>Balance: <strong>%d</strong> credits</div>", $g->getDi()->selfserviceBalanceTable->balance($user)) . $out;
        });

        $grid->runWithLayout('admin/user-layout.phtml');
    }
}