<?php
/**
 * Class represents records from table coupon_batch
 * * * * * * * {autogenerated}
 * @property int $batch_id 
 * @property string $comment 
 * @property string $discount_type enum('percent','number')
 * @property double $discount 
 * @property date $begin_date 
 * @property date $expire_date 
 * @property int $is_disabled 
 * @property int $is_recurring 
 * @property string $product_ids 
 * @property int $use_count 
 * @property int $user_use_count 
 * @property int $user_id 
 * @see Am_Table
 */
class CouponBatch extends Am_Record {
    function delete() {
        $this->deleteFromRelatedTable('?_coupon');
        parent::delete();
    }
    function generateCoupons($count, $minLen, $maxLen)
    {
        $table = $this->getDi()->couponTable;
        for ($i=0; $i<$count; $i++){
            $coupon = $this->getDi()->couponRecord;
            $coupon->code = $table->generateCouponCode($minLen, $maxLen);
            $coupon->batch_id = $this->pk();
            $coupon->insert();
        }
    }
}

class CouponBatchTable extends Am_Table {
    protected $_key = 'batch_id';
    protected $_table = '?_coupon_batch';
    protected $_recordClass = 'CouponBatch';

    function deleteByUserId($user_id){
        if (!$user_id)
            throw new Am_Exception_InternalError("user_id is empty in " . __METHOD__);
        $list = $this->_db->selectCol("SELECT batch_id FROM ?_coupon_batch WHERE user_id=?d", $user_id);
        if ($list)
            $this->_db->query("DELETE FROM ?_coupon_batch, ?_coupon WHERE batch_id IN (?a)", $list);
    }

    function getOptions($onlyEnabled = true)
    {
        return array_map(array("Am_Controller", "escape"), $this->_db->selectCol("SELECT batch_id as ARRAY_KEY, 
            CONCAT('#', batch_id, ' ', IF(comment<>'', comment, CONCAT(discount, IF(discount_type='percent', '%', '$'), IF(begin_date, CONCAT(' (', begin_date, ' - ', expire_date, ')'), ''))))
            FROM ?_coupon_batch
            {WHERE is_disabled = 0}",
            $onlyEnabled ? 1 : DBSIMPLE_SKIP));
    }
}
