<?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');
	}

	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"){
		    $album_id = '';
		    $flag = true;
			$album_chk_id = $this->input->post('album_chk_id', TRUE);
			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);
			
			$insert_data = array(
			    'merchandise_id' => $merchandise_id,
			    'album_id' => $album_id,
			    'size' => $size,
			    'user_id' => $userdata["id"],
			    'site_id' => $site_id,
			    'created_at' => date('Y-m-d H:i:s')
			);
			
			$this->CartModel->insert_row($insert_data);
			
			$this->session->set_flashdata('success', 'A 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://d1z6a3vjnfowyr.cloudfront.net/'.$site_row['logo'];
		$data['is_single_gallery'] = $site_row['is_single_gallery'];
		
		$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";
		}
	    
	    $id = $this->input->get('id',TRUE);
	    $isDelivery = $this->input->get('isDelivery', TRUE);
	    $total_price_usd = $this->input->get('total_price_usd', TRUE);
	    $total_price = $this->input->get('total_price', TRUE);
	    $site_id = $this->input->get('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' => 1,
	        '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"]."'");
	    $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"],
	   //         );
	   //         $this->CartModel->insert_detail_row($insert_cart_detail_data);
	            
	   //         $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->get("name", TRUE);
		  //  $phone   = $this->input->get("phone", TRUE);
		  //  $address = $this->input->get("address", TRUE);
		  //  $country = $this->input->get("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='.$id.'&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?';
 
		// Add fields to paypal form
		$this->paypal_lib->add_field('return', $returnURL);
		$this->paypal_lib->add_field('cancel_return', $cancelURL);
		$this->paypal_lib->add_field('notify_url', $notifyURL);
		$this->paypal_lib->add_field('custom', $userdata['id']);
		$this->paypal_lib->add_field('item_number', $max_order_id);
		$this->paypal_lib->add_field('amount', $total_price_usd);

		// Render paypal form
		$this->paypal_lib->paypal_auto_form();
	}
	
	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,
	        '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")
	            );
	            
	            $this->CartModel->insert_detail_row($insert_cart_detail_data);
	            
	            $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));
	}
}