<?php
/**
 * Class represents records from table aff_payout
 * {autogenerated}
 * @property int $payout_id PK
 * @property date $date
 * @property date $thresehold_date
 * @property float|null $total
 * @property string|null $type
 * {/autogenerated}
 */
class AffPayout extends Am_Record 
{
    /**
     * @return AffPayoutDetail
     */
    function addDetail($aff_id, $amount)
    {
        $detail = $this->getDi()->affPayoutDetailRecord;
        $detail->aff_id = $aff_id;
        $detail->amount = $amount;
        $detail->payout_id = $this->pk();
        $detail->insert();
        $this->total += $amount;
        return $detail;
    }
    
    /** @return Am_Aff_PayoutMethod|null */
    function getPayoutMethod()
    {
        foreach (Am_Aff_PayoutMethod::getEnabled() as $k => $p)
            if ($k == $this->type)
                return $p;
    }

    function delete()
    {
        $this->getTable()->getAdapter()->query("
            UPDATE ?_aff_commission SET payout_detail_id = NULL
            WHERE
            payout_detail_id IN (
                SELECT payout_detail_id
                    FROM ?_aff_payout_detail
                    WHERE payout_id=?)
        ", $this->pk());
        $this->getDi()->affPayoutDetailTable->deleteByPayoutId($this->pk(), false);
        return parent::delete();
    }
}

/** @extends Am_Table<AffPayout> */
class AffPayoutTable extends Am_Table 
{
    protected $_key = 'payout_id';
    protected $_table = '?_aff_payout';
}
