<?php

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

class Location extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('cart_model', 'cart');
        $this->load->model('cart_items_model', 'cart_items');
        $this->load->model('province_model', 'province');
    }

    public function set_user_location() {
        if (!empty($_POST)) {
            $this->form_validation->set_rules('location_id', 'Location', 'trim|required');
            if ($this->form_validation->run()) {
                $this->session->set_userdata('location_id', $this->input->post('location_id'));
                $msg = 'true';
            } else {
                $msg = strip_tags(form_error('location_id'));
            }
            echo json_encode($msg);
        }
    }

    public function changeLocation($location_id) {
        $this->session->set_userdata('location_id', $location_id);
        $this->updateCartByLocation($location_id);
        redirect($_GET['redirect']);
    }

    public function updateCartByLocation($location_id = '') {
        $province_data = $this->province->getProvinceById($location_id);
        $sub_total = $this->cart_items->getCartItemsTotal();
        $sub_total = $sub_total['total_item_price'];
        $cart_data = $this->cart->getCartDetail();
        if ($cart_data) {
            $discount = $cart_data['discount'];
            $coupon_id = $cart_data['coupon_id'];
            $coupon_code = $cart_data['coupon_code'];
            $coupon_percentage = $cart_data['coupon_percentage'];
            $discounted_total = $sub_total - $discount;
            $gst = number_format((($discounted_total * $province_data->gst) / 100), 2, '.', '');
            $pst = number_format((($discounted_total * $province_data->pst) / 100), 2, '.', '');
            $hst = number_format((($discounted_total * $province_data->hst) / 100), 2, '.', '');
            $total_cart_price = number_format(($discounted_total + $gst + $pst + $hst), 2, '.', '');
            $data = array(
                'cart_id' => $cart_data['cart_id'],
                'sub_total' => $sub_total,
                'location_id' => $province_data->location_id,
                'location_name' => $province_data->location_name,
                'gst_per' => $province_data->gst,
                'pst_per' => $province_data->pst,
                'hst_per' => $province_data->hst,
                'discount' => $discount,
                'coupon_id' => $coupon_id,
                'coupon_code' => $coupon_code,
                'coupon_percentage' => $coupon_percentage,
                'gst' => $gst,
                'pst' => $pst,
                'hst' => $hst,
                'total_cart_price' => $total_cart_price,
            );
            $this->cart->updateCart($data);
        }
    }

}