<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Cart extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('content_model', 'content');
        $this->load->model('cart_model', 'cart');
        $this->load->model('area_model', 'area');
        $this->load->model('cart_items_model', 'cart_items');
        $this->load->model('package_model', 'package');
        $this->load->model('tray_category_model', 'trayCat');
        $this->load->model('tray_item_model', 'trayItem');
        $this->load->model('online_category_model', 'onlineCat');
        $this->load->model('online_item_model', 'onlineItem');
    }

    public function index() {
      //  $this->common_model->checkCartItems();
        $data['METATITLE'] = 'Cart | ' . $this->config->item('site_title');
        $data['METAKEYWORDS'] = $this->config->item('site_title') . ' Shopping cart';
        $data['METADESCRIPTION'] = $this->config->item('site_title') . ' Shopping cart';
        $data['page_name'] = 'full_cart';
        $data['cart_data'] = $this->cart->getCartDetail();
        $data['cart_items_data'] = $this->cart_items->getCartItemDetail();
        $this->load->view($this->config->item('template') . '/header', $data);
        $this->load->view($this->config->item('template') . '/full_cart');
        $this->load->view($this->config->item('template') . '/footer');
    }

    public function checkout() {
        $this->common_model->checkCartItems();
        $data['METATITLE'] = 'Checkout | ' . $this->config->item('site_title');
        $data['METAKEYWORDS'] = $this->config->item('site_title') . ' Checkout';
        $data['METADESCRIPTION'] = $this->config->item('site_title') . ' Checkout';
        $data['page_name'] = 'checkout';
        $data['area_list'] = $this->area->getAreaList();

        $this->load->view($this->config->item('template') . '/header', $data);
        $this->load->view($this->config->item('template') . '/checkout');
        $this->load->view($this->config->item('template') . '/footer');
    }

    public function getAreaCharges() {
        $area_id = $this->input->post('area_id');
        $this->session->set_userdata('area_id', $area_id);
        $area_detail = $this->common_model->getSingleRowFromAnyTable('area_id', $area_id, 'tbl_area_wise_delivery_charges');
        $data['charges'] = $charges = $area_detail->charges;
        $data['success'] = true;
        if($area_detail) {
        $area_data = array(
                'area_id' => $this->input->post('area_id'),
                'area_name' => $area_detail->area_name,
                'delivery_charges' => $area_detail->charges,
            );
        } else {
            $area_data = array(
                'area_id' => 0,
                'area_name' => '',
                'delivery_charges' => 0,
            );
        }
        $this->updateCartCost('', $area_data);
        $data['sidebar_cart'] = $this->load->view($this->config->item('template') . '/sidebar_cart', null, true);
        if (sizeof($charges) == 0) {
            $data['success'] = false;
        }
        echo json_encode($data);
        die;
    }

    public function addCartPackageItem() {
        if (!empty($_POST)) {
            $package_detail = $this->common_model->getSingleRowFromAnyTable('package_id', $this->input->post(package_id), 'tbl_packages');
            if ($this->session->userdata('no_of_people') < $package_detail->min_order_amount) {
                $this->session->set_flashdata('package_error', 'Minimum number of people for package should be ' . $package_detail->min_order_amount);
                redirect($_SERVER['HTTP_REFERER']);
                exit;
            }
            $selected_package_items = $this->input->post(package_items);
//                pr($selected_package_items);die;
            $total_additional_price = 0;
            $package_items_quantity = $this->input->post(package_item_quantity);
            foreach ($selected_package_items as $key => $value) {
                $is_item_default = $this->package->getSpecificationsbyPackageAndItem($this->input->post(package_id), $value);
                //pr($is_item_default);
                $item_detail = $this->common_model->getSingleRowFromAnyTable('pkg_item_id', $value, 'tbl_package_items');

                if ($is_item_default['item_type'] == 'default')
                    $item_price = '0';
                else
                    $item_price = $is_item_default['upgrade_price'];

                if ($is_item_default['is_upgradable'] == 'no')
                    $item_quantity = $this->input->post('no_of_people');
                else if ($is_item_default['is_upgradable'] == 'yes')
                    $item_quantity = $package_items_quantity[$key];
                if ($item_quantity != '') {
                    if ($item_quantity >= $is_item_default['min_people']) {
                        $total_item_price = $item_quantity * $item_price;
                        $all_package_items[] = array(
                            'item_name' => $item_detail->item_name,
                            'item_id' => $value,
                            'category_id' => $item_detail->category_id,
                            'item_price' => $item_price,
                            'item_type' => $is_item_default['item_type'],
                            'item_quantity' => $item_quantity,
                            'total_item_price' => $total_item_price,
                        );
                        $total_additional_price+=$total_item_price;
                    }
                }
            }
            $total_package_price = $total_additional_price + $package_detail->price;
            $data = array(
                'item_name' => $package_detail->name,
                'item_id' => $this->input->post(package_id),
                'unit_price' => $package_detail->price,
                'no_of_people' => $this->input->post('no_of_people'),
                'item_quantity' => $this->input->post('no_of_people'),
                'total_item_price' => $package_detail->price * $this->input->post('no_of_people') + $total_additional_price,
            );

            $cart_package_id = $this->cart_items->addCartPackage($data);
            $this->cart_items->addCartPackageItems($all_package_items, $cart_package_id);
            $this->updateCartCost();
            redirect('cart');
            exit();
        } else {
            redirect($_SERVER['HTTP_REFERER']);
            exit();
        }
    }
     public function addCartMealItem() {
        if (!empty($_POST) && $this->input->post('package_items')) {
            $package_detail = $this->common_model->getSingleRowFromAnyTable('package_id', $this->input->post(package_id), 'tbl_packages');
            $selected_package_items = $this->input->post('package_items');
            $total_additional_price = 0;
            $package_items_quantity = $this->input->post('package_item_quantity');
            foreach ($selected_package_items as $key => $value) {
                $is_item_default = $this->package->getSpecificationsbyPackageAndItem($this->input->post(package_id), $value);
                $item_detail = $this->common_model->getSingleRowFromAnyTable('pkg_item_id', $value, 'tbl_package_items');
                if ($is_item_default['item_type'] == 'default')
                    $item_price = '0';
                else
                    $item_price = $is_item_default['upgrade_price'];
                if ($is_item_default['is_upgradable'] == 'no')
                    $item_quantity = $this->input->post('no_of_people');
                else if ($is_item_default['is_upgradable'] == 'yes')
                    $item_quantity = $package_items_quantity[$key];
                if ($item_quantity != '') {
                    if ($item_quantity >= $is_item_default['min_people']) {
                        $total_item_price = $item_quantity * $item_price;
                        $all_package_items[] = array(
                            'item_name' => $item_detail->item_name,
                            'item_id' => $value,
                            'category_id' => $item_detail->category_id,
                            'item_price' => $item_price,
                            'item_type' => $is_item_default['item_type'],
                            'item_quantity' => 0,
                            'total_item_price' => $total_item_price,
                        );
                        $total_additional_price+=$total_item_price;
                    }
                }
            }
            $total_package_price = $total_additional_price + $package_detail->price;
            $online_category_name = $this->common_model->getSingleFieldFromAnyTable('online_cat_name', 'online_cat_id', $package_detail->online_cat_id, $this->onlineCat->tableName);
            $data = array(
                'item_name' => $package_detail->name,
                'item_id' => $this->input->post(package_id),
                'unit_price' => $package_detail->price,
                'category_id' => $package_detail->online_cat_id,
                        'category_name' => $online_category_name,
                'no_of_people' => 0,
                'item_quantity' => 1,
                'total_item_price' => $package_detail->price  + $total_additional_price,
            );

            $cart_package_id = $this->cart_items->addCartPackage($data);
            $this->cart_items->addCartPackageItems($all_package_items, $cart_package_id);
            $this->updateCartCost();
            redirect($_SERVER['HTTP_REFERER']);
            exit();
        } else {
            redirect($_SERVER['HTTP_REFERER']);
            exit();
        }
    }
public function addCartOnlineItem() {
        //   pr($_POST);die;
        if (!empty($_POST)) {
            $this->form_validation->set_rules('item_id', 'Item Name', 'trim|required');
            if ($this->form_validation->run()) {
                $unit_ids = $this->input->post('unit_id');
                 $item_quantity=$this->input->post('quantity');   
                foreach ($unit_ids as $key => $value) {
                
                $quantity=$item_quantity;
                    $previousCartItem = $this->cart_items->getCartItemByUnitAnditem($this->input->post('item_id'),$value,'online_item');
                    if (isset($previousCartItem) && !empty($previousCartItem)) {
                        $quantity+=$previousCartItem['item_quantity'];
                    }
                    $online_item_detail = $this->common_model->getSingleRowFromAnyTable('online_item_id', $this->input->post('item_id'), $this->onlineItem->tableName);
                    $online_unit_detail = $this->common_model->getSingleRowFromAnyTable('unit_id', $value, $this->onlineItem->tableOnlineUnits);
                    $online_category_name = $this->common_model->getSingleFieldFromAnyTable('online_cat_name', 'online_cat_id', $online_item_detail->category_id, $this->onlineCat->tableName);
//                $item_note='';
//                if($this->input->post(item_note)!=''){
//                    $item_note=$this->input->post(item_note);
//                }
                    $data = array(
                        'cart_item_id' => $previousCartItem['cart_item_id'],
                        'item_name' => $online_item_detail->item_name,
                        'item_id' => $this->input->post('item_id'),
//                    'item_note' => $item_note,
                    'item_type' => 'online_item',
                        'category_id' => $online_item_detail->category_id,
                        'category_name' => $online_category_name,
                        'unit_price' =>  $online_unit_detail->unit_prices,
                        'unit_id' => $value,
                        'unit_name' => $online_unit_detail->unit_name,
                        'no_of_people' => 0,
                        'item_quantity' => $quantity,
                        'item_note' => $this->input->post('product_note'),
                        'total_item_price' => $quantity * $online_unit_detail->unit_prices,
                    );
                    // pr($data);die;
                    $this->cart_items->addCartItems($data);
                $this->updateCartCost();
                }
                $data = array(
                    'page_content' => $this->load->view($this->config->item('template') . '/sidebar_cart', null, true),
                    'cart_items' => $this->cart_items->getCountCartItems(),
                );
                return $this->output
                                ->set_header("HTTP/1.0 200 OK")
                                ->set_content_type('application/json')
                                ->set_output(json_encode($data));
//                redirect($_SERVER['HTTP_REFERER']);
//                exit;
            }
        } else {
            echo 'false';
        }
    }
    public function addCartItem() {
        //   pr($_POST);die;
        if (!empty($_POST)) {
            $this->form_validation->set_rules('item_id', 'Item Name', 'trim|required');
            if ($this->form_validation->run()) {
                $unit_ids = $this->input->post('unit_id');
                // $item_quantity=$this->input->post('quantity');             
                $item_quantity = '1';
                foreach ($unit_ids as $key => $value) {
                    // $quantity = $item_quantity[$key];       
                    $quantity = '1';
                    $previousCartItem = $this->cart_items->getCartItemByUnitAnditem($this->input->post('item_id'), $value);
                    if (isset($previousCartItem) && !empty($previousCartItem)) {
                        $quantity+=$previousCartItem['item_quantity'];
                    }
                    $tray_item_detail = $this->common_model->getSingleRowFromAnyTable('tray_item_id', $this->input->post(item_id), $this->trayItem->tableName);
                    $tray_unit_detail = $this->common_model->getSingleRowFromAnyTable('unit_id', $value, $this->trayItem->tableTrayUnits);
                    $tray_category_name = $this->common_model->getSingleFieldFromAnyTable('tray_cat_name', 'tray_cat_id', $tray_item_detail->category_id, $this->trayCat->tableName);
//                $item_note='';
//                if($this->input->post(item_note)!=''){
//                    $item_note=$this->input->post(item_note);
//                }
                    $data = array(
                        'cart_item_id' => $previousCartItem['cart_item_id'],
                        'item_name' => $tray_item_detail->item_name,
                        'item_id' => $this->input->post('item_id'),
//                    'item_note' => $item_note,
                        'item_type' => 'item',
                        'category_id' => $tray_item_detail->category_id,
                        'category_name' => $tray_category_name,
                        'unit_price' => $tray_unit_detail->unit_prices,
                        'unit_id' => $value,
                        'unit_name' => $tray_unit_detail->unit_name,
                        'no_of_people' => $tray_unit_detail->no_of_people,
                        'item_quantity' => $quantity,
                        'total_item_price' => $quantity * $tray_unit_detail->unit_prices,
                    );
                    // pr($data);die;
                    $this->cart_items->addCartItems($data);
                }
                $this->updateCartCost();

                $data = array(
                    'page_content' => $this->load->view($this->config->item('template') . '/sidebar_cart', null, true),
                    'cart_items' => $this->cart_items->getCountCartItems(),
                );
                return $this->output
                                ->set_header("HTTP/1.0 200 OK")
                                ->set_content_type('application/json')
                                ->set_output(json_encode($data));
            }
        } else {
            echo 'false';
        }
    }

    public function incrementProductQuantity() {
        $cart_item_id = $this->input->post(cart_item_id);
        $cart_item_data = $this->cart_items->getCartItemByCartItemId($cart_item_id);
        $quantity = $cart_item_data['item_quantity'] + 1;
        if ($cart_item_data) {
            $data = array(
                'cart_item_id' => $cart_item_data['cart_item_id'],
                'item_quantity' => $quantity,
                'total_item_price' => $quantity * $cart_item_data['unit_price'],
            );
            $this->cart_items->updateCartItem($data);
            $this->updateCartCost();
            $data = array(
                'sidebar_cart' => $this->load->view($this->config->item('template') . '/sidebar_cart', null, true),
            );
            return $this->output
                            ->set_header("HTTP/1.0 200 OK")
                            ->set_content_type('application/json')
                            ->set_output(json_encode($data));
        } else {
            echo 'false';
        }
    }

    public function decrementProductQuantity() {
        $cart_item_id = $this->input->post(cart_item_id);
        $cart_item_data = $this->cart_items->getCartItemByCartItemId($cart_item_id);
        $quantity = $cart_item_data['item_quantity'] - 1;
        if ($cart_item_data['item_quantity'] == 1) {
            $this->cart_items->deleteCartItemByCartItemId($cart_item_id);
            $this->updateCartCost();
            $this->load->view($this->config->item('template') . '/sidebar_cart');
        } else if ($cart_item_data) {
            $data = array(
                'cart_item_id' => $cart_item_data['cart_item_id'],
                'item_quantity' => $quantity,
                'total_item_price' => $quantity * $cart_item_data['unit_price'],
            );
            $this->cart_items->updateCartItem($data);
            $this->updateCartCost();
            $this->load->view($this->config->item('template') . '/sidebar_cart');
        } else {
            echo 'false';
        }
    }

    public function applyCoupon() {
        if (!empty($_POST)) {
            $this->form_validation->set_rules('coupon_code', 'Coupon Code', 'trim|required');
            if ($this->form_validation->run()) {
                $coupon_data = $this->common_model->getSingleRowFromAnyTable('coupon_code', $this->input->post('coupon_code'), 'tbl_coupons');
                //  pr($coupon_data);
                if ($coupon_data) {
                    if ($coupon_data->status == 'inactive') {
                        $this->session->set_flashdata('cart_coupon_messages', 'This Coupon code is inactivated now.');
                        redirect($_SERVER['HTTP_REFERER']);
                        exit;
                    }
                    if ($coupon_data->expiration_date <= time()) {
                        $this->session->set_flashdata('cart_coupon_messages', 'This Coupon code Got Expired Now.');
                        redirect($_SERVER['HTTP_REFERER']);
                        exit;
                    }
                    $cart_data = $this->cart->getCartDetail();
                    if ($cart_data['sub_total'] < $coupon_data->minimum_order_amount) {
                        $this->session->set_flashdata('cart_coupon_messages', 'Your Amount Should be greater than ' . $coupon_data->minimum_order_amount);
                        redirect($_SERVER['HTTP_REFERER']);
                        exit;
                    }
                    $discount = 0;
                    if ($coupon_data->coupon_type == 'percentage') {
                        $coupon_percentage = $coupon_data->coupon_price;
                        $discount = $cart_data['sub_total'] * ($coupon_data->coupon_price / 100);
                    } else if ($coupon_data->coupon_type == 'money') {
                        $coupon_percentage = 0;
                        $discount = $coupon_data->coupon_price;
                    }
                    $coupon_data = array(
                        'coupon_id' => $coupon_data->coupon_id,
                        'coupon_code' => $coupon_data->coupon_code,
                        'discount' => $discount,
                        'coupon_percentage' => $coupon_percentage,
                    );
                    $this->updateCartCost($coupon_data);
                    $this->session->set_flashdata('cart_coupon_messages', 'Congratulations! Your Coupon Code Has Been Applied Successfully.');
                    redirect($_SERVER['HTTP_REFERER']);
                    exit;
                } else {
                    $this->session->set_flashdata('cart_coupon_messages', 'This Coupon Code Does not exist.');
                    redirect($_SERVER['HTTP_REFERER']);
                    exit;
                }
            } else {
                $this->session->set_flashdata('cart_coupon_messages', 'There is some Error with Form.');
                redirect($_SERVER['HTTP_REFERER']);
                exit;
            }
        }
    }

    public function deleteCartItem() {
        $cart_item_id = $this->input->post('cart_item_id');
        $this->cart_items->deleteCartItemByCartItemId($cart_item_id);
        $this->cart_items->deleteCartPackageItemByCartItemId($cart_item_id);
        $this->updateCartCost();
        $output = array(
            'cart_data' => $this->load->view($this->config->item('template') . '/sidebar_cart', null, true),
            'cart_items' => $this->cart_items->getCountCartItems(),
        );
        return $this->output
                        ->set_header("HTTP/1.0 200 OK")
                        ->set_content_type('application/json')
                        ->set_output(json_encode($output));
    }

    public function getCartPackageItems($cart_item_id) {
        $data['cart_items'] = $this->cart_items->getCartItemByCartItemId($cart_item_id);
        $data['package_detail'] = $package_detail = $this->common_model->getSingleRowFromAnyTable('package_id', $data['cart_items']['item_id'], 'tbl_packages');
        $data['cart_package_items'] = $this->cart_items->getCartPackageItemDetail($cart_item_id);
        $this->load->view($this->config->item('template') . '/cart_package_items', $data);
    }

    public function getCartMealItems($cart_item_id) {
        
        $data['cart_package_items'] = $this->cart_items->getCartPackageItemDetail($cart_item_id);
        $this->load->view($this->config->item('template') . '/cart_meal_items', $data);
    }
    
    public function updateCartCost($coupon_data = '', $area_data = '') {
        $sub_total = $this->cart_items->getCartItemsTotal();
        $sub_total = $sub_total['total_item_price'];
        $cart_data = $this->cart->getCartDetail();
        $discount = 0;
        $coupon_id = 0;
        $coupon_code = 0;
        $coupon_percentage = 0;
        $delivery_charges = 0;
        $area_id = 0;
        $area_name = 0;

        if ($coupon_data) {
            $discount = $coupon_data['discount'];
            $coupon_id = $coupon_data['coupon_id'];
            $coupon_code = $coupon_data['coupon_code'];
            $coupon_percentage = $coupon_data['coupon_percentage'];
        } else if ($cart_data) {
             if($cart_data['coupon_percentage']!=0)
            $discount = ($sub_total * ($cart_data['coupon_percentage']/ 100));
            else
            $discount = $cart_data['discount'];
            $coupon_id = $cart_data['coupon_id'];
            $coupon_code = $cart_data['coupon_code'];
            $coupon_percentage = $cart_data['coupon_percentage'];
        }
        if ($cart_data) {
            $delivery_charges = $cart_data['delivery_charges'];
            $area_id = $cart_data['area_id'];
            $area_name = $cart_data['area_name'];
        }
        if ($area_data) {
            $delivery_charges = $area_data['delivery_charges'];
            $area_id = $area_data['area_id'];
            $area_name = $area_data['area_name'];
        } else if ($sub_total < $this->config->item('minimum_order_amount') && $delivery_charges <= 0) {
            $delivery_charges = $this->config->item('delivery_charges');
        } else {
            $delivery_charges = 0;
        }
        $discounted_total = $sub_total - $discount;
        $gst = number_format((($discounted_total * $this->config->item('gst')) / 100), 2, '.', '');
        $pst = number_format((($discounted_total * $this->config->item('pst')) / 100), 2, '.', '');
        $hst = number_format((($discounted_total * $this->config->item('hst')) / 100), 2, '.', '');
        $total_cart_price = number_format(($discounted_total + $delivery_charges + $gst + $pst + $hst), 2, '.', '');
        $data = array(
            'cart_id' => $cart_data['cart_id'],
            'sub_total' => $sub_total,
            'location_id' => $this->config->item('location_id'),
            'location_name' => $this->config->item('location_name'),
            'gst_per' => $this->config->item('gst'),
            'pst_per' => $this->config->item('pst'),
            'hst_per' => $this->config->item('hst'),
            'discount' => $discount,
            'coupon_id' => $coupon_id,
            'coupon_code' => $coupon_code,
            'coupon_percentage' => $coupon_percentage,
            'delivery_charges' => $delivery_charges,
            'gst' => $gst,
            'pst' => $pst,
            'hst' => $hst,
            'area_id' => $area_id,
            'area_name' => $area_name,
            'total_cart_price' => $total_cart_price,
        );
        $this->cart->updateCart($data);
    }

    public function emptyCart() {
        $this->cart->emptyCart();
        $this->cart_items->emptyCartItems();
        $this->cart_items->emptyCartPackageItemsBySession();
        redirect($_SERVER['HTTP_REFERER']);
        exit;
    }

}
