<?php

class ControllerHome extends Controller
{
    public function index()
    {
        $customer =& $this->locator->get('customer');

        $database =& $this->locator->get('database');

        $config   =& $this->locator->get('config');

        $currency =& $this->locator->get('currency');

        $language =& $this->locator->get('language');

        $image    =& $this->locator->get('image');

        $module   =& $this->locator->get('module');

        $response =& $this->locator->get('response');

        $tax      =& $this->locator->get('tax');

        $template =& $this->locator->get('template');

        $url      =& $this->locator->get('url');

        $cart     =& $this->locator->get('cart');

        $user     =& $this->locator->get('user');

        $request  =& $this->locator->get('request');

        $session  =& $this->locator->get('session');

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

        $view = $this->locator->create('template');

	if ( !$customer->isLogged())
	{	
//		header('Location: gate.html');
//		exit();	
	} 
//========================================================================================================================================================================================
/*
        $ip_database = $database->getRow("select * from ipligence WHERE ip_from <= INET_ATON('".$_SERVER['REMOTE_ADDR']."') and ip_to >= INET_ATON('".$_SERVER['REMOTE_ADDR']."')");
        if ($ip_database && strcasecmp($ip_database['country_name'],"CHINA")!=0) {
            //record visitor
            date_default_timezone_set('Asia/Hong_Kong');
            $start_time=date('Y-m-d 00:00:00',time());
            $end_time=date('Y-m-d 23:59:59',time());

            $today_visitor=$database->getRow("select visitor_id ,ip_address from visitors where china_time BETWEEN '".$start_time."' and '".$end_time."' and ip_address = '".$_SERVER["REMOTE_ADDR"]."' order by china_time desc");

            if ($today_visitor) {
                $visitor_sql = "update visitors set source='?', browser='?', country='?', china_time='?', times=times+1 where visitor_id = '?'";
                $database->query($database->parse($visitor_sql,@$_SERVER['HTTP_REFERER'],$_SERVER['HTTP_USER_AGENT'],$ip_database['country_name'],date('Y-m-d H:i:s',time()),$today_visitor['visitor_id']));
            } else {
                $visitor_sql="insert into visitors set ip_address='?',source='?',browser='?',country='?',china_time='?'";
                $database->query($database->parse($visitor_sql,@$_SERVER["REMOTE_ADDR"],$_SERVER['HTTP_REFERER'],$_SERVER['HTTP_USER_AGENT'],$ip_database['country_name'],date('Y-m-d H:i:s',time())));
            }
     } */
//========================================================================================================================================================================================

        $home_setting=$database->getRows("select status,count,setting_height from home_setting");

        $view->set('title', $language->get('title', $config->get('config_store')));

        $view->set('heading_title', $language->get('heading_title', $config->get('config_store')));

        if (!$customer->isLogged()) {

            $view->set('text_greeting', $language->get('text_greeting', $url->href('account_login'), $url->href('account_create')));

        } else {

            $view->set('text_greeting', $language->get('text_logged', $customer->getFirstName()));

        }

        $view->set('text_latest', $language->get('text_latest'));

// Recommend Categories
         $recommend_categories = array();

        if ($home_setting[2]['status']==1) {
            $recommend_category=$database->getRow("select category_id from `category` WHERE recommend=1");
            if ($recommend_category) {
            $recommend_category_id=$recommend_category['category_id'];
 $categories_rows=$database->getRows("select ct.category_id, ctd.name from `category` ct left join `category_description` ctd on ct.category_id = ctd.category_id where ct.parent_id=$recommend_category_id order by recommend DESC");

              foreach ($categories_rows as $k=>$category_row) {

                 $category_id = $category_row['category_id'];
  $product_rows=$database->getRows("SELECT pd.name,p.product_id,p.image_id,p.price,p.sold FROM `product` p LEFT JOIN `product_description` pd on p.product_id = pd.product_id WHERE p.category_id=$category_id");
                  $recommend_products = array();
                  foreach ($product_rows as $k=>$product_row) {
                    $product_image_id=$product_row['image_id'];
                    $image_row=$database->getRow("select filename from image where image_id=$product_image_id");
                    $recommend_products[] = array(
                    'product_id'  => $product_row['product_id'],

                    'name' => $product_row['name'],

                    'href'  => $url->href('product', FALSE, array('product_id' => $product_row['product_id'])),

                    'thumb' => $image->resize($image_row['filename'], $config->get('config_image_width'), $config->get('config_image_height')),

                    'price' => $currency->format($product_row['price']),

                    'market_price' => $currency->format(1.8*$product_row['price']),

                    'sold'  => $product_row['sold'],
                    
                    'review_info'=>$database->getRow("select avg(rating) as avg, count(review_id) as count from `review` where product_id=".$product_row['product_id']),

                    'href_addtowishlist' => $url->href('my_wishlist', 'addtowishlist', array('product_id' => $product_row['product_id']))
            );

//print_r($recommend_products);exit;
     }
                    $recommend_categories[] = array(
                            'name'  => $category_row['name'],

                            'products' => $recommend_products
                        );
                }
            }
        }

    $view->set('recommend_categories', $recommend_categories);

  // RECENT ORDERS

        if ($home_setting[0]['status']==1) {

            $order_data = array();

            $result_order=$database->getRows("select o.order_id, o.reference, o.firstname, o.lastname, o.date_added, o.total, o.currency, o.value,o.payment_city,o.payment_zone,o.payment_country,o.order_status_id from `order` AS o where 1 order by o.order_id desc limit 60"); // where o.date_added>='".date('Y-m-d h:i:s',time()-86400*7)."'

            if (count($result_order)<12) {
                $result_order=$database->getRows("select o.order_id, o.reference, o.firstname, o.lastname, o.date_added, o.total, o.currency, o.value,o.payment_city,o.payment_zone,o.payment_country,o.order_status_id from `recent_order` AS o where 1 order by o.order_id desc limit 60");

            }
                       date_default_timezone_set('Asia/Hong_Kong');

                    $day_0=date("Y-m-d");

                    $day_1=date("Y-m-d",strtotime("-1 day"));

                    $day_2=date("Y-m-d",strtotime("-2 day"));

                    $day_3=date("Y-m-d",strtotime("-3 day"));

                    $order_count=count($result_order);

                foreach ($result_order as $k=>$result) {

                    $order_status_info=$database->getRow("select name as status_name from order_status where order_status_id='".$result['order_status_id']."'");

                      $country_info=$database->getRow("select c.name,c.icon from country as c where c.name='".$result['payment_country']."'");

                      $k++;

                      if ($k>0 && $k<25) {

                          $order_date=$day_1;

                      } elseif ($k >4 && $k<8) {

                          $order_date=$day_2;

                      } else {

                          $order_date=$day_3;

                      }

                    $order_data[] = array(

                            'order_id'   => $result['order_id'], // 'reference'   => $result['reference'],

    'customer'   => '<label>'.$result['payment_city'].', '.$result['payment_zone'].', '.$result['payment_country'].' '.'<img width="16" height="16"  src="../icon/country/'.$country_info['icon'].'">'.'</label>',

                            'date_added' => '<label>'.$order_date.' '.date('h:i:s',strtotime($result['date_added'])).'</label>', // date('Y-m-d h:i:s',strtotime($result['date_added']))

                            'total'      => '<label>'.$currency->format($result['total'], $result['currency'], $result['value']).'</label>',

                            'status_name'=> '<label>'.$order_status_info['status_name'].'</label>',

                            'href'       => $url->href('order_view', false, array('order_id' => $result['order_id']))

                      );
            }

            $view->set('latest_orders', $order_data);

        }

        $view->set('home_setting', $home_setting);

        // Append header and foot
        $template->set($module->fetchTemplate('header'));

        // Append category
        $view->set($module->fetchTemplate('category'));

        // Append flash
        $view->set($module->fetchTemplate('flash'));

        $template->set('content', $view->fetch('content/home.tpl'));

        $template->set($module->fetchTemplate('footer'));

        $response->set($template->fetch('layout.tpl'));

    }

}
