<?php
/**
 * Class represents records from table button
 * {autogenerated}
 * @property int $button_id PK
 * @property string $hash
 * @property string|null $title
 * @property string|null $comment
 * @property int|null $use_coupons
 * @property string|null $coupon
 * @property int|null $is_disabled
 * @property string|null $paysys_id
 * @property string|null $billing_plan_id
 * @property int|null $saved_form_id FK saved_form
 * {/autogenerated}
 */
class Button extends Am_Record
{
    function createInvoice()
    {
        $bp = $this->getDi()->billingPlanTable->load($this->billing_plan_id);
        $pr = $bp->getProduct();
        if ($pr->is_archived) {
            throw new Am_Exception_InputError;
        }

        /* @var $invoice Invoice */
        $invoice = $this->getDi()->invoiceRecord;

        $paysys_id = $this->unserializeList($this->paysys_id);
        if (count($paysys_id) == 1) {
            $invoice->paysys_id = current($paysys_id);
        }

        $invoice->add($pr);

        if ($this->coupon) {
            $invoice->setCouponCode($this->coupon);
            $invoice->validateCoupon();
        }

        return $invoice;
    }
}

/** @extends Am_Table<Button> */
class ButtonTable extends Am_Table
{
    protected $_key = 'button_id';
    protected $_table = '?_button';
    protected $_recordClass = 'Button';

    public function insert(array $values, $returnInserted = false)
    {
        if (empty($values['hash'])) {
            $values['hash'] = $this->getDi()->security->randomString(12);
        }
        return parent::insert($values, $returnInserted);
    }
}