<?php
class BannersAdmin extends Buyers
{
    public function fetch()
    {
        if($this->request->method('post'))
        {
            //сохраняем сортировку на js т.к. у каждого баннера своя форма, а не единая в отличие от товаров
            if($positions = $this->request->post('positions'))
            {
                foreach($positions AS $num => $arr)
                {
                    $id = $arr[0];
                    $position = $arr[1];

                    $ids[$num] = $id;
                    $sorting[] = $position;
                }

                sort($sorting);
                foreach($sorting as $num => $position)
                    $this->banners->update_banner($ids[$num], array('position'=>$position));

                exit(true);
            }

            $banner_id = $this->request->post('id', 'integer');
            $banner = $this->request->post('banner');
            $old_image = $this->request->post('old_image', 'string');

            if(empty($banner_id))
            {
                $status = "added";
                $banner_id = $this->banners->add_banner($banner);
                $this->banners->update_banner($banner_id, array('position'=>$banner_id));
            }
            else
            {
                $status = "updated";
                $this->banners->update_banner($banner_id, $banner);
                //удалим фотку если есть новая
                if($old_image && !empty($images))
                    $this->images->delete_images($old_image);
            }

            $images = $this->images->update_images($banner_id, $this->images->banners_images_dir);
            $this->request->redirect(array('module'=>'BannersAdmin','message_success'=>$status));
        }

        if($delete_id = $this->request->get('delete', 'integer'))
        {
            $this->banners->delete_banner($delete_id);
            $this->request->redirect(array('module'=>'BannersAdmin','message_success'=>'deleted'));
        }

        $filter = array('sort'=>'position');

        $banners = $this->banners->get_banners($filter);
        $this->design->assign('banners', $banners);
        $this->design->assign('pages', $this->pages->get_pages_tree());
        $this->design->assign('all_pages', $this->pages->get_all_pages());

        return $this->design->fetch('banners.tpl');
    }
}
