<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class CartController extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model('NotificationModel');
		$this->load->model('GuestModel');
		$this->load->model('CartModel');
		$this->load->model('OrderModel');
		$this->load->model('AuthModel');
		$this->load->model('SiteModel');
		$this->load->model('SouvenirModel');
		$this->load->library('Paypal_lib');

        $this->load->model('SiteDataModel');
       
	}
	public function get_discount()
	{
		$userdata = $this->session->userdata('makeabl2020');
		if (empty($userdata) || !isset($userdata["id"]))
			redirect('login', 'refresh');
		
		$site_id = $userdata['site_id'];

		$discountcode = $this->input->post('discountcode');

        $discount_info_qr = $this->CartModel->get_discount_qr($discountcode, $site_id);
        if(!empty($discount_info_qr))
        {
            $discount_info = $discount_info_qr;
        }
        else
        {
            $discount_info = $this->CartModel->get_discount($discountcode, $site_id);           
        }
		
		echo json_encode($discount_info);
	}

	public function index()
	{
		$userdata = $this->session->userdata('makeabl2020');
		if (empty($userdata) || !isset($userdata["id"]))
			redirect('login', 'refresh');
		
		$add_cart_btn = $this->input->post('add_cart_btn', TRUE);
		if($add_cart_btn == "ok"){
            // print_r($_POST);
            // die;
		    $album_id = '';
		    $flag = true;


            if(!empty($_POST['is_combo']))
            {
                foreach($_POST['combo'] as $combo)
                {
                    $album_id .= $combo['album_id'].',';
                }

                $album_id = rtrim($album_id, ",");
            }
            else
            {
               $album_chk_id = $this->input->post('album_chk_id', TRUE);
               $album_id = $album_chk_id;
                // foreach ($album_chk_id as $key => $val) {
                //     if($flag == true){
                //         $album_id = $val; 
                //         $flag = false;
                //     }else{
                //         $album_id = $album_id .", ". $val; 
                //     }
                // }
            }


		
			
			$merchandise_id = $this->input->post('merchandise_id', TRUE);
		    $site_id = $this->input->post('site_id', TRUE);
		    $size = $this->input->post('size_id', TRUE);
            $qty = !empty($this->input->post('qty')) ? $this->input->post('qty') : 1;
			
			$insert_data = array(
			    'merchandise_id' => $merchandise_id,
			    'album_id' => $album_id,
			    'size' => $size,
			    'user_id' => $userdata["id"],
			    'site_id' => $site_id,
                'amount' => $qty,
			    'created_at' => date('Y-m-d H:i:s')
			);
			
			$cart_id = $this->CartModel->insert_row($insert_data);


            if(!empty($_POST['is_combo']))
            {
                foreach($_POST['combo'] as $combo)
                {
                    $array_combo = array(
                        'cart_id' => $cart_id,
                        'album_id' => $combo['album_id'],
                        'merchandise_id' => $combo['merchandise_id'],
                        'sel_layout' => $combo['sel_layout'],
                        'qty' => $combo['qty']
                    );

                    $this->db->insert('cart_combo_tb', $array_combo);
                }
            }
			 

            $getsouvenir = $this->db->where('id', $merchandise_id);
            $getsouvenir = $this->db->get('souvenir_tb')->row();


            $this->SiteDataModel->insert_row('', 'Cart', $getsouvenir->title);

			$this->session->set_flashdata('success', 'Merchandise added to cart.');
			redirect(base_url('cart'));
			exit();
		}
		
		$del_btn = $this->input->post("del_btn", TRUE);
		if($del_btn == "ok"){
		    $edit_id = $this->input->post("edit_id", TRUE);
		    
		    $this->CartModel->delete_row($edit_id);
		    
		    $this->session->set_flashdata('success', 'A merchandise removed from cart!');
			redirect(base_url('cart'));
			exit();
		}
		
		$site_row = $this->SiteModel->get_row($userdata['site_id']);
		
		$data['title'] = 'Cart | MAKEABL';
		$data['userdata'] = $userdata;
		$data['guest_detail'] = $this->GuestModel->get_row($userdata['id']);
		$data['country_data'] = $this->CartModel->get_country_row($userdata['site_id']);
		$data['cart_list'] = $this->CartModel->get_rows(" where cart_tb.id > 0 and cart_tb.isCheckout = 0 and cart_tb.user_id = '".$userdata["id"]."' and cart_tb.is_staff = 0 order by cart_tb.id desc");
		$data['notification_list'] = $this->NotificationModel->get_rows(" where id > 0 and isDeleted = 0 and guest_id = '".$userdata["id"]."' order by id desc");
		$data['new_notification_count'] = $this->NotificationModel->get_count(" where id > 0 and isDeleted = 0 and guest_id = '".$userdata["id"]."' and isShow = 0");
		$data['site_logo'] = 'http://d38x82mkkml5o1.cloudfront.net/'.$site_row['logo'];
		$data['is_single_gallery'] = $site_row['is_single_gallery'];
		
        $data['header_title'] = 'Cart';

         // $this->SiteDataModel->insert_row();

		$this->load->view('template/header', $data);
		$this->load->view('template/sidebar', $data);		
		$this->load->view('cart', $data);		
		$this->load->view('template/footer', $data);		
	}
	
	public function purchase()
    {
        $userdata = $this->session->userdata('makeabl2020');
        if(empty($userdata) || !isset($userdata["id"]))
        {
            redirect('login', 'refresh');
        }

        $get_max_order_id = $this->OrderModel->get_max_row();

        if(count($get_max_order_id) > 0)
        {
            if(date('Ym') . "00001" > $get_max_order_id['max_orderID'])
            {
                $get_max_order_id['max_orderID'] = date('Ym') . "00001";
            }
            else
            {
                $get_max_order_id['max_orderID'] = $get_max_order_id['max_orderID'] + 1;
            }
        }
        else
        {
            $get_max_order_id['max_orderID'] = date('Ym') . "00001";
        }

        $ids             = $this->input->post('id', TRUE);
        $isDelivery      = $this->input->post('isDelivery', TRUE);
        $total_price_usd = $this->input->post('price', TRUE);
        $total_price     = $this->input->post('total_price', TRUE);
        $site_id         = $this->input->post('site_id', TRUE);
        $currency        = $this->get_currency_rows($userdata['site_id']);
        $currency        = strtolower($currency['iso_code']);
        $guest_qr_token  = $userdata['qr_token'];

        $discountcode = !empty($_POST['discount_code_qr']) ? $_POST['discount_code_qr'] : '';
        $discount_code_qr_id = !empty($_POST['discount_code_qr_id']) ? $_POST['discount_code_qr_id'] : '';

        $insert_order_data = array(
            'orderID' => $get_max_order_id['max_orderID'],
            'isDelivery' => $isDelivery,
            'total_price' => $total_price,
            'total_price_usd' => $total_price_usd,
            'currency' => $currency,
            'user_id' => $userdata["id"],
            'site_id' => $site_id,
            'is_paid' => 1,
            'is_front' => 1,
            'pay_method' => 'credit card',
            'created_at' => date("Y-m-d H:i:s"),
            'discountcode' => $discountcode,
            'discount_code_qr_id' => $discount_code_qr_id,
            'created_date' => time(),
        );
        $this->OrderModel->insert_row($insert_order_data);

        $max_order_id = $this->OrderModel->get_max_id_row();

        if(!empty($discount_code_qr_id))
        {
            $updateQuery = $this->db->query("UPDATE `discount_codes_qr_tb` SET `is_used` = '1' WHERE `discount_codes_qr_tb`.`id` = ".$discount_code_qr_id." ");
        }


        $cart_list = $this->CartModel->get_rows(" where cart_tb.id > 0 and cart_tb.isCheckout = 0 and cart_tb.user_id = '" . $userdata["id"] . "'");
        $cartid    = '';
        foreach($cart_list as $key => $val)
        {
            if($key != 0)
            {
                $cartid .= ",";
            }
            $cartid .= strval($val["id"]);
        }

        if(count($cart_list) > 0)
        {
            foreach($cart_list as $key => $val)
            {
                $insert_cart_detail_data = array(
                    'order_id' => $max_order_id,
                    'merchandise_id' => $val["merchandise_id"],
                    'size' => $val["title"],
                    'price' => $val["price"],
                    'quantity' => $val["amount"],
                    'created_at' => date("Y-m-d H:i:s"),
                    'album_id' => $val["album_id"],
                );

                $order_history_id =  $this->CartModel->insert_detail_row($insert_cart_detail_data);


                $getCartCombo = $this->db->where('cart_id', $val['id']);
                $getCartCombo = $this->db->get('cart_combo_tb')->result();

                foreach($getCartCombo as $valueC)
                {
                    $getSizeCombo = $this->db->where('souvenir_id',$valueC->merchandise_id);
                    $getSizeCombo = $this->db->get('souvenir_size_tb')->row();

                    $arrayOrderHistory = array(
                        'order_history_id' => $order_history_id,
                        'merchandise_id' => $valueC->merchandise_id,
                        'album_id' => $valueC->album_id,
                        'size' => !empty($getSizeCombo->title) ? $getSizeCombo->title : '',
                    );

                    $this->db->insert('order_history_combo_tb', $arrayOrderHistory);
                }


                $update_cart_detail_data = array(
                    'isCheckout' => 1,
                );
                $this->CartModel->update_row($update_cart_detail_data, array('id' => $val["id"]));
                $sold_merchandise_info = $this->SouvenirModel->get_row($val["merchandise_id"]);
                if($sold_merchandise_info)
                {
                    $update_soldCount_data = array(
                        'soldCount' => $sold_merchandise_info['soldCount'] + 1,
                    );
                    $this->SouvenirModel->update_row($update_soldCount_data, array('id' => $val["merchandise_id"]));
                }
            }
        }

        if($isDelivery == 1)
        {
            $name    = $this->input->post("name", TRUE);
            $phone   = $this->input->post("phone", TRUE);
            $address = $this->input->post("address", TRUE);
            $country = $this->input->post("country", TRUE);

            $insert_delivery_data = array(
                'order_id' => $max_order_id,
                'name' => $name,
                'email' => $userdata["email"],
                'phone' => $phone,
                'address' => $address,
                'country_id' => $country,
                'created_at' => date("Y-m-d H:i:s"),
            );
            $this->CartModel->insert_delivery_row($insert_delivery_data);
        }

        // Set variables for paypal form
        $name    = '';
        $phone   = '';
        $address = '';
        //        if($isDelivery == 1)
        //        {
        //            $name    = $this->input->get("name", TRUE);
        //            $phone   = $this->input->get("phone", TRUE);
        //            $address = $this->input->get("address", TRUE);
        //        }
        //        $returnURL = base_url() . 'orderpaypal/success?site_id=' . $site_id . '&id=' . $ids . '&cart_ids=' . $cartid;
        // 		$cancelURL = base_url().'orderpaypal/cancel?orderID='.$get_max_order_id['max_orderID'].'&isDelivery='.$isDelivery.'&total_price='.$total_price.'&total_price_usd='
        // 		.$total_price_usd.'&currency='.$currency.'&user_id='.$userdata["id"].'&site_id='.$site_id.'$is_paid=1&created_at='.date("Y-m-d H:i:s");
        //        $notifyURL = base_url() . 'orderpaypal/ipn?orderID=' . $get_max_order_id['max_orderID'] . '&isDelivery=' . $isDelivery . '&total_price=' . $total_price . '&total_price_usd=' . $total_price_usd . '&currency=' . $currency . '&user_id=' . $userdata["id"] . '&site_id=' . $site_id . '&is_paid=1&created_at=' . date("Y-m-d H:i:s") . '&cart_ids=' . $cartid . '&name=' . $name . '&phone=' . $phone . '&address=' . $address;
        //        $cancelURL = base_url() . 'orderpaypal/cancel?';


        require_once('application/libraries/stripe-php/init.php');
        \Stripe\Stripe::setApiKey($this->config->item('stripe_secret'));

        $stripeInfo = \Stripe\Charge::create(
            [
                "amount" => $total_price * 100,
                "currency" => $currency,
                "source" => $this->input->post('stripeToken'),
                "description" => 'GL Clix Photo',
            ]
        );
        
        $this->session->set_flashdata('success', 'Payment is successful.');

        $data['guest_id']          = $userdata['id'];
        $data['order_id']          = $max_order_id;
        $data['charge_id']         = $stripeInfo["id"];
        $data['txn_id']            = $stripeInfo["balance_transaction"];
        $data['payment_gross']     = $total_price;
        $data['payment_gross_usd'] = $total_price_usd;
        $data['currency_code']     = $currency;
        
        
        if($stripeInfo['outcome']['seller_message'] == 'Payment complete.')
        {
            $data['payment_status'] = "Completed";
        }
        else
        {
            $data['payment_status'] = "failed";
        }

        $data['created_at'] = date('Y-m-d H:i:s');
        $this->CartModel->insertTransaction($data);
        
        try {
            $order_data = $this->OrderModel->get_for_order_row($get_max_order_id['max_orderID']);
            $order_list = $this->OrderModel->get_for_order_rows($order_data["row_id"]);
            $site = $this->SiteModel->get_row($order_data['site_id']);
            $country_data = $this->CartModel->get_country_row($order_data['site_id']);

            $this->load->library('email');
            $config['protocol']     = 'smtp';
            $config['smtp_host']    = 'glclix.co';
            $config['smtp_port']    = '587';
            $config['smtp_timeout'] = '60';
            $config['smtp_user']    = 'support@glclix.co';
            $config['smtp_pass']    = 'Glclix23!';
            $config['mailtype']     = 'html';
            $config['charset']      = 'utf-8';
            $config['newline']      = '\r\n';

            $this->email->initialize($config);

            $this->email->from('support@glclix.co', 'GL Clix Photo Team');
            $this->email->to($order_data["email"]);
            $this->email->subject("GL Clix Photo Purchase");

            $message = 'Dear Valued Customer,<br><br>';
            $message .= 'Thank you for completing your purchase. Below you will find a copy of your invoice and order #:<br/><br/>';
            $message .= '<table style="width: 50%; margin: 0;">';
            $message .='<thead>';
            $message .='        </thead>';
            $message .='        <tbody>';
            $message .='          <tr>';
            $message .='            <td style="width:30%;vertical-align:top">';
            $message .='             <p style="margin:0 0 10px 0;padding:0;font-size:14px;"><span style="display:block;font-weight:bold;font-size:13px">Site Name:</span> </p>';
            $message .='            </td>';
            $message .='            <td style="width:70%;vertical-align:top">';
            $message .='              <p style="margin:0 0 10px 0;padding:0;font-size:14px;">'.$site["title"].'</p>';
            $message .='            </td>';
            $message .='          </tr>';
            $message .='          <tr>';
            $message .='            <td style="width:30%;vertical-align:top">';
            $message .='              <p style="margin:0 0 10px 0;padding:0;font-size:14px;"><span style="display:block;font-weight:bold;font-size:13px">Invoice To:</span> </p>';
            $message .='            </td>';
            $message .='            <td style="width:70%;vertical-align:top">';
            $message .='              <p style="margin:0 0 10px 0;padding:0;font-size:14px;">'.$order_data["email"].'</p>';
            $message .='            </td>';
            $message .='          </tr>';
            $message .='          <tr>';
            $message .='            <td style="width:30%;vertical-align:top">';
            $message .='              <p style="margin:0 0 10px 0;padding:0;font-size:14px;"><span style="display:block;font-weight:bold;font-size:13px">Address:</span> </p>';
            $message .='            </td>';
            $message .='            <td style="width:70%;vertical-align:top">';
            $message .='              <p style="margin:0 0 10px 0;padding:0;font-size:14px;">'.$order_data['delivery_address'].'</p>';
            $message .='            </td>';
            $message .='          </tr>';
            $message .='          <tr>';
            $message .='            <td style="width:30%;vertical-align:top">';
            $message .='              <p style="margin:0 0 10px 0;padding:0;font-size:14px;"><span style="display:block;font-weight:bold;font-size:13px">Invoice Number:</span> </p>';
            $message .='            </td>';
            $message .='            <td style="width:70%;vertical-align:top">';
            $message .='              <p style="margin:0 0 10px 0;padding:0;font-size:14px;">'.$order_data["orderID"].'</p>';
            $message .='            </td>';
            $message .='          </tr>';
            $message .='          <tr>';
            $message .='            <td style="width:30%;vertical-align:top">';
            $message .='              <p style="margin:0 0 10px 0;padding:0;font-size:14px;"><span style="display:block;font-weight:bold;font-size:13px">Invoice Date:</span> </p>';
            $message .='            </td>';
            $message .='            <td style="width:70%;vertical-align:top">';
            $message .='              <p style="margin:0 0 10px 0;padding:0;font-size:14px;">'.date("d/m/Y", strtotime($order_data["orderDate"])).'</p>';
            $message .='            </td>';
            $message .='          </tr>';
            $message .='        </tbody> ';
            $message .='     </table>';
            $message .='     <table style="width: 50%; margin: 0;">';
            $message .='     <tr >';
            $message .='    <td valign="top" style="width: 10%; border-bottom:solid windowtext 1.0pt">';
            $message .='    <p class="MsoNormal" align="center" style="text-align:center"><b><span style="font-size:10.0pt">#</span></b></p>';
            $message .='    </td>';
            $message .='    <td valign="top" style="width: 40%; border-bottom:solid windowtext 1.0pt;">';
            $message .='    <p class="MsoNormal" align="center" style="text-align:center"><b><span style="font-size:10.0pt">Merchandise Name</span></b></p>';
            $message .='    </td>';
            $message .='    <td valign="top" style="width: 10%; border-bottom:solid windowtext 1.0pt;">';
            $message .='    <p class="MsoNormal" align="center" style="text-align:center"><b><span style="font-size:10.0pt">Price</span></b></p>';
            $message .='    </td>';
            $message .='    <td valign="top" style="width: 20%; border-bottom:solid windowtext 1.0pt;">';
            $message .='    <p class="MsoNormal" align="center" style="text-align:center"><b><span style="font-size:10.0pt">Qty</span></b></p>';
            $message .='    </td>';
            $message .='    <td valign="top" style="width: 20%; border-bottom:solid windowtext 1.0pt;">';
            $message .='    <p class="MsoNormal" align="center" style="text-align:center"><b><span style="font-size:10.0pt">Total</span></b></p>';
            $message .='    </td>';
            $message .='    </tr>';
            if(count($order_list) > 0){
                foreach($order_list as $key => $val)
                {
                    $message .='     <tr>';
                    $message .='    <td valign="top" style="width: 10%; border-bottom:solid windowtext 1.0pt;">';
                    $message .='    <p class="MsoNormal" align="center" style="text-align:center"><span style="font-size:10.0pt">'.($key + 1).'</span></p>';
                    $message .='    </td>';
                    $message .='    <td valign="top" style="width: 40%; border-bottom:solid windowtext 1.0pt;">';
                    $message .='    <p class="MsoNormal" align="center" style="text-align:center"><span style="font-size:10.0pt">'.$val["merchandise_desc"].'</span></p>';
                    $message .='    </td>';
                    $message .='    <td valign="top" style="width: 10%; border-bottom:solid windowtext 1.0pt;">';
                    $message .='    <p class="MsoNormal" align="center" style="text-align:center"><span style="font-size:10.0pt">'.$country_data["symbol"].number_format(($val["price"]*(100-$val["discount"])/100), 2).'</span></p>';
                    $message .='    </td>';
                    $message .='    <td valign="top" style="width: 20%; border-bottom:solid windowtext 1.0pt;">';
                    $message .='    <p class="MsoNormal" align="center" style="text-align:center"><span style="font-size:10.0pt">'.$val["quantity"].'</span></p>';
                    $message .='    </td>';
                    $message .='    <td valign="top" style="width: 20%; border-bottom:solid windowtext 1.0pt;">';
                    $message .='    <p class="MsoNormal" align="center" style="text-align:center"><span style="font-size:10.0pt">'.$country_data["symbol"].number_format(($val["price"]*(100-$val["discount"])/100 * $val["quantity"]), 2).'</span></p>';
                    $message .='    </td>';
                    $message .='    </tr>';
                }
            }
            $message .='    <tr >';
            $message .='    <td style="width: 10%;"></td>';
            $message .='    <td style="width: 40%;"></td>';
            $message .='    <td style="width: 10%;"></td>';
            $message .='    <td valign="top" style="width:20%;">';
            $message .='    <p class="MsoNormal" align="center" style="text-align:center"><b><span style="font-size:10.0pt">Subtotal:</span></b></p>';
            $message .='    </td>';
            $message .='    <td valign="top" style="width:20%;">';
            if($order_data["delivery"]=="0"){
                $message .='    <p class="MsoNormal" align="center" style="text-align:center"><b><span style="font-size:10.0pt">'.$country_data["symbol"].number_format($order_data["total_price"], 2).'</span></b></p>';
            }
            else{
                $message .='    <p class="MsoNormal" align="center" style="text-align:center"><b><span style="font-size:10.0pt">'.$country_data["symbol"].number_format($order_data["total_price"]-$country_data["tax"], 2).'</span></b></p>';
            }


            $message .='    </td>';
            $message .='    </tr>';
            $message .='    <tr >';
            $message .='    <td style="width: 10%;"></td>';
            $message .='    <td style="width: 40%;"></td>';
            $message .='    <td style="width: 10%;"></td>';
            $message .='    <td valign="top" style="width:20%;border-bottom:solid windowtext 1.0pt;">';
            $message .='    <p class="MsoNormal" align="center" style="text-align:center"><span style="font-size:10.0pt">Shipping:</span></p>';
            $message .='    </td>';
            $message .='    <td valign="top" style="width:20%;border-bottom:solid windowtext 1.0pt;">';
            if($order_data["delivery"]=="0"){
                $message .='<p class="MsoNormal" align="center" style="text-align:center"><span style="font-size:10.0pt">'.$country_data["symbol"]."0".'</span></p>';
            }
            else{
                $message .='<p class="MsoNormal" align="center" style="text-align:center"><span style="font-size:10.0pt">'.$country_data["symbol"].number_format($country_data["tax"], 2).'</span></p>';
            }
            $message .='    </td>';
            $message .='    </tr>';
            $message .='    <tr>';
            $message .='    <td style="width: 10%;"></td>';
            $message .='    <td style="width: 40%;"></td>';
            $message .='    <td style="width: 10%;"></td>';
            $message .='    <td valign="top" style="width:20%;">';
            $message .='    <p class="MsoNormal" align="center" style="text-align:center"><b><span style="font-size:10.0pt">Grand Total:</span></b></p>';
            $message .='    </td>';
            $message .='    <td valign="top" style="width:20%;">';
            $message .='    <p class="MsoNormal" align="center" style="text-align:center"><b><span style="font-size:10.0pt">'.$country_data["symbol"].number_format(($order_data["total_price"]), 2).'</span></b></p>';
            $message .='    </td>';
            $message .='    </tr>';
            $message .='        </tbody>';
            $message .='        <tfooter> ';
            $message .='        </tfooter>';
            $message .='      </table>';

            $message .= '</br></br>If you have any questions or concerns please send us an email at <a href="mailto:support@glclix.co" target="_blank">support@glclix.co</a>.<br/><br/>';
            $message .= 'Have a great day!<br/>';
            $message .= 'GL Clix Team<br/>';
            $message .= '<a href="https://glclix.co" target="_blank" >glclix.co</a><br/>';
            $this->email->message($message);
            // $this->email->send();
        } catch (Exception $e) {
            echo $e->getMessage();
        }

        $ids = explode(',', $ids);

        foreach($ids as $id)
        {
            $this->CartModel->delete_row($id);
        }

        $this->session->set_userdata('payg-gallery', $data);

        $this->SiteDataModel->insert_row('', 'Purchase', 'Checkout');

        redirect('/cart', 'refresh');
    }
	
	public function payfunc(){
	    $userdata = $this->session->userdata('makeabl2020');
		if (empty($userdata) || !isset($userdata["id"]))
			redirect('login', 'refresh');
		
	    $get_max_order_id = $this->OrderModel->get_max_row();
	    if(count($get_max_order_id) > 0){
			if(date('Ym')."00001" > $get_max_order_id['max_orderID']){
				$get_max_order_id['max_orderID'] = date('Ym')."00001";
			}else{
				$get_max_order_id['max_orderID'] = $get_max_order_id['max_orderID']+1;
			}
		}else{
			$get_max_order_id['max_orderID'] = date('Ym')."00001";
		}
	    
	    $isDelivery = $this->input->post('isDelivery', TRUE);
	    $total_price = $this->input->post('total_price', TRUE);
	    $total_price_usd = $this->input->get('total_price_usd', TRUE);
	    $site_id = $this->input->post('site_id', TRUE);
	    $currency = $this->CartModel->get_currency($site_id);
	    $insert_order_data = array(
	        'orderID' => $get_max_order_id['max_orderID'],
	        'isDelivery' => $isDelivery,
	        'total_price' => $total_price,
	        'total_price_usd' => $total_price_usd,
	        'currency'=> $currency,
	        'user_id' => $userdata["id"],
	        'site_id' => $site_id,
	        'is_paid' => 0,
            'is_front' => 1,
            'pay_method' => 'cash',
	        'created_at' => date("Y-m-d H:i:s")
	    );
	    
	    $this->OrderModel->insert_row($insert_order_data);
	    
	    $max_order_id = $this->OrderModel->get_max_id_row();
	    
	    $cart_list = $this->CartModel->get_rows(" where cart_tb.id > 0 and cart_tb.isCheckout = 0 and cart_tb.user_id = '".$userdata["id"]."'");
	    if(count($cart_list) > 0){
	        foreach($cart_list as $key => $val){
	            $insert_cart_detail_data = array(
	                'order_id' => $max_order_id,
	                'merchandise_id' => $val["merchandise_id"],
	                'album_id' => $val["album_id"],
	                'size' => $val["title"],
	                'price' => $val["price"],
	                'quantity' => $val["amount"],
	                'created_at' => date("Y-m-d H:i:s")
	            );
	            
	            $order_history_id = $this->CartModel->insert_detail_row($insert_cart_detail_data);

                $getCartCombo = $this->db->where('cart_id', $val['id']);
                $getCartCombo = $this->db->get('cart_combo_tb')->result();

                foreach($getCartCombo as $valueC)
                {
                    $getSizeCombo = $this->db->where('souvenir_id',$valueC->merchandise_id);
                    $getSizeCombo = $this->db->get('souvenir_size_tb')->row();

                    $arrayOrderHistory = array(
                        'order_history_id' => $order_history_id,
                        'merchandise_id' => $valueC->merchandise_id,
                        'album_id' => $valueC->album_id,
                        'size' => !empty($getSizeCombo->title) ? $getSizeCombo->title : '',
                    );

                    $this->db->insert('order_history_combo_tb', $arrayOrderHistory);
                }

	            
	            $update_cart_detail_data = array(
	                'isCheckout' => 1
	            );
	            
	            $this->CartModel->update_row($update_cart_detail_data, array('id' => $val["id"]));
	            
	            $sold_merchandise_info = $this->SouvenirModel->get_row($val["merchandise_id"]);
	            if($sold_merchandise_info){
	                
	                $update_soldCount_data = array(
	                    'soldCount' => $sold_merchandise_info['soldCount'] + 1
	                );
	                
	                $this->SouvenirModel->update_row($update_soldCount_data, array('id' => $val["merchandise_id"]));
	            }
	        }
	    }
	    
	    if($isDelivery == 1){
	        $name    = $this->input->post("name", TRUE);
		    $phone   = $this->input->post("phone", TRUE);
		    $address = $this->input->post("address", TRUE);
		    $country = $this->input->post("country", TRUE);
		    
		    $insert_delivery_data = array(
		        'order_id' => $max_order_id,
		        'name' => $name,
		        'email' => $userdata["email"],
		        'phone' => $phone,
		        'address' => $address,
		        'country_id' => $country,
		        'created_at' => date("Y-m-d H:i:s")
		    );
		    
		    $this->CartModel->insert_delivery_row($insert_delivery_data);
	    }
	    
	    echo json_encode(
			array(
				'status' => 200, 
				'msg' => '<div class="alert alert-success fade in alert-dismissible show" style="margin-top:18px;">
                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                <span aria-hidden="true" style="font-size:20px">×</span>
                            </button>
                            <strong>Success!</strong> Your order has been successfully!
                        </div>'
			)
		);
	}
	
	public function update_amount_func(){
	    $edit_id = $this->input->post('id', TRUE);
	    $amount = $this->input->post('amount', TRUE);
	    
	    $update_data = array(
	        'amount' => $amount
	    );
	    
	    $this->CartModel->update_row($update_data, array('id' => $edit_id));	    
		$amount = $this->CartModel->get_amount_row($edit_id);	   
	    echo(json_encode($amount));
	}
		function get_currency_rows($id)
    {
        $sql   = "SELECT iso_code, country_id FROM site_tb st
                INNER JOIN country_tb ct ON ct.id = st.country_id
                WHERE st.id = $id";
        $query = $this->db->query($sql);

        return $query->row_array();
    }
}