<?php
/**
 * Class represents records from table aff_banners
 * {autogenerated}
 * @property int $banner_id 
 * @property int $type 
 * @property string $title 
 * @property string $desc 
 * @property int $upload_id 
 * @property int $upload_big_id 
 * @property string $url 
 * @property string $mime 
 * @property int $width 
 * @property int $height 
 * @property int $is_disabled 
 * @see Am_Table
 */
class AffBanner extends Am_Record {

    const TYPE_TEXTLINK = 1;
    const TYPE_BANNER = 2;
    const TYPE_PAGEPEEL = 3;
    const TYPE_LIGHTBOX = 4;
    const TYPE_CUSTOM = 5;

    public function insert($reload = true)
    {
        $table_name = $this->getTable()->getName();
        $max = $this->getAdapter()->selectCell("SELECT MAX(sort_order) FROM {$table_name}");
        $this->sort_order = $max + 1;
        return parent::insert($reload);
    }

    public function delete()
    {
        $ret = parent::delete();
        $table_name = $this->getTable()->getName();
        $this->getAdapter()->query("UPDATE {$table_name}
            SET sort_order=sort_order-1
            WHERE sort_order>?", $this->sort_order);
        return $ret;
    }

    function getUrl()
    {
        return $this->url;
    }
}

class AffBannerTable extends Am_Table {
    protected $_key = 'banner_id';
    protected $_table = '?_aff_banner';
    protected $_recordClass = 'AffBanner';
    
    function findActive($category = null){
        return $this->selectObjects("SELECT * FROM ?_aff_banner
            WHERE is_disabled=0
            AND {category = ?} {category IS NULL AND ?d=?d}
            ORDER BY sort_order",
            is_null($category) ? DBSIMPLE_SKIP : $category,
            !is_null($category) ? DBSIMPLE_SKIP : 1, 1);
    }

    function getCategories($onlyEnabled = false)
    {
        return $this->_db->selectCol("SELECT DISTINCT category, category AS ?
            FROM ?_aff_banner
            WHERE category IS NOT NULL
            {AND is_disabled = ?}
            ORDER BY category",
            DBSIMPLE_ARRAY_KEY, $onlyEnabled ? 0 : DBSIMPLE_SKIP);
    }
}

