<?php

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

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

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

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

        $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');

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

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

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

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

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

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

         if ($request->get('product_id', 'post')) {
            $cart->add($request->get('product_id', 'post'), 1, $request->get('option', 'post'));
          }

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

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

        if ($cart->hasProducts()) {

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

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

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

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

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

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

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

                      $view->set('error_outofstock', ((!$cart->hasStock()) && ($config->get('config_stock_check')) ? $language->get('error_stock') : NULL));

                    $subtotal_discount=0;
                    $country_cost_usd=$shipping_method_usd=0;
                    $country_icon=$country_name='';
                    $shipping_name='EMS';
                    $ship_method_name='';
                    $vip_info=array('vip_rank'=>'General Buyer', 'discount'=>0 );

                    $country_id=$request->get('country_id', 'post');
                    if (empty($country_id)) {
                        if ($session->get('shipping_country')) {
                             $country_row=$database->getRow("select country_id from country where name LIKE '".$session->get('shipping_country')."'");
                             $country_id=$country_row['country_id'];
                        } else {
                            $country_id=$customer->getCountryId();
                        }
                    }
                    $country_id=empty($country_id)?223:$country_id;
                    $shipping_method_id=$request->get('shipping_method_id', 'post');
                    if (empty($shipping_method_id)) {
                        if ($session->get('shipping_name')) {
                             $ship_row=$database->getRow("select ship_id from ship_manage where name LIKE '".$session->get('shipping_name')."'");
                             $shipping_method_id=$ship_row['ship_id'];
                        }
                    }
                    $shipping_method_id=empty($shipping_method_id)?3:$shipping_method_id;
 //                    echo "<script>alert('SHIPPING_METHOD_ID=$shipping_method_id');</script>";

                    $country_row=$database->getRow("SELECT `name`, `icon`, `extra_usd` FROM `country` WHERE `country_id` = '".$country_id."'");
                     if ($country_row) {

                         $country_cost_usd=$country_row['extra_usd'];
                         $country_name=$country_row['name'];
                         $country_icon=$country_row['icon'];

                     }

                   $view->set('country_name',$country_name);
                   $view->set('country_icon',$country_icon);

                   if ($customer->getId()) {

                      $vip_info=$database->getRow("select v.vip_rank,v.discount,c.current_points from customer as c left join vip as v on (c.vip_rank=v.vip_rank) where customer_id='".$customer->getId()."'");
                      $vip_discount_array=explode('%',$vip_info['discount']);
                      $subtotal_discount=$vip_discount_array[0];
                      $vip_info=array(
                         'vip_rank'=>$vip_info['vip_rank'],
                           'discount'=>$subtotal_discount,
                      );
                   }
                $view->set('vip_info',$vip_info);

                $subtotal_usd=$cart->getSubtotal();
                $view->set('subtotal_usd', $subtotal_usd);
                $view->set('subtotal_discount', $subtotal_discount);

                $ship_rows=$database->getRows("select ship_id,name,register_fee from ship_manage where 1"); //ship_id in (11,12)
                $shipping_methods=array();
                foreach ($ship_rows as $key => $row) {

                        if ($shipping_method_id==$row['ship_id']) {
 //                       	echo "<script>alert('shipping_method_id=row_id');</script>";
                            $shipping_method_usd=$row['register_fee'];
                            $shipping_name=$row['name'];
                            $ship_method_name=$shipping_name.' + <b>'.$currency->format($row['register_fee']).'</b>';
                        }

                     $shipping_methods[]=array( 'ship_id'=>$row['ship_id'],
                                                'name'=>$row['name'],
                                                'ship_fee'=>$currency->format($row['register_fee'])
                                                );
                }
//        echo "<script>alert('SHIP_METHOD_NAME=$ship_method_name');</script>";
                  $view->set('shipping_methods',$shipping_methods);
                  $view->set('ship_method_name',$ship_method_name);
                  $view->set('countries', $database->cache('country', "select * from country where allow_ship=1 and icon!='' order by name"));

                $shipping_cost_usd=round($country_cost_usd+$shipping_method_usd,2);
                $grand_total_usd=round($subtotal_usd*(1-$subtotal_discount/100)+$shipping_cost_usd,2);

                $view->set('country_cost',$currency->format($country_cost_usd));
                $view->set('shipping_cost',$currency->format($country_cost_usd));
                $view->set('grand_total',$currency->format($grand_total_usd));
                $view->set('subtotal', $currency->format($cart->getSubtotal()));

                  $product_array2=array();
                  foreach ($cart->getProducts() as $product) {
                  $product_array = $product;
                  $product_array['price']=$currency->format($product['price']);
                  $product_array['discount_price']=$currency->format($product['discount_price']);
                  $product_array['total']=$currency->format($product['total']);
                  $product_array['href']=$url->href('product', FALSE, array('product_id' => $product['product_id']));

                $product_array2[] = $product_array;
                  }
//		      	var_dump($product_array2); exit;
                  $view->set('products', $product_array2);
                $view->set('country_id', $country_id);
                $view->set('shipping_method_id', $shipping_method_id);

                $view->set('cart', $url->href('cart'));

                $session->set('shipping_country', $country_name);
                $session->set('shipping_cost', $shipping_cost_usd);
                $session->set('shipping_name', $shipping_name);

                  if ($request->has('checkout', 'post')) {
                    $response->redirect($url->ssl('checkout_shipping'));
                  }

        } else {
             $view->set('heading_title', $language->get('heading_title'));
              $view->set('text_error', $language->get('text_error'));
            $view->set('continue', $url->href(''));
        }
        $view->set('customer_logged', $customer->isLogged());
        $template->set('content', $view->fetch('content/cart.tpl'));
        $template->set($module->fetchPublic());
          $response->set($template->fetch('layout.tpl'));
  }

    public function calculate()
    {
        $database  =& $this->locator->get('database');
        $request  =& $this->locator->get('request');
        $currency =& $this->locator->get('currency');
        $session  =& $this->locator->get('session');

        $subtotal_usd=$request->has('subtotal_usd')?$request->get('subtotal_usd'):0;
        $subtotal_discount=$request->has('subtotal_discount')?$request->get('subtotal_discount'):0;
        $shipping_to_usd=$shipping_method_usd=0;
        $grand_total=0;
        if ($request->has('country_id')) {
            $country_id=$request->get('country_id', 'get');
            $country_info=$database->getRow("SELECT `name`, `extra_usd`, `allow_ship`, `ship_id` FROM `country` WHERE `country_id` = '".$country_id."'");
            if ($country_info) {
            $shipping_to_usd=$country_info['extra_usd'];
            $session->set('shipping_country', $country_info['name']);
            }
        }
        if ($request->has('shipping_method_id')) {
            $shipping_method_id=$request->get('shipping_method_id');
            $shipping_row=$database->getRow("SELECT `name`, `register_fee` FROM `ship_manage` WHERE `ship_id` = '".$shipping_method_id."'");
            if ($shipping_row) {
                $shipping_method_usd=$shipping_row['register_fee'];
                $session->set('shipping_name', $shipping_row['name']);
            }
        }
        $shipping_cost_usd=$shipping_to_usd+$shipping_method_usd;
        $session->set('shipping_cost', $shipping_cost_usd);
        $shipping_to=$currency->format($shipping_to_usd);
        $grand_total=$currency->format(round($subtotal_usd*(1-$subtotal_discount/100)+$shipping_cost_usd,2));
        echo $shipping_to.'|'.$grand_total.'|'.$shipping_cost_usd;
    }

    public function removeAll()
    {
        $database  =& $this->locator->get('database');
        $customer =& $this->locator->get('customer');
        $cart     =& $this->locator->get('cart');

        if ($customer->getId()) {
            $database->query("update customer set cart = NULL where customer_id = ".$customer->getId());
        }
        $cart->clear();
        echo "<script>window.history.back(-1);</script>";
    }

    public function ajax_removeproduct()
    {
        $database  =& $this->locator->get('database');
        $request = &$this->locator->get('request');
        $response = &$this->locator->get('response');
        $customer =& $this->locator->get('customer');
        $cart     =& $this->locator->get('cart');
        $calculate =& $this->locator->get('calculate');
        $currency =& $this->locator->get('currency');

        $product_key = $request->get('product_key');
        $cart->remove($product_key);
        if ( intval( $cart -> getSubtotal() ) != 0 ) {
          $gShow['sub_total'] = $currency->format($cart -> getSubtotal());
          $gShow['calculate'] = $calculate->getTotalText();
          $gShow['errcode'] = 0;
          $gShow['errmsg'] = 'success';
        } else {
          $gShow['errcode'] = 1;
          $gShow['errmsg'] = 'empty cart';
        }
        $response->set(json_encode($gShow));
    }
    public function ajax_chg_cart_qty()
    {
        $database = & $this->locator->get('database');
        $request  = & $this->locator->get('request');
        $response = & $this->locator->get('response');
        $customer = & $this->locator->get('customer');
        $cart     = & $this->locator->get('cart');
        $calculate =& $this->locator->get('calculate');
        $currency =& $this->locator->get('currency');

        $product_key = $request->get('product_key');
        $qty         = (int) $request->get('product_qty');
        if ($qty > 0) {
            $cart -> update($product_key, $qty);
            $product = $cart -> products[$product_key];
            if ($product['price'] == $product['discount_price']) {
              $product['price'] = $currency->format($product['price']);
              $product['discount_price'] = '';
            } else {
              $product['price'] = $currency->format($product['price']);
              $product['discount_price'] = $currency->format($product['discount_price']);
            }
            $product['total'] = $currency->format($product['total']);
            $gShow['product']   = $product;
            $gShow['sub_total'] = $currency->format($cart -> getSubtotal());
            $gShow['calculate'] = $calculate->getTotalText();
            $gShow['errcode'] = 0;
            $gShow['errmsg'] = 'success';
        } else {
            $gShow['errcode'] = 1;
            $gShow['errmsg'] = '';
        }
        $response->set(json_encode($gShow));
    }

    public function ajax_batch_chg_cart_qty()
    {
        $database = & $this->locator->get('database');
        $request  = & $this->locator->get('request');
        $response = & $this->locator->get('response');
        $customer = & $this->locator->get('customer');
        $cart     = & $this->locator->get('cart');

        $cart_qty = $request->get('cart_qty', 'post');

        if (is_array($cart_qty)) {
            foreach ($cart_qty as $cartQty) {
                $qty         = (int) $cartQty['product_qty'];
                $product_key = $cartQty['product_key'];
                if ($qty > 0) {
                    $cart -> update($product_key, $qty);
                }
            }
        }
    }

    public function ajax_cart_header_block()
    {
        $config   =& $this->locator->get('config');
        $cart     =& $this->locator->get('cart');
        $currency =& $this->locator->get('currency');
        $customer =& $this->locator->get('customer');
        $language =& $this->locator->get('language');
        $url      =& $this->locator->get('url');
        $database =& $this->locator->get('database');
        $template =& $this->locator->create('template');
        $calculate =& $this->locator->get('calculate');
        $image    =& $this->locator->get('image');
        $language->load('extension/module/cart.php');
        $template->set('text_cart', $language->get('text_cart'));
        $cart_quantity = 0;
        $cart_product_data=array();
        foreach ($cart->getProducts() as $key => $result) {
          $product_image_info=$database->getRow("select p.product_id,p.image_id,i.filename from product p left join image i on i.image_id=p.image_id where p.product_id='".$result['product_id']."' ");
          $cart_quantity = $cart_quantity + $result['quantity'];

          $cart_product_data[]=array(
               'product_id'=>$result['product_id'],
               'thumb' =>$image->resize($product_image_info['filename'], 100, 100),
               'price' =>$currency->format($result['price']),
               'name' =>$result['name'],
               'quantity'=>$result['quantity'],
               'href_remove'=>$cart->remove($result['product_id']),
               'product_key'=> $key,
          );
        }
        $template->set('cart_quantity', $cart_quantity);
        $cart_subtotal = $calculate->getTotalText();
        $template->set('cart_subtal', $cart_subtotal);
        $template->set('cart_products', $cart_product_data);

        echo $template->fetch('module/cart.tpl');
    }
}
