<?php

class Am_Grid_Action_Group_SelfserviceCredit extends Am_Grid_Action_Group_Form
{
    protected $credit = false;

    public function __construct($credit = true)
    {
        $this->credit = (bool)$credit;
        parent::__construct(
            $credit ? "self-service-credit" : "self-service-debit",
            $credit ? ___("Self-Service Credit") : ___("Self-Service Debit")
        );
    }

    public function handleRecord($id, $record)
    {
        switch ($this->credit) {
            case true:
                $this->grid->getDi()->selfserviceHistoryTable
                    ->credit($record, $this->_vars['value'], $this->_vars['type_id'], $this->_vars['description']);
                break;
            case false:
                $this->grid->getDi()->selfserviceHistoryTable
                    ->debit($record, $this->_vars['value'], $this->_vars['type_id'], $this->_vars['description']);
                break;
        }
    }

    public function createForm(): Am_Form
    {
        $form = new Am_Form_Admin('self-service');
        $id = $this->grid->getId();

        $options = $this->grid->getDi()->selfserviceTypeTable->getOptions();
        $type_id = $form->addSelect("{$id}_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("{$id}_value", ['autofocus' => 'autofocus'])
            ->setLabel(___('Value'))
            ->setId('ss-value');

        $value->addRule('required');

        $form->addText("{$id}_description", ['class' => 'am-el-wide'])
            ->setLabel(___('Comment'));

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

        $form->addSaveButton($this->credit ? ___('Credit') : ___('Debit'));

        return $form;
    }
}