<?php
class Banners extends Buyers
{
    public function __construct()
    {
        if(!is_dir($this->config->root_dir.$this->images->banners_images_dir))
            mkdir($this->config->root_dir.$this->images->banners_images_dir, 0755);
    }

    public function get_banners($filter = array())
    {
        $page_id = '';
        $visible = '';
        $limit = '';
        $banner_id = '';
        $sorted = 'position ASC';

        if(isset($filter['page_id']))
            $page_id = $this->db->placehold('AND page_id IN(?@)', (array) $filter['page_id']);

        if(!empty($filter['limit']))
            $limit = $this->db->placehold('LIMIT ?', (int)$filter['limit']);

        if(isset($filter['visible']))
            $visible = $this->db->placehold('AND visible=?', (int)$filter['visible']);

        if(!empty($filter['banner_id']))
            $banner_id = $this->db->placehold('AND id = ?', (int)$filter['banner_id']);

        if(!empty($filter['sort']))
        {
            switch($filter['sort'])
            {
                case 'id':
                    $sorted = $this->db->placehold('id ASC');
                break;
                case 'random':
                    $sorted = $this->db->placehold('RAND()');
                break;
                case 'position':
                    $sorted = $this->db->placehold('position ASC');
                break;
            }
        }

        $query = $this->db->placehold("SELECT * FROM banners WHERE 1 $visible $banner_id $page_id ORDER BY $sorted $limit");
        $this->db->query($query);
        $banners = $this->db->results();
        if(!empty($banners))
        {
            $images = $this->images->get_images(array('relation' => 'banners', 'relation_id' => array_keys($banners)));
            foreach($images AS $image)
                $banners[$image->relation_id]->image = $image;
        }
        return $banners;
    }

    public function update_banner($banner_id, $banner)
    {
        $query = $this->db->placehold('UPDATE banners SET ?% WHERE id = ? LIMIT 1', $banner, (int)$banner_id);
        $this->db->query($query);
        return $banner_id;
    }

    public function add_banner($banner)
    {
        $query = $this->db->placehold('INSERT INTO banners SET ?%', $banner);
        $this->db->query($query);
        return $this->db->insert_id();
    }

    public function delete_banner($id)
    {
        $this->db->query("SELECT * FROM banners WHERE id = ? LIMIT 1", (int)$id);
        if($banner = $this->db->result())
        {
            if($images = $this->images->get_images(array('relation_id'=>$id, 'relation'=>'banners')))
                $this->images->delete_images(array_keys($images));
            $this->db->query('DELETE FROM banners WHERE id = ? LIMIT 1', (int)$id);
        }
    }
}
