<?php
/**
 * Class represents records from table aff_banners
 * {autogenerated}
 * @property int $banner_id PK
 * @property int $sort_order
 * @property int $type
 * @property string $title
 * @property string|null $desc
 * @property string|null $html
 * @property int|null $upload_id FK upload
 * @property int|null $upload_big_id
 * @property string $url
 * @property int|null $is_blank
 * @property string|null $mime
 * @property int|null $width
 * @property int|null $height
 * @property int $is_disabled
 * @property string|null $user_group_id FK user_group
 * @property string|null $category
 * {/autogenerated}
 */
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;
    }
}

/** @extends Am_Table<AffBanner> */
class AffBannerTable extends Am_Table {
    protected $_key = 'banner_id';
    protected $_table = '?_aff_banner';
    protected $_recordClass = 'AffBanner';
    
    /** @return TRecord[] */
    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);
    }
}

