<?php

/** @help-id "PluginDocs/Modules/SelfService" */
class Am_Form_Setup_SelfService extends Am_Form_Setup
{
    function __construct()
    {
        parent::__construct('self-service');
        $this->setTitle(___('Self Service'));
    }

    function initElements()
    {
        $this->addText('self-service.type_title')
            ->setLabel(___('Title'));

        $gr = $this->addGroup()
            ->setSeparator(' ')
            ->setLabel(___("Affiliate Payout Conversion Rate\n".
                "how many credits affiliate should receive for %s",  Am_Currency::render(1)));

        $gr->addText('self-service.value', ['size'=>4]);

        $this->addAdvCheckbox('self-service.multi')
            ->setLabel(___("Allow to exchange credits for more than one copy of product\n"
                . "By default aMember allow to purchase only one copy of a product using credits.\n"
                . "With that option enabled user will be able to add the same product more then once"));

        $options = Am_Di::getInstance()->selfserviceTypeTable->getOptions();
        $type_id = $gr->addSelect('self-service.type_id')
            ->loadOptions($options)
            ->setValue(key($options));

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

        $title = Am_Di::getInstance()->db->selectCell("SELECT title FROM ?_selfservice_type WHERE type_id=1");

        $this->setDefault('self-service.value', 1);
        $this->setDefault('self-service.type_title', $title);

        $this->addElement('email_checkbox', 'self-service.product_added_admin')
            ->setLabel(___("Notify Admin when User Get Product"));

        $this->addInteger('self-service.records_per_page', ['placeholder' => 10])
            ->setLabel(___('Products per Page'));
        
        $this->addAdvCheckbox('self-service.allow-transfer')
            ->setLabel(___('Allow to transfer credits between users
            When enabled, user will be able to send credits to another user
            User will be able to transfer credits with no expiration period.'));
        
        $this->addElement('email_checkbox', 'self-service.credits_received')
            ->setLabel(___("Notify user when credits transferred to his account"));

        $this->addSaveCallbacks(null, [$this, 'saveTitle']);
    }

    function saveTitle(Am_Config $before, Am_Config $after)
    {
        Am_Di::getInstance()->db->query("UPDATE ?_selfservice_type SET title=? WHERE type_id=1",
            $after->get('self-service.type_title'));
        Am_Config::saveValue('self-service.type_title', null);
    }
}