<?php
class ControllerCategory extends Controller
{
    public function index()
    {
        ini_set("display_errors", "On");
        error_reporting(1);
        date_default_timezone_set('Asia/Hong_Kong');

        $config   = $this->locator->get('config');
        $currency = $this->locator->get('currency');
        $database = $this->locator->get('database');
        $language = $this->locator->get('language');
        $image    = $this->locator->get('image');
        $module   = $this->locator->get('module');
        $request  = $this->locator->get('request');
        $response = $this->locator->get('response');
        $session  = $this->locator->get('session');
        $tax      = $this->locator->get('tax');
        $template = $this->locator->get('template');
        $url      = $this->locator->get('url');
        $view = $this->locator->create('template');

        $language->load('controller/category.php');

        if ($request->has('page')) {
          $session->set(($request->has('sort') ? 'category.' . $request->get('sort') . '.page' : 'category.page'), $request->get('page'));
        }
        $page =$request->has('sort') ? $session->get('category.' . $request->get('sort') . '.page') : $session->get('category.page');
        $page=($page==NULL)?1:$page;

        $sort=$request->has('sort')?$request->get('sort'):1;
        $view->set('sort', $sort);
        $view->set('path', $request->has('path')?$request->get('path'):0);

        $category_id = (int) ((!$request->get('path')) ? '0' : (int) end(explode('_', $request->get('path'))));
        $category_info = $database->getRow("select name from category c left join category_description cd on (c.category_id = cd.category_id) where c.category_id = $category_id");

        if ($category_info) {

            $view->set('heading_title', $category_info['name']);

            if (($database->countRows("select product_id from product where category_id=$category_id")) || ($database->countRows("select parent_id from category where parent_id=$category_id"))) {

                $category_data = array();

                $sub_category_results = $database->cache('category-'.$category_id.'-sub_categories', "select c.category_id,cd.name,i.filename from category c left join category_description cd on (c.category_id = cd.category_id) left join image i on (c.image_id = i.image_id) where c.parent_id = $category_id and c.status = 1 order by c.sort_order");

                foreach ($sub_category_results as $c_result) {
                      $category_data[] = array(
                        'name'  => $c_result['name'],
                        'href'  => $url->href('category', FALSE, array('path' => ($request->get('path')) ? $request->get('path') . '_' . $c_result['category_id'] : $c_result['category_id'])),
                        'thumb' => $image->resize($c_result['filename'], $config->get('config_image_width'), $config->get('config_image_height'))
                      );
                }

                $view->set('categories', $category_data);

                $product_data = array();
                $sql="select p.product_id,i.filename,pd.name,p.quantity,p.sold,p.price,p.status, p.date_added from product p left join image i on (p.image_id = i.image_id) left join product_description pd on (p.product_id = pd.product_id) where p.category_id = $category_id";
                switch ($sort) {
                    case 1:
                        {
                            $sql.=" order by p.date_added asc";
                            break;
                        }
                    case 2:
                        {
                            $sql.=" order by p.sold desc";
                            break;
                        }
                    case 3:
                        {
                            $sql.=" order by p.price asc";
                            break;
                        }
                    case 4:
                        {
                            $sql.=" order by p.price desc";
                            break;
                        }
                    default:
                        break;
                }
                $sub_product_results = $database->cache('category-'.$category_id.'-sub_products', $database->splitQuery($sql, $page, $config->get('config_max_rows')));

                foreach ($sub_product_results as $p_result) {

                      $product_data[] = array(
                        'name'  => $p_result['name'],
                        'product_id' => $p_result['product_id'],
                        'href'  => $url->href('product', FALSE, array('path' => $request->get('path'), 'product_id' => $p_result['product_id'])),
                        'thumb' => $image->resize($p_result['filename'], $config->get('config_image_width'), $config->get('config_image_height')),
                        'price' => $currency->format($p_result['price']),
                        'sold' =>  $p_result['sold'],
                        'review_info'=>$database->getRow("select avg(rating) as avg, count(review_id) as count from `review` where product_id=".$p_result['product_id']),
                        'date_added'=>$p_result['date_added'],
                        'quantity' =>  $p_result['quantity'],
                        'status' =>  $p_result['status'],
                        'market_price' => $currency->format($p_result['price']*1.7),
                        'href_addtowishlist' =>  $url->href('my_wishlist', 'addtowishlist', array('product_id' => $p_result['product_id']))
                      );
                }

                $page_data = array();
                  for ($i = 1; $i <= $database->getPages(); $i++) {
                    $page_data[] = array(
                        'text'  => $language->get('text_pages', $i, $database->getPages()),
                        'value' => $i
                    );
                  }
                $view->set('pages', $page_data);
                $view->set('page', $page);
                $view->set('href_new_arrivals', $url->href('category', NULL, array('path'=>$request->get('path'), 'sort'=>1)));
                $view->set('href_top_sellers', $url->href('category', NULL, array('path'=>$request->get('path'), 'sort'=>2)));
                $view->set('products', $product_data);
                $view->set('text_results', $database->getTotal());
                $view->set('text_product', $language->get('text_product'));

                $view->set('action', $url->href('category', FALSE, array('path' => $request->get('path'))));

                $template->set('content', $view->fetch('content/category.tpl'));
                $template->set($module->fetchPublic());
                $response->set($template->fetch('layout.tpl'));
              } else {
                $view->set('heading_title', $category_info['name']);
                $view->set('text_error', $language->get('text_empty'));
                $view->set('button_continue', $language->get('button_continue'));
                $view->set('breadcrumbs', $breadcrumb);
                $view->set('continue', $url->href(''));
                $template->set('content', $view->fetch('content/error.tpl'));
                $template->set($module->fetchPublic());
                $response->set($template->fetch('layout.tpl'));
              }
        }
    }

}
