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

class Order extends MY_Controller {

	/**
	 * user admin
	 *
	 * @package		User
	 *
     * @version		1.0 --
     * @since		Version 1.0 2017
	 */
	private $fed_auth;
	private $fed_rates; 
    private $fed_account; 
    public $_list_data = array();

	public function __construct() {

		global $config;
		parent::__construct();
		$this->fed_auth = g('db.admin.fedex_auth_url');
		$this->fed_rates = g('db.admin.fedex_rates_url');
        $this->fed_account = g('db.admin.fedex_account_no');
        $this->dt_params['dt_headings'] = "order_id,order_number,order_name,order_billing_email,order_amount,order_createdon,order_payment_status";
        $this->dt_params['searchable'] = array("order_id","order_number","order_billing_email","order_payment_status");
        $this->dt_params['action'] = array(
                                    	"hide_upload_button" => true,
										"hide_save_new" => true,
        								"hide_add_button" => true ,
                                        "hide" => false ,
                                        "show_delete" => false ,
                                        "show_edit" => true ,
                                        "order_field" => false ,
                                        "show_view" => false ,
                                        "extra" => array(
                                        	'<a title="View" href="'.$config['admin_base_url'].'order/detail/%d/" class="btn-xs btn btn-primary order_details_btn"><i class="icon-picture"></i></a>',
                                        	
                                		) ,
                                      );
        
        $this->_list_data['user_status'] = array( 
                                        STATUS_INACTIVE => "<span class=\"label label-default\">Inactive</span>" ,  
                                        STATUS_ACTIVE =>  "<span class=\"label label-primary\">Active</span>"  
                                    );
         $this->_list_data['order_dispatch_status'] = array(
            STATUS_INACTIVE => "<span class=\"label label-default\">No</span>" ,
            STATUS_ACTIVE =>  "<span class=\"label label-primary\">Yes</span>"
        );

		// $this->_list_data['order_state'] = $this->model_state->find_all_list_active(array(),"state_name");
		// $this->_list_data['order_billing_state'] = $this->model_state->find_all_list_active(array(),"state_name");
		// $this->_list_data['order_shipping_state'] = $this->model_state->find_all_list_active(array(),"state_name");

		// For use IN JS Files
		$config['js_config']['paginate'] = $this->dt_params['paginate'];
		
		$_POST = $this->input->post(NULL, false);
		
	}

	public function add($id='', $data=array())
	{
		$curl = curl_init();

        curl_setopt_array($curl, array(
          CURLOPT_URL => $this->fed_auth,
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'POST',
          CURLOPT_POSTFIELDS => 'grant_type=client_credentials&client_id=l728624bdf25334bcfb40207c484e412b3&client_secret=06c02c9a26d1486b9c7a2de9c385cf16',
          CURLOPT_HTTPHEADER => array(
            'Content-Type: application/x-www-form-urlencoded'),
        ));

        $response = curl_exec($curl);
        curl_close($curl);
        $data['fedtoken'] = json_decode($response,true)['access_token'];
		$data['states'] = $this->model_state->find_all();
		// Popluated LISTDATA in constructor
		$this->add_script(array( "jquery.validate.js" , "form-validation-script.js") , "js" );
		// debug($_POST,1);
		parent::add($id, $data);
// 		redirect(g('admin_base_url') . "order");
	}
	
	public function search(){
	    debug($_POST,1);
	}
	
	public function update_dispatch($order_id=''){
		$id=$_GET['id'];
		$dispatch_status=$_GET['st_type'];
		//debug($dispatch_status,1);
		if($dispatch_status==0){
		$updateorder['order_dispatch_status']=1;
		}else{
			$updateorder['order_dispatch_status']=0;
		}
		$this->model_order->update_by_pk($id, $updateorder);
		redirect(g('admin_base_url') . "order");
	}
	public function detail($order_id='')
	{   
		/** check rights before deletion **/
		$class_name = $this->router->class;
		$page_name = $class_name."_edit";
		//$this->admin_rights->check_admin_rights($page_name);
		
		//$this->add_script(array( "jquery.validate.js" , "form-validation-script.js") , "js" );

		$this->layout_data['template_config']['show_toolbar'] = false ;
		$this->register_plugins(array(						
									"jquery-ui",
									"bootstrap",
									"bootstrap-hover-dropdown",
									"jquery-slimscroll",
									"uniform",
									"boots",
									"font-awesome",
									"simple-line-icons" ,
									"select2",
									"bootbox",
									"bootstrap-toastr",
									"bootstrap-datetimepicker"
								));


		
		$data['order_detail'] = $this->model_order->get_order_detail($order_id);
		$recipt = $data['order_detail']['order_response'];
        $recipt = unserialize($recipt);
        $data['receipt_url'] = $recipt['receipt_url'];
		//$data['ashare_detail'] = $this->model_adshare->get_adshare_detail($data['order_detail']['order_adshare_id']);
        //debug($data[ 'ashare_detail' ]);
		//$data['country'] = $this->model_country->find_by_pk($data[ 'order_detail' ]['order_country']);
		
		if(!array_filled($data[ 'order_detail' ]))
			not_found("Invalid Order ID");

        // check is parent value ste (use when someone reserve adspace in adshare).
        /*if($data[ 'ashare_detail' ]['adshare_is_parent']!=null){
            $old_data = $data['ashare_detail'];
            //debug($old_data);
            $data['ashare_detail'] = $this->model_adshare->get_adshare_detail($data[ 'ashare_detail' ]['adshare_is_parent']);
            //debug($data['ashare_detail']);
            // set old data value to new data
            $data['ashare_detail']['adshare_is_parent'] = $old_data['adshare_is_parent'];
            $data['ashare_detail']['adshare_number'] = $old_data['adshare_number'];

            // Set adshare id for adshare info
            $adshare_id = $data[ 'ashare_detail' ]['adshare_is_parent'];
        }
        else{
            // Set adshare id for adshare info
            $adshare_id = $data['order_detail']['order_adshare_id'];
        }*/
        //debug($data['ashare_detail'],1);

		$total_quantity = 0;
		$total_amount = 0;
		$item_data = $this->model_order_item->get_order_items($order_id);
        //debug($item_data,1);

		foreach ($item_data as $key => $value) {

			$options = unserialize($value['order_item_option']);

			$amount = $value['order_item_subtotal'];
			//if(isset($options['subscription_tenure'])){
			//	$tenure = ($options['subscription_tenure'] == 2 ? '3' : '1');
			//	$amount = ($value['order_item_subtotal']*$tenure);
			//}
			$total_amount += $amount;

			$total_quantity += $value['order_item_qty'];
			//$total_amount += $value['order_item_subtotal'];
		}


        // JOIN
        /*$param['joins'][] = array(
            "table"=>"adshare_attachment" ,
            "joint"=>"adshare_attachment.adshare_attachment_adshare_id = adshare_id",
        );*/
        //$adshare = (array) $this->model_adshare->find_by_pk($adshare_id, true,$param);
		
		$data[ 'total_quantity' ] = $total_quantity;
		$data[ 'total_amount' ] = $total_amount;
		$data[ 'order_items' ] = $item_data;
		//$data[ 'adshare_info' ] = $adshare;
		$data[ 'page_title_min' ] = "Detail";
		$data[ 'page_title' ] = "Order";
		$data[ 'class_name' ] = "order";
		$data[ 'model_name' ] = "model_order";
		$data[ 'model_obj' ] = $this->model_order;
		$data[ 'dt_params' ] = $this->dt_params ;
		$data[ 'id' ] = $id;
        // debug($data,1);

		//$this->load_view("invoice" , $data);
		// debug($data,1);
		$this->load_view("detail" , $data);
	}

	public function index()
	{
		// Popluated LISTDATA in constructor
		parent::index();
		
	}
	
public function get_view($id=0)
	{
		global $config;
		$result = array();
		$class_name = $this->router->class;
		$model_name = 'model_'.$class_name ;
		$model_obj = $this->$model_name ;
		$form_fields = $model_obj->get_fields();
		if($id)
		{
			$result['record'] = $this->$model_name->find_by_pk($id);
			$result['record'] = $this->$model_name->prepare_view_data($result['record']);
			if(!$result['record'] )
				$result['failure'] = "No Item Found";
				// Load relation fields data
			$relation_data = $this->$model_name->get_relation_data($id);
			if(array_filled($relation_data))
				$result['record']['relation_data'] = $relation_data;
		}
		else
		{
			$result['failure'] = "No Item Found";
		}

		return $result;

	}
	
public function stripe_capture_payment()
	{
		$order_id = $this->input->post('order_id');
		$order = $this->model_order->find_by_pk($order_id);
		// debug($order,1);
		require_once(APPPATH . 'libraries/stripe-sdk/init.php');
		// $stripe_charge_id = $order['order_response'];
		// $param001['where']['config_variable'] = 'stripe_secret_key';
		// $data001 = $this->model_config->find_one($param001);
		// debug($data001,1);
		$order_response = unserialize($order['order_response']);
		$amount = $order['order_amount'] * 100;
		// 	debug(unserialize($order['order_response']),1);
		// 	debug($order_response['id'],1);
		try{
			$stripe = new \Stripe\StripeClient(g('db.admin.stripe_secret_key'));
			$charge = $stripe->charges->capture($order_response['id'],['amount'=>$amount]);

			$response = str_replace('Stripe\Charge JSON:', '', $charge);
			// debug($response);
			$response = json_decode($response, true);
			
			if($response['captured'] == 1)
			{
				$update_param['order_payment_status'] = 3;
				$update_param['order_response_after_capture'] = serialize($response);
				$updated_id = $this->model_order->update_by_pk($order_id,$update_param);
				if($updated_id)
				{
					$order = $this->model_order->find_by_pk($order_id);
					$this->invoice_email($order);
				}
				$param['status'] = 1;
				$param['msg'] = "Success";    
			}
				else
				{
					$param['status'] = 0;
					$param['msg'] = "Failed";
				}
		}

		catch (Exception $e) {
			// echo "Something else happened, completely unrelated to Stripe";
			$body = $e->getJsonBody();
			$err = $body['error'];
			$title = $err;
			$msg_type = 'error';
			$param['error'] = $err['message'];
		}
		
		echo json_encode($param);
	}

public function dispatch_order()
	{
		$order_id = $this->input->post('order_id');
		$tracking_id = $this->input->post('tracking_id');
// 		$tracking_id1 = $this->input->post('tracking_id1');
		$order = $this->model_order->find_by_pk($order_id);
		if($order)
		{
			$update_param['order_tracking_number'] = $tracking_id;
// 			$update_param['order_tracking_number1'] = $tracking_id1;
			$update_param['order_payment_status'] = 4;
			$update_param['order_dispatch_status'] = 1;
			$update_param['order_payment_comments'] = 'Dispatched';
			$updated_id = $this->model_order->update_by_pk($order_id, $update_param);
			if($updated_id)
			{
				$order = $this->model_order->find_by_pk($order_id);
				$this->invoice_email($order);
			}
			$param['status'] = 1;
		}
		else
		{
			$param['status'] = 0;
		}
		echo json_encode($param);
	}

public function complete_order()
	{
		$order_id = $this->input->post('order_id');
		$order = $this->model_order->find_by_pk($order_id);
		if($order)
		{
			$update_param['order_payment_status'] = 1;
			$update_param['order_payment_comments'] = 'Completed';
			$updated_id = $this->model_order->update_by_pk($order_id, $update_param);
			
			if($updated_id)
			{
				$order = $this->model_order->find_by_pk($order_id);
				$this->invoice_email($order);
			}
			$param['status'] = 1;
		}
		else
		{
			$param['status'] = 0;
		}
		echo json_encode($param);
	}

public function stripe_refund_payment()
	{
		$order_id = $this->input->post('order_id');
		$amount = $this->input->post('refund_amount');
		$amount = $amount * 100; // $ to cents
		$order = $this->model_order->find_by_pk($order_id);
		// debug($order,1);
		require_once(APPPATH . 'libraries/stripe-sdk/init.php');
		// $stripe_charge_id = $order['order_response'];
		// $param001['where']['config_variable'] = 'stripe_secret_key';
		// $data001 = $this->model_config->find_one($param001);
		// debug($data001,1);
		$order_response = unserialize($order['order_response']);
		// 	debug(unserialize($order['order_response']),1);
		// 	debug($order_response['id'],1);
		// $stripe = new \Stripe\StripeClient($data001['config_value']);
		$stripe = new \Stripe\StripeClient(g('db.admin.stripe_secret_key'));

		try
		{
			$refund = $stripe->refunds->create([
				'charge' => $order_response['id'],
				'amount' => $amount]);

			// debug($refund);
			$response = str_replace('Stripe\Refund JSON:', '', $refund);
			// debug($response);
			$response = json_decode($response, true);
			// debug($response);
			
			if($response['status'] == 'succeeded')
			{
				$update_param['order_payment_status'] = 8;
				$update_param['order_payment_comments'] = 'Refunded';
				$update_param['order_refund_amount'] = $amount + $order['order_refund_amount'];
				$update_param['order_response_after_refund'] = serialize($response);
				// debug($update_param);
				$updated_id = $this->model_order->update_by_pk($order_id,$update_param);
				if($updated_id)
				{
					$order = $this->model_order->find_by_pk($order_id);
					$this->invoice_email($order);
				}

				$param['status'] = 1;
				$param['msg'] = "Success";    
			}
			else
			{
				$param['status'] = 0;
				$param['msg'] = "Failed";
			}
		}

		catch (Exception $e) {
			// echo "Something else happened, completely unrelated to Stripe";
			$body = $e->getJsonBody();
			$err = $body['error'];
			$title = $err;
			$msg_type = 'error';
			$param['error'] = $err['message'];
		}
		echo json_encode($param);
	}

public function stripe_cancel_payment()
	{
		$order_id = $this->input->post('order_id');
		$order = $this->model_order->find_by_pk($order_id);
		// debug($order,1);
		require_once(APPPATH . 'libraries/stripe-sdk/init.php');
		// $stripe_charge_id = $order['order_response'];
		// $param001['where']['config_variable'] = 'stripe_secret_key';
		// $data001 = $this->model_config->find_one($param001);
		// debug($data001,1);
		$order_response = unserialize($order['order_response']);
		// 	debug(unserialize($order['order_response']),1);
		// 	debug($order_response['id'],1);
		// $stripe = new \Stripe\StripeClient($data001['config_value']);
		$stripe = new \Stripe\StripeClient(g('db.admin.stripe_secret_key'));

		$response = $stripe->refunds->create([
			'charge' => $order_response['id']]);
		
		if($response['status'] == 'succeeded')
		{
			$update_param['order_payment_status'] = 6;
			$update_param['order_payment_comments'] = 'Cancelled';
			$update_param['order_response_after_refund'] = serialize($response);
			$updated_id = $this->model_order->update_by_pk($order_id,$update_param);
			if($updated_id)
			{
				$order = $this->model_order->find_by_pk($order_id);
				$this->invoice_email($order);
			}
			$param['status'] = 1;
			$param['msg'] = "Success";    
		}
		else
		{
			$param['status'] = 0;
			$param['msg'] = "Failed";
		}
		echo json_encode($param);
	}

public function invoice_email($getorderDetail)
        //public function invoice_email()
	{
		/*$order_id = 28;
		$getorderDetail = $this->model_order->find_by_pk($order_id);*/

		// $title = 'Order Confirmation - Invoice #' . $getorderDetail['order_id'];
		if($getorderDetail['order_payment_status'] == 1){
			$title = 'Order Completed - Invoice #'.$getorderDetail['order_id']; 

			} 
			elseif($getorderDetail['order_payment_status'] == 2){
			$title = 'Order Created - Invoice #'.$getorderDetail['order_id'];}

		    elseif($getorderDetail['order_payment_status'] == 3){ 
			$title = 'Order Payment Approved - Invoice #'.$getorderDetail['order_id'];}

			elseif($getorderDetail['order_payment_status'] == 4){ 
			$title = 'Order Dispatched - Invoice #'.$getorderDetail['order_id'].' - Tracking #'.$getorderDetail['order_tracking_number'];}

			elseif($getorderDetail['order_payment_status'] == 5){ 
			$title = 'Order Hold - Invoice #'.$getorderDetail['order_id'];}

    		elseif($getorderDetail['order_payment_status'] == 6){
    			$title = 'Order Cancelled - Invoice #'.$getorderDetail['order_id'];}
    
    		elseif($getorderDetail['order_payment_status'] == 7){
    			$title = 'Order Declined - Invoice #'.$getorderDetail['order_id'];}
    
    		elseif($getorderDetail['order_payment_status'] == 8){
    			$title = 'Order Payment Refunded - Invoice #'.$getorderDetail['order_id'];
    			}

		$param['joins'][] = array(
			"table" => "product",
			"joint" => "product.product_id = order_item.order_item_product_id"
		);

		$param['where']['order_item_order_id'] = $getorderDetail['order_id'];
		$data['cart'] = $this->model_order_item->find_all($param);
		$data['order_detail'] = $getorderDetail;
		$data['userdata'] = $this->user_info;

		$template = $this->load->view("_layout/email_template/invoice", $data, true);
		//$template = $this->load->view("_layout/email_template/invoice",$data,false);

		$to = $data['order_detail']['order_billing_email'];
		//  debug($to); 
		//  debug(g("db.admin.email")); 
		//  debug($title); 
		//  debug($template,1);
		$this->create_invoice_pdf($data);
		$this->model_email->invoice_email_temp($to, $template, $title);
		$to = g("db.admin.email");
        $this->model_email->invoice_email_temp($to, $template, $title);
	}

public function create_invoice_pdf($data)
{
    require_once(APPPATH."libraries/tcpdf/tcpdf.php");
    
	$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
	$pdf->SetCreator(PDF_CREATOR);
	$pdf->SetAuthor('CrisptechLLC');
	$pdf->SetTitle('Order Details');
	$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
	$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
    $pdf->setPrintHeader(false);
	$pdf->AddPage();
	$pdf_template = $this->load->view("_layout/invoice_pdf_template", $data, true);
	$pdf->writeHTML($pdf_template, true, false, true, false, '');
// 	$pdf->Output(FCPATH . 'invoices/'.md5('Invoice-'.$getorderDetail['order_id']).'.pdf', 'I'); //Opens PDF in browser
	$pdf->Output(FCPATH . 'invoices/'.md5('Invoice-'.$data['order_detail']['order_id']).'.pdf', 'F'); //Creates PDF
}

public function send_email()
{
    $order_id = $this->input->post('order_id');
    $order = $this->model_order->find_by_pk($order_id);
    if($order)
    {
        $this->invoice_email($order);
        $param['txt'] = 'Email has been sent to customer billing address!';
        $param['status'] = 1;
    }
    else
    {
        $param['txt'] = 'Something went wrong!';
        $param['status'] = 0;
    }
    
    echo json_encode($param);
    
}

public function generate_pdf()
{
    $order_id = $this->input->post('order_id');
    $order = $this->model_order->find_by_pk($order_id);
    if($order)
    {
        $param['joins'][] = array(
			"table" => "product",
			"joint" => "product.product_id = order_item.order_item_product_id"
		);

		$param['where']['order_item_order_id'] = $order['order_id'];
		$data['cart'] = $this->model_order_item->find_all($param);
		$data['order_detail'] = $order;
		$data['userdata'] = $this->user_info;
		$this->create_invoice_pdf($data);
		$return_param['status'] = 1;
		echo json_encode($return_param);
    }
    
}

public function refresh_cart()
	{
		$cart_data = $this->cart->contents();
		$cart_count = count($this->cart->contents());
		$cart_total = $this->cart->total();
		$total_weight = 0;
		$cart_body = '';
		// debug($cart_data,1);
		foreach($cart_data as $key=>$value):
		$total_product_weight = $value['options']['product_weight']*$value['qty'];
		$total_weight = $total_weight + $total_product_weight;
		$cart_body .= "
			<tr>
				<td>{$value['options']['product_sku']}</td>
				<td>{$value['name']}</td>
				<td>$ {$value['price']}</td>
				<td>{$value['qty']}</td>
				<td>$ {$value['subtotal']}</td>
			</tr";
		endforeach;
		
		$cart_info = "
		<li><strong style='color:#333'>Total Products</strong> : <span id='cart_total_items'>{$cart_count}</span> </li>
		<li><strong style='color:#333'>Total Weight</strong> : <span id='cart_total_weight'>{$total_weight} oz</span></li>
		<li><strong style='color:#333'>Total Price</strong> : <span id='cart_total'>$ {$cart_total}</span>  </li>";

		$param['cart_body'] =$cart_body;
		$param['cart_info'] =$cart_info;
		echo json_encode($param);
	}

public function clear_cart()
	{
		$clear_cart = $this->input->post('clear_cart');
		$cart_contents = count($this->cart->contents());
		if($clear_cart && $cart_contents > 0)
		{
			$this->cart->destroy();
			$param['status'] = 1;
			$param['msg'] = 'Cart has been cleared!';
		}
		else
		{
			$param['status'] = 0;
			$param['msg'] = 'Cart is already empty!';
		}
		echo json_encode($param);
	}

// public function create_admin_order()
// 	{
// 		if($this->validate('model_admin_order'))
// 		{
// 			$admin_order_data = $this->input->post('admin_order');
// 			$admin_order_data['admin_order_status'] = 1; // 1 - Checkout needed // 0 - Checkout already done
// 			$order_state = $this->model_state->find_by_pk($admin_order_data['admin_order_state']);
// 			$admin_order_data['admin_order_state'] = $order_state['state_name'];

// 			$shipping_state = $this->model_state->find_by_pk($admin_order_data['admin_order_shipping_state']);
// 			$admin_order_data['admin_order_shipping_state'] = $order_state['state_name'];
			
// 			$billing_state = $this->model_state->find_by_pk($admin_order_data['admin_order_billing_state']);
// 			$admin_order_data['admin_order_billing_state'] = $order_state['state_name'];
// 			$admin_order_data['admin_order_total'] = $this->cart->total();
// 			$admin_order_data['admin_order_amount'] = $this->cart->total() + $admin_order_data['admin_order_tax'] + $admin_order_data['admin_order_shipment_price'];
			
// 			$inserted_id = $this->model_admin_order->insert_record($admin_order_data);

			
			
// 			if ($inserted_id > 0) 
// 			{
// 				$cart_data = $this->cart->contents();
// 				//debug($cart_data,1);
// 				/** Add items **/

// 				foreach ($cart_data as $key => $value)
// 					{
// 						//$oitem['order_currency_type'] = $this->currency;
// 						$oitem['admin_order_item_status'] = 1;
// 						$oitem['admin_order_item_order_id'] = $inserted_id;
// 						$oitem['admin_order_item_product_id'] = $value['id'];
// 						$oitem['admin_order_item_price'] = $value['price'];
// 						$oitem['admin_order_item_subtotal'] = $value['subtotal'];
// 						$oitem['admin_order_item_qty'] = $value['qty'];
// 						$oitem['admin_order_item_name'] = $value['name'];
// 						$oitem['admin_order_item_user_id'] = $this->userid;
// 						$oitem['admin_order_item_option'] = serialize($value['options']);
// 						$this->model_admin_order_item->insert_record($oitem);
// 						// debug($oitem);
// 					}

// 					$admin_order_param['admin_order_token'] = md5($inserted_id.time());
// 					$admin_order_param['admin_order_link'] = base_url().'checkout/step1/'.$admin_order_param['admin_order_token'];
// 					$this->model_admin_order->update_by_pk($inserted_id, $admin_order_param);
// 					$this->cart->destroy();
// 					$param['status'] = 1;
// 					$param['txt'] = 'Checkout Link Created Successfully';
// 					$param['url'] = $url;
// 					$param['oid'] = $inserted_id;
// 					$param['order_amount'] = $order_data['order_amount'];
// 					// debug($url,1);
// 					echo json_encode($param);
// 			}
// 			else 
// 			{
// 				$param['status'] = 0;
// 				$param['txt'] = 'Failed to create Link. Please try later.';
// 				echo json_encode($param);
// 			}
		
// 				// debug($admin_order_data,1);
// 		}
	
// 	else 
// 	{
// 		$param['status'] = 0;
// 		$param['txt'] = validation_errors();
// 		//$param['txt'] = 'Please complete all required fields';
// 		echo json_encode($param);
// 	}

// }

public function update_order_item_quantity()
	{
		// debug($_POST,1);
		$order_id = $this->input->post('order_id');
		$new_qty = $this->input->post('product_qty');
		$order_item_id = $this->input->post('order_item_id');
		$order_item_quantity_original = $this->input->post('order_item_quantity_original');

		if($order_item_quantity_original >= $new_qty)
		{
		$order = $this->model_order->find_by_pk($order_id);
		$order_item = $this->model_order_item->find_by_pk($order_item_id);

		$billing_state = $order['order_billing_state'];
		$billing_state = $this->db->query("SELECT * FROM `fb_state` WHERE `state_name`= '".$billing_state."' 
											AND `state_status` = 1")->result_array();

		$order_item_update_param['order_item_qty'] = $new_qty;
		$order_item_update_param['order_item_subtotal'] = round($new_qty * $order_item['order_item_price'],2);
		$dataForFront['order_item'] = $order_item_update_param;
		// debug($order_item_update_param);
		$isOrderItemUpdated = $this->model_order_item->update_by_pk($order_item_id, $order_item_update_param);

		$order_items_total = $this->get_order_items_total($order_id);

		$order_update_param['order_total'] = round($order_items_total['total_price'],2);
		$taxed_amount = $billing_state[0]['state_tax'] * $order_update_param['order_total'] / 100;
		$order_update_param['order_tax'] = round($taxed_amount,2);
		
		$shipping_methods = $this->get_fed_rates($order['order_billing_zip'],$order_items_total['total_weight']);
		// debug($shipping_methods,1);
		$order_update_param['order_shipment_price'] = 0;
		foreach($shipping_methods as $key=>$value)
		{
			if($order['order_shipping'] == $value['serviceName'])
			{
				$order_update_param['order_shipment_price'] = $value['totalNetFedExCharge'];
			}
		}
		$order_update_param['order_amount'] = round($order_update_param['order_shipment_price'] + $order_update_param['order_tax'] + 
												$order_update_param['order_total'],2);
		
		$dataForFront['order'] = $order_update_param;
		// debug($order_update_param);
		$isOrderUpdated = $this->model_order->update_by_pk($order_id, $order_update_param);
		if($isOrderItemUpdated > 0 && $isOrderUpdated > 0)
		{
			$returnParam['status'] = 1;
			$returnParam['txt'] = 'Quantity has been updated';
			$returnParam['data'] = $dataForFront;
		}
		else
		{
			$returnParam['status'] = 0;
			$returnParam['txt'] = 'Something went wrong';
		}
	}
	else{
		$returnParam['status'] = 0;
		$returnParam['txt'] = 'New quantity can not be greater than the originally ordered quantity..';
	}
		echo json_encode($returnParam);
	}

public function get_order_items_total($order_id)
	{
		$orderItemsData = array();
		$order_items_total_weight = 0;
		$order_items_total_price = 0;
		$orderItemParam['where']['order_item_order_id'] = $order_id;
		$orderItems = $this->model_order_item->find_all($orderItemParam);
		// debug($orderItems);
		foreach($orderItems as $key=>$value)
		{
			$order_items_total_price += $value['order_item_subtotal'];
			$unserializeData = unserialize($value['order_item_option']);
			$order_item_total_product_weight = $unserializeData['product_weight'] * $value['order_item_qty'];
			$order_items_total_weight += $order_item_total_product_weight;
		}
		$orderItemsData['total_weight'] = $order_items_total_weight;
		$orderItemsData['total_price'] = $order_items_total_price;

		return $orderItemsData;
	}

	public function get_fed_rates($zip, $final_weight)
	{
		$curl = curl_init();

        curl_setopt_array($curl, array(
          CURLOPT_URL => $this->fed_auth,
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'POST',
          CURLOPT_POSTFIELDS => 'grant_type=client_credentials&client_id=l728624bdf25334bcfb40207c484e412b3&client_secret=06c02c9a26d1486b9c7a2de9c385cf16',
          CURLOPT_HTTPHEADER => array(
            'Content-Type: application/x-www-form-urlencoded'),
        ));

        $response = curl_exec($curl);
        curl_close($curl);
        $token = json_decode($response,true)['access_token'];

        $admin_order_id = $this->input->post('admin_order_id');
        // debug($token);
        // debug($zip,1);
        // $final_weight = 0;
        // foreach($this->cart->contents() as $key => $val)
        // {
        //     $final_weight = $final_weight + $val['options']['product_weight'];
        // }
        // debug($final_weight,1);
        $curl = curl_init();

        curl_setopt_array($curl, array(
          CURLOPT_URL => $this->fed_rates,
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'POST',
          CURLOPT_POSTFIELDS =>'{
          "accountNumber": {
            "value": "'.$this->fed_account.'"
          },
          "requestedShipment": {
            "shipper": {
              "address": {
                "postalCode": 94538,
                "countryCode": "US"
              }
            },
            "recipient": {
              "address": {
                "postalCode": "'.$zip.'",
                "countryCode": "US"
              }
            },
            "pickupType": "DROPOFF_AT_FEDEX_LOCATION",
            "rateRequestType": [
              "ACCOUNT",
              "LIST"
            ],
            "requestedPackageLineItems": [
              {
                "weight": {
                  "units": "LB",
                  "value": "'.$final_weight.'"
                }
              }
            ]
          }
        }',
          CURLOPT_HTTPHEADER => array(
            'x-customer-transaction-id: 624deea6-b709-470c-8c39-4b5511281492',
            'content-type: application/json',
            'authorization: Bearer '.$token.''
          ),
        ));
        
        $response = curl_exec($curl);
        // debug($response,1);
        curl_close($curl);
        
        $res_fin = json_decode($response,true);
        foreach ($res_fin['output']['rateReplyDetails'] as $key => $val):
            $service[$key]['serviceName'] = $val['serviceName'];
            $service[$key]['totalNetFedExCharge'] = $val['ratedShipmentDetails'][0]['totalNetFedExCharge'];
        endforeach;

		// debug($service,1);
		return $service;
	}

	public function update_order_amount()
	{
		$order_id = $this->input->post('order_id');
		$updateParam['order_amount'] = $this->input->post('amount');
		$isUpdated = $this->model_order->update_by_pk($order_id,$updateParam);
		if($isUpdated)
		{
			$param['status'] = 1;
		}
		else
		{
			$param['status'] = 0;
		}
		echo json_encode($param);
	}

	public function reset_order_amount()
	{
		$order_id = $this->input->post('order_id');
		$order = $this->model_order->find_by_pk($order_id);
		if($order['order_amount_old'] != $order['order_amount'])
		{
			$updateParam['order_amount'] = $order['order_amount_old'];
			$isUpdated = $this->model_order->update_by_pk($order_id,$updateParam);
			if($isUpdated)
			{
				$param['status'] = 1;
				$param['txt'] = 'Amount has been reset to its initial value!';
			}
			else
			{
				$param['status'] = 0;
				$param['txt'] = 'Something Went wrong!';
			}
		}
		else
		{
			$param['status'] = 0;
			$param['txt'] = 'Amount has already set to its inital value!';
		}
		
		echo json_encode($param);
	}
}




/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
