<?PHP
require_once('api/Simpla.php');

class ServiceAdmin extends Simpla
{
    private $allowed_image_extentions = array('png', 'gif', 'jpg', 'jpeg', 'ico');

    public function fetch()
    {
        if ($this->request->method('POST')) {
            $id = $this->request->post('id', 'integer');
            $db_page = $this->services->get($id);

            $page = new stdClass();
            $page->id = $id;
            $page->parent = $this->request->post('parent', 'integer');

            $page->name = $this->request->post('name');
            $page->header = $this->request->post('header');
            $page->url = $this->request->post('url');

            $page->meta_title = $this->request->post('meta_title');
            $page->meta_keywords = $this->request->post('meta_keywords');
            $page->meta_description = $this->request->post('meta_description');

            $page->introtext = $this->request->post('introtext');
            $page->toptext = $this->request->post('toptext');
            $page->body = $this->request->post('body');
            $page->bottext = $this->request->post('bottext');

            $page->menu_id = $this->services->menu_id;
            $page->visible = $this->request->post('visible', 'boolean');
            $page->show_home = $this->request->post('show_home', 'boolean');
            $page->show_service = $this->request->post('show_service', 'boolean');

            $page->works_url = $this->request->post('works_url');
            $page->works_url_text = $this->request->post('works_url_text');

            $page->body = str_replace('<p>&nbsp;</p>', '', $page->body); //
            $page->body = str_replace('<div class="col-sm-6 mb">&nbsp;</div>', '', $page->body); // <div class="zooming2-title">'.$title.'</div>

            $page->body = preg_replace('~<div class="col-sm-6 mb"><img(.*)src="(.*)/thumbs/400x300cp/(.*)"(.*)></div>~Uis', '<img$1src="$2/$3"$4>', $page->body);
            $page->body = preg_replace('~<div class="col-sm-6 mb">.*<div class="zooming2-title">.*</div>.*<img(.*)src="(.*)/thumbs/400x300cp/(.*)"(.*)></div>~Uis', '<img$1src="$2/$3"$4>', $page->body);

            // Связанные товары
            if (is_array($this->request->post('related_products'))) {
                foreach ($this->request->post('related_products') as $p) {
                    $rp[$p]->related_id = $p;
                    $rp[$p]->type = 'product';
                }
                $related_objects = $rp;
            }

            // Связанные статьи
            if (is_array($this->request->post('related_pages'))) {
                foreach ($this->request->post('related_pages') as $p) {
                    $rp[$p]->related_id = $p;
                    $rp[$p]->type = 'page';
                }
                $related_objects = $rp;
            }

            if (is_array($this->request->post('related_articles'))) {
                foreach ($this->request->post('related_articles') as $p) {
                    $rp[$p]->related_id = $p;
                    $rp[$p]->type = 'article';
                }
                $related_objects = $rp;
            }

            ## Не допустить одинаковые URL разделов.
            if (($p = $this->services->get($page->url)) && $p->id != $page->id) {
                $this->design->assign('message_error', 'url_exists');
            } else {
                // url брендовых страниц
                /*if(!empty($db_page->brand_id) && ($brand = $this->services->get_brand($db_page->brand_id))) {
                    $page->url = $brand->url;
                }*/

                if (empty($page->id)) {
                    $page->id = $this->pages->add_page($page);
                    $this->services->set_visible($page->id, $page->visible);
                    $this->services->fix_positions();
                    $page = $this->services->get($page->id);
                    $this->design->assign('message_success', 'added');
                } else {
                    $this->services->update($page->id, $page);
                    $page = $this->services->get($page->id);
                    $this->design->assign('message_success', 'updated');
                }

                // Удаление изображения
                if ($this->request->post('delete_image')) {
                    $this->pages->delete_image($page->id);
                }
                // Загрузка изображения
                $image = $this->request->files('image');

                if (!empty($image['name']) && in_array(strtolower(pathinfo($image['name'], PATHINFO_EXTENSION)), $this->allowed_image_extentions)) {
                    if ($image_name = $this->image->upload_image($image['tmp_name'], $image['name'])) {
                        $this->pages->delete_image($page->id);
                        $this->pages->update_page($page->id, array('image' => $image_name));
                        $page->image = $image_name;
                    } else {
                        $this->design->assign('error', 'error uploading image');
                    }
                }
            }

            // Связанные объекты
            $query = $this->db->placehold('DELETE FROM __pages_objects WHERE page_id=?', $page->id);
            $this->db->query($query);

            if (is_array($related_objects)) {
                $pos = 0;
                foreach ($related_objects as $i => $related_object)
                    $this->pages->add_related_object($page->id, $related_object->related_id, $related_object->type);
            }

            //страница услуги и услуга не брендовая
            if (intval($page->menu_id) === $this->services->menu_id && !$page->brand_id) {
                // создаём или обновляем её брендовые страницы
                $this->services->create_brands_pages($page->id, $this->request->post('brands'));
            }
        } else {
            $id = $this->request->get('id', 'integer');
            if (!empty($id) && !empty($page = $this->services->get($id))) {

            } else {
                $page = new stdClass();
                $page->menu_id = $this->services->menu_id;
                $page->visible = 1;
            }
        }

        $this->design->assign('page', $page);
        $this->design->assign('root_url', $this->services->get_root_url());

        // Связанные объекты
        $related_objects = $this->pages->get_related_objects(array('id' => $page->id));

        if (!empty($related_objects)) {
            $r_products = array();
            $r_pages = array();
            $r_articles = array();

            foreach ($related_objects as &$r_p)
                if ($r_p->type == 'product') $r_products[$r_p->object_id] = &$r_p;
                elseif ($r_p->type == 'page') $r_pages[$r_p->object_id] = &$r_p;
                elseif ($r_p->type == 'article') $r_articles[$r_p->object_id] = &$r_p;


            if (!empty($r_products)) {
                $temp_products = $this->products->get_products(array('id' => array_keys($r_products)));
                foreach ($temp_products as $temp_product)
                    $r_products[$temp_product->id] = $temp_product;
            }

            if (!empty($r_pages)) {
                $temp_pages = $this->pages->get_pages(array('id' => array_keys($r_pages)));
                foreach ($temp_pages as $temp_page)
                    $r_pages[$temp_page->id] = $temp_page;
            }

            if (!empty($r_articles)) {
                $temp_pages = $this->articles->get_articles(array('id' => array_keys($r_articles)));
                foreach ($temp_pages as $temp_page)
                    $r_articles[$temp_page->id] = $temp_page;
            }

            $page->body = preg_replace_callback('~<img.*class=.*zooming2[^>].*>~Uis', array($this, 'resizeBodyImages'), $page->body);

            $this->design->assign('related_products', $r_products);
            $this->design->assign('related_pages', $r_pages);
            $this->design->assign('related_articles', $r_articles);
        }

        // Меню выбора родительской страницы (услуги)
        $select_items = $this->pages->get_select_pages(array('parent' => $this->services->root_id));
        $this->design->assign('select_items', $select_items);

        //привязанные к услуге брендовые страницы
        if (!$page->brand_id) {
            $this->design->assign('service_brands', $this->services->get_service_brands($page->id));
        }
        // все марки
        $this->design->assign('brands', $this->services->get_all_brands());

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

    function resizeBodyImages($m)
    {
        preg_match('~src=["\'](.*)["\']~Uis', $m[0], $img);
        preg_match('~title=["\'](.*)["\']~Uis', $m[0], $title);
        preg_match('~alt=["\'](.*)["\']~Uis', $m[0], $alt);

        if (empty($img[1])) return $m[0];
        $alt = isset($alt[1]) ? $alt[1] : '';
        $title = isset($title[1]) ? $title[1] : '';
        $src = Img::get(urldecode($img[1]), array('width' => 400, 'height' => 300, 'crop' => true));
        $tl = $title ? '<div class="zooming2-title">' . $title . '</div>' : '';
        return '<div class="col-sm-6 mb">' . $tl . '<img alt="' . $alt . '" class="zooming2" src="' . $src . '" title="' . $title . '"></div>' . "\n";
    }  


}