<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Order extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        // header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method');
        // header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');
        // // avoiding preflight requests
        $method = $_SERVER['REQUEST_METHOD'];
        if ($method == "OPTIONS") {
            die();
        }

        $this->load->helper('form');
        $this->load->library('upload');
    }
    
    public function test_cards(){
        $json_data = @file_get_contents('php://input');
       $client =  $this->encrypt3Des($json_data);
       
        
		$data = array(
		    'client'=>$client
		    );
        
        	$ch = curl_init('https://api.flutterwave.com/v3/charges?type=card');
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
				curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_HTTPHEADER, array(
					'Content-Type: application/json',
					'Authorization:Bearer FLWSECK-d5140d8492c64c311d670a400ebcfe17-X'
				));
				//execute the curl
				$result = curl_exec($ch);
				$resdata['info'] = $result;
				
				 return $this->output
                        ->set_content_type('application/json')
                        ->set_status_header(200)
                        ->set_output(json_encode(array(
                            'success' => true,
                            'message' => 'initiated',
                            
                            'momo_processor' => json_decode($result)
                        )));
				
				
                
        
    }
    
    public function encrypt3Des($data){
        

  $encData = openssl_encrypt($data, 'DES-EDE3', 'd5140d8492c6f4a2effc2d68', OPENSSL_RAW_DATA);
  
    return base64_encode($encData); 

 }

    public function place_order()
    {
        // get item(s) in the cart
        // create an order
        // use the order id to create each product_in_order

        $json_data = json_decode(@file_get_contents('php://input'), true);
        $order_number = rand(1236758, 9238997); // generate a random number btwn these two
        $check_first = $this->db->get_where('orders', array('order_number' => $order_number))->row();

        if ($check_first == null) {
            // check first if there is nothing with this generated random number
            $order_data = array(
                'amount' => $json_data['amount'],
                'user_id' =>$json_data['user_id'],
                'order_number' => $order_number,
                'shipping_details' => $json_data['shipping_details'],
                'payment_type' => $json_data['payment_type'],
                'payment_status' => 'pending',
                'network' => 'mobile',
                'phone' => $json_data['payment_details']['phone'],
                'time_added' => time(),
            );
        } else {
            // create a new order_number
            $order_number = rand(1236758, 9238997); // generate a random number btwn these two
            $check_first = $this->db->get_where('orders', array('order_number' => $order_number))->row();

            if ($check_first == null) {
                // check first if there is nothing with this generated random number
                $order_data = array(
                    'amount' => $json_data['amount'],
                    'user_id' =>$json_data['user_id'],
                    'order_number' => $order_number,
                    'shipping_details' => $json_data['shipping_details'],
                    'payment_type' => $json_data['payment_type'],
                    'payment_status' => 'pending',
                    'network' => $json_data['payment_details']['network'],
                    'phone' => $json_data['payment_details']['phone'],
                    'time_added' => time(),
                );
            }
        }
        if ($this->db->insert('orders', $order_data)) {
            // get the order inserted in the  DB
            $order_id = $this->db->insert_id();

            foreach ($json_data['products'] as $product) {
                $this->db->insert('product_in_order', array('product_id' => $product['product']['product_id'], 'order_id' => $order_id, 'quantity' => $product['product']['quantity']));
            }

            // initiate mobile money// or card

            // expect the json object to have the total amount,  products , and payment type
            // for mobile money  i expect the mobile money number
            // for cards ,  i expect the card number, the expiry date and cvv

            if ($json_data['payment_type'] == 'MOMO') {
                // check for the network
                // if MPESA initiate PESAMONI
                // if AIRTEL,MTN initiate Flutterwave

                // $pesamoni_uri = 'https://pesamoni.com/api/live/v1/transactions';
                $token = time() . $order_number;
                $mobile =$json_data['payment_details']['phone'];
                // $data = array(
                //     'amount' => $json_data['amount'],
                //     'apiusername' => '732308812496456', 
                //     'apipassword' => '5ec03f52e0d151811d43',
                //     'method' => 'acreceive',
                //     'reference'=>"$token",
                //     'mobile'=>"$mobile",
                //     'token' => "$token"
                // );
                
                //initialize curl
                
                //pesamoni
              
                // $ch = curl_init($pesamoni_uri);
				// curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
				// curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
				// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				// curl_setopt($ch, CURLOPT_HTTPHEADER, array(
				// 	'Content-Type: application/json'
				// ));
				// //execute the curl
				// $result = curl_exec($ch);
				// $resdata['info'] = $result;
				
				//flutterwave
                $tx_ref =time() . $order_number;
				$flutter_data = array(
				    'tx_ref'=>$tx_ref,
				    'amount'=>$json_data['amount'],
				    'phone_number'=>'07'. $mobile,
				    "email"=>"kimbowaandrew@gmail.com",
				    'currency'=>'UGX',
				    'network'=>'MTN'
				    );
				
				
					$ch = curl_init('https://api.flutterwave.com/v3/charges?type=mobile_money_uganda');
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
				curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($flutter_data));
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_HTTPHEADER, array(
					'Content-Type: application/json',
					'Authorization:Bearer FLWSECK-ad202c2a734a87d54b1a7ca72fa92c6d-X'
				));
				//execute the curl
				$result = curl_exec($ch);
			
                // store transaction details

                $txn_data = array(
                    "order_number" => $order_number,
                    "token" => $tx_ref,
                    "amount" => $json_data['amount'],
                    "transaction_type" => "MOMO",
                    "status" => "pending",
                    "date_added" => time()
                );

                if ($this->db->insert('transactions', $txn_data)) {

                    // // on success of the txn  using the token give value
                    // return $this->output
                    //     ->set_content_type('application/json')
                    //     ->set_status_header(200)
                    //     ->set_output(json_encode(array(
                    //         'success' => true,
                    //         'message' => 'initiated',
                    //         'token' => $token,
                    //         'momo_processor' => $resdata
                    //     )));
                    
                    	 return $this->output
                        ->set_content_type('application/json')
                        ->set_status_header(200)
                        ->set_output(
                           json_encode( array(
                          'success' => true,
                            'message' => 'initiated',
                            'token' => $tx_ref,
                            'momo_processor'=>json_decode($result)->meta->authorization
                            )
                            )
                           
                        );
				
               
                } else {
                    return $this->output
                        ->set_content_type('application/json')
                        ->set_status_header(200)
                        ->set_output(json_encode(array(
                            'success' => false,
                            'message' => 'txn info not saved',

                        )));
                }
            } else
              if ($json_data['payment_type'] == 'MPESA') {
                // check for the network
                // if MTN , MPESA initiate PESAMONI
                // if AIRTEL, initiate Flutterwave

                $pesamoni_uri = 'https://pesamoni.com/api/live/v1/transactions';
                $token = time() . $order_number;
                $mobile =$json_data['payment_details']['phone'];
                $data = array(
                    'amount' => $json_data['amount'],
                    'apiusername' => '732308812496456', 
                    'apipassword' => '5ec03f52e0d151811d43',
                    'method' => 'acreceiveke',
                    'reference'=>"$token",
                    'mobile'=>"$mobile",
                    'token' => "$token"
                );
                //initialize curl
                
               
                // $ch = curl_init('$pesamoni_uri');
                // curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                // curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
                // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                // curl_setopt($ch, CURLOPT_VERBOSE, true);
                // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
                // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                // curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                //     'Content-Type: application/json'
                // ));
                // //execute the curl
                // $result = curl_exec($ch);
                // $resdata['info'] = $result;
                
     
                
                
                	$ch = curl_init($pesamoni_uri);
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
				curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_HTTPHEADER, array(
					'Content-Type: application/json'
				));
				//execute the curl
				$result = curl_exec($ch);
				$resdata['info'] = $result;
                
                // store transaction details

                $txn_data = array(
                    "order_number" => $order_number,
                    "token" => $data['token'],
                    "amount" => $json_data['amount'],
                    "transaction_type" => "MOMO",
                    "status" => "pending",
                    "date_added" => time()
                );

                if ($this->db->insert('transactions', $txn_data)) {

                    // on success of the txn  using the token give value
                    return $this->output
                        ->set_content_type('application/json')
                        ->set_status_header(200)
                        ->set_output(json_encode(array(
                            'success' => true,
                            'message' => 'initiated',
                            'token' => $token,
                            'momo_processor' => $resdata
                        )));
                } else {
                    return $this->output
                        ->set_content_type('application/json')
                        ->set_status_header(200)
                        ->set_output(json_encode(array(
                            'success' => false,
                            'message' => 'txn info not saved',

                        )));
                }
            
              } 
          elseif ($json_data['payment_type'] == 'CARD') {
                // call for pesamoni / flutterwave
                $pesamoni_uri = 'https://pesamoni.com/api/live/v1/transactions';
                $token = time() . $order_number;
                $card_data = array(
                    'amount' => $json_data['amount'],
                    'apiusername' => '732308812496456', //eg 732308812496456 555254730066043
                    'apipassword' => '5ec03f52e0d151811d43', //eg 5ec03f52e0d151811d43 86ea6b2ef754115eb906
                    'method' => 'cardaccept',
                    'holdername' => $json_data['payment_details']['card_details']['holdername'],
                    'cardnumber' => $json_data['payment_details']['card_details']['cardnumber'],
                    'cvv' => $json_data['payment_details']['card_details']['cvv'],
                    'exp' => $json_data['payment_details']['card_details']['exp'],
                    'token' => $token,
                    'currency' => 'UGX',

                );
                //initialize curl
                $ch = curl_init($pesamoni_uri);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($card_data));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json'
                ));
                //execute the curl
                $result = curl_exec($ch);
                // $data['info'] = $result;

                // store transaction details

                $txn_data = array(
                    "order_number" => $order_number,
                    "token" => $token,
                    "amount" => $json_data['amount'],
                    "transaction_type" => "CARD",
                    "status" => "pending",
                    "date_added" => time()
                );

                if ($this->db->insert('transactions', $txn_data)) {

                    // print $result;

                    // on success of the txn  using the token give value
                    return $this->output
                        ->set_content_type('application/json')
                        ->set_status_header(200)
                        ->set_output(json_encode(array(
                            'success' => true,
                            'message' => 'initiated',
                            'token' => $token,
                            'card_processor' => $result
                        )));
                } else {
                    return $this->output
                        ->set_content_type('application/json')
                        ->set_status_header(200)
                        ->set_output(json_encode(array(
                            'success' => false,
                            'message' => 'txn info not saved',

                        )));
                }
            }
        }
    }
    
public function verify_order(){
    
    $json_data = json_decode(@file_get_contents('php://input'), true);
    
    // $token = $_GET['token'];
    // print $token;
    // return;
    
    
    if($json_data !=null){
        // flutter wave data
        $token =$json_data['data']['tx_ref'];
        $status =$json_data['data']['status'];
         if($status =='successful'){
        // set transaction to success
        // set order to successful
        
        // get transaction
        $transaction = $this->db->get_where('transactions',array('token'=>$token))->row();
        
        $this->db->where('token',$token);
        $this->db->set('status','successful');
        if($this->db->update('transactions')){
            // also set the order payment_status to success
            
            $order = $this->db->get_where('orders',array('order_number'=>$transaction->order_number))->row();
           
            $this->db->where('order_number',$transaction->order_number);
            
            $this->db->set('payment_status','successful');
            
            if($this->db->update('orders')){
                
                // also reduce the product number
                // get products from a given order and update each of the
               
                
              $user_id = $this->db->get_where('orders',array('order_number'=>$transaction->order_number))->row()->user_id;
                
                $shipping_details = json_decode($order->shipping_details);


                $users_name;
                $user;
                if($user_id !='guest'){
                
                    $user = $this->db->get_where('users',array('id'=>$user_id))->row();
                    $users_name = $user->firstname." ". $user->lastname;
                
                }else{
                    $users_name = "customer 🙂";
                }

                
                $products_html = "";
                
                 $products = $this->db->get_where('product_in_order',array('order_id'=>$order->id))->result_array();
                // loop through the products and update each
                
               
                
                foreach($products as $product){
                    
                    //first get the product and update its available quantity
                    $order_product = $this->db->get_where('products',array('id'=>$product['product_id']))->row();

                
                
                
                    $this->db->where('id',$product['product_id']);
                    $this->db->set('number_of_products', ($order_product->number_of_products-$product['quantity']));
                    
                    $this->db->update('products');
                    $product_price =((int)$product['quantity']*(int)$order_product->product_price);
                 

//  $products_html += "
//         <tr>
//                             <td style='height: 50px;padding: 15px; border: 1px solid #ddd;'>
//                                 <p style='text-align: center;'>$order_product->product_name
//                                     <br/>
//                                     <br/>
//                                     <img width='30%' src='$order_product->main_image'>
//                                 </p>
//                             </td>
//                             <td style='height: 50px;padding: 15px; border: 1px solid #ddd;text-align: center;'><span>Testing</span></td>
//                             <td style='height: 50px;padding: 15px; border: 1px solid #ddd; text-align: center;'>2</td>
//                             <td style='height: 50px;padding: 15px; border: 1px solid #ddd;text-align: center;'>
//                                 <strong>4</strong></td>
//                         </tr>
        
//         ";
                  
                  
                  $products_html .= "
        <tr>
                            <td style='height: 50px;padding: 15px; border: 1px solid #ddd;'>
                                <p style='text-align: center;'>".$order_product->product_name."
                                    <br/>
                                    <br/>
                                    <img width='30%' src=".$order_product->main_image.">
                                </p>
                            </td>
                            <td style='height: 50px;padding: 15px; border: 1px solid #ddd;text-align: center;'><span>".$order_product->product_description."</span></td>
                            <td style='height: 50px;padding: 15px; border: 1px solid #ddd; text-align: center;'>".(int)$product['quantity']."</td>
                            <td style='height: 50px;padding: 15px; border: 1px solid #ddd;text-align: center;'>
                                <strong>UGX ".$order_product->product_price."</strong></td>
                        </tr>
          
            
            
            ";
            
   
                }
                
                
                
                
                 $nice_html = "
            
            <article>
<section>
<div style='width: 100%; padding-top:50px;'>
    <div style='width: 80%; margin: auto;'>
        <div style='margin: auto;'>
            <h1 style='float:left;'>
                <span style='font-weight: 300;'>ORDER NUMBER :</span>
                <strong>$transaction->order_number</strong>
            </h1>
            <img width='15%' style='float: right;' src='https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcROpXpIkNHT04iq7VhBGOf_4JYFajRNGLnlLg&usqp=CAU'>
            <div style='clear: both;'>
            </div>
        </div>
    </div>
    <hr/>
</section>


<section>
<div style='width: 100%; '>
    <div style='width: 80%; margin: auto; '>
        <h2>Dear $users_name,</h2>

        <p>Thank you for  the purchase, we deeply appreciate your endeavours. Below is your order summary. You can use the unique order number to track your order. Delivery is free of charge within Kampala City; make sure you entered the right address
            when making your order for precise delivery of your product(s).
           <a style='color:#EB4B5C' href='https://www.instagram.com/everythingirly_eastafrica/'> #Evrythingirly</a>
            </p>

        <section>
            <div style='padding: 20px 0px;'>
                <h3 style='>DELIVERY DETAILS</h3>
                <table style='border: 1px solid #ddd;border-collapse: collapse;width: 100%;'>
                    <tbody>
                        <tr>
                            <td style='height: 50px;padding: 15px; border: 1px solid #ddd; background-color: #f2f2f2;'>NAME:</td>
                            <td style='height: 50px;padding: 15px; border: 1px solid #ddd;'>$shipping_details->fname $shipping_details->lname</span></td>
                            <td style='height: 50px;padding: 15px; border: 1px solid #ddd; background-color: #f2f2f2;'>ADDRESS/STREET/BUILDING:</td>
                        </tr>

                        <tr>
                            <td style='height: 50px;padding: 15px; border: 1px solid #ddd; background-color: #f2f2f2;'>PHONE NUMBER:</td>
                            <td style='height: 50px;padding: 15px; border: 1px solid #ddd;'><span>$shipping_details->phone</span></td>
                            <td rowspan='2' style='height: 50px;padding: 15px; text-align:center; border: 1px solid #ddd;'>
                            $shipping_details->address
                                <br/> $shipping_details->region $shipping_details->city $shipping_details->country
                                
                            </td>
                        </tr>

                        <tr>
                            <td style='height: 50px;padding: 15px; border: 1px solid #ddd; background-color: #f2f2f2;'>EMAIL:</td>
                            <td style='height: 50px;padding: 15px; border: 1px solid #ddd;'><span>$shipping_details->email</span></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </section>

        <section>
            <div style='padding-top: 30px;'>
                <h3>ORDER DETAILS</h3>
                <table style='border-collapse: collapse;width: 100%;'>
                    <thead style='background-color: #f2f2f2;'>
                        <th style='height: 50px;padding: 15px; border: 1px solid #ddd;'>PRODUCT</th>
                        <th style='height: 50px;padding: 15px; border: 1px solid #ddd;'>DESCRIPTION</th>
                        <th style='height: 50px;padding: 15px; border: 1px solid #ddd;'>QUANTITY</th>
                        <th style='height: 50px;padding: 15px; border: 1px solid #ddd;'>UNIT COST</th>
                    </thead>
                    <tbody>
                       $products_html

                        <tr>
                            <td colspan='2' style='height: 50px;padding: 15px;'></td>
                          
                            <td style='height: 50px;padding: 15px; border: 1px solid #ddd; text-align: center;'>
                                <strong>TOTAL</strong></td>
                            <td style='height: 50px;padding: 15px; border: 1px solid #ddd; text-align: center;'>
                                <strong>UGX $order->amount</strong>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </section>

        <section>
            <div style='padding:30px 0px;'>
                <table style='border-collapse: collapse;width: 100%;'>
                    <tr style='background-color: #f2f2f2;'>
                        <td style='height: 50px;padding: 15px; border: 1px solid #ddd;'>FREE DELIVERY IN 6 WORKING HRS WITHIN KAMPALA CITY, UGANDA</td>
                        <td style='height: 50px;padding: 15px; border: 1px solid #ddd;text-align: center;'>PAYMENT TYPE : MOBILE MONEY</td>
                    </tr>
                </table>
            </div>
        </section>


        <section>
            <div style='padding:30px 0px; width:60%; margin:auto; text-align:center; color:rgb(18, 159, 240);'>
                <span><small>Thanks, EG Sales  Team</small> </span>
                <br/>
                <span><small>Pentagon City Acarde PC475, Kampala</small></span>
                <br/>
                <span><small>Directly Call us on +256 783096053 for inquires | Get us on Instagram <a href='https://www.instagram.com/evrythingirly.com_eshops/'> @evrythingirly.com_eshops</a></small></span>
            </div>
        </section>

        

    </div>
</div>
</section>
</article>
            ";
                 
                
                
                
                
                // send email having these details
                
                
                 $config = array(
                    'protocol' => 'sendmail',
                    'smtp_host' => 'evrythingirly.com',
                    'smtp_keepalive'=>TRUE,
                    'smtp_port' => 656,
                    'validate'=>FALSE,
                    'smtp_user' => 'no-reply@evrythingirly.com',
                    'smtp_pass' => 'noreply@evrythingirly',
                    'mailtype' => 'html',
                    'charset' => 'iso-8859-1'
                );
                
                $this->load->library('email');
                $this->email->set_header('Content-Type', 'text/html');
                $this->email->from('no-reply@evrythingirly.com', 'Evrythingirly');
                $this->email->to($user->email);
                
                  $this->email->subject('Purchase Successful 🥰');
                $this->email->message($nice_html);
               
                 
               if ($this->email->send()) {
                print "Transaction successful";
                return;
                   
               }
            }  
            
        }
        
        
    } else {
         // set transaction to cancelled
        // set order to cancelled
        
        // get transaction
        $transaction = $this->db->get_where('transactions',array('token'=>$token))->row();
        
        $this->db->where('token',$token);
        $this->db->set('status','cancelled');
        if($this->db->update('transactions')){
            // also set the order status to success
            $this->db->where('order_number',$transaction->order_number);
            $this->db->set('payment_status','cancelled');
            if($this->db->update('orders')){
                print "Transaction failed";
                return;
            }        
        }
        
    }
        
    }
    
    
    
    // else if its post data
    // this is pesamoni
if($_SERVER['REQUEST_METHOD'] === 'POST'){
    
    $token = $_POST['token'];
    $status = $_POST['status'];
    
    if($token !=null && $status !=null){
    // $reference = $json_data['reference'];
    if($status =='success'){
        // set transaction to success
        // set order to successful
        
        // get transaction
        $transaction = $this->db->get_where('transactions',array('token'=>$token))->row();
        
        $this->db->where('token',$token);
        $this->db->set('status','successful');
        if($this->db->update('transactions')){
            // also set the order payment_status to success
            
            $order = $this->db->get_where('orders',array('order_number'=>$transaction->order_number))->row();
           
            $this->db->where('order_number',$transaction->order_number);
            
            $this->db->set('payment_status','successful');
            if($this->db->update('orders')){
                print "Transaction successful";
                return;
            }         
        }
    }else{
        $transaction = $this->db->get_where('transactions',array('token',$token))->row();
        
        $this->db->where('token',$token);
        $this->db->set('status','cancelled');
        if($this->db->update('transactions')){
            // also set the order status to success
            $this->db->where('order_number',$transaction->order_number);
            $this->db->set('payment_status','cancelled');
            if($this->db->update('orders')){
                print "Transaction failed";
                return;
            }        
        }
    }
        
    } else {
         // set transaction to cancelled
        // set order to cancelled
        
        // get transaction
      if($token !=null && $status !=null){  
        $transaction = $this->db->get_where('transactions',array('token',$token))->row();
        
        $this->db->where('token',$token);
        $this->db->set('status','cancelled');
        if($this->db->update('transactions')){
            // also set the order status to success
            $this->db->where('order_number',$transaction->order_number);
            $this->db->set('payment_status','cancelled');
            if($this->db->update('orders')){
                print "Transaction failed";
                return;
            }        
        }
      }else{
           print "Transaction failed";
                return;
      }
        
    }
}else{
     print "Transaction failed GET Request";
                return;
}
}

public function check_transaction(){
    
        $json_data = json_decode(@file_get_contents('php://input'), true);
        
       $txn = $this->db->get_where('transactions',array('token'=>$json_data['token']))->row();
       
       if($txn->status =='successful'){
           return $this->output
                        ->set_content_type('application/json')
                        ->set_status_header(200)
                        ->set_output(json_encode(array(
                            'success' => true,
                            'message' => 'Transaction successful',

                        )));
       } else  if($txn->status =='cancelled'){
            return $this->output
                        ->set_content_type('application/json')
                        ->set_status_header(200)
                        ->set_output(json_encode(array(
                            'success' => false,
                            'message' => 'Transaction cancelled',

                        )));
           
       }else{
            return $this->output
                        ->set_content_type('application/json')
                        ->set_status_header(200)
                        ->set_output(json_encode(array(
                            'success' => false,
                            'message' => 'Transaction pending',

                        )));
       }
        
        
}



    public function get_order($id)
    {
        $this->db->where('id',$id);
        $this->db->select('orders.id, orders.order_number,orders.payment_type,orders.shipping_details,orders.phone,orders.network, orders.time_added');
        $this->db->from('orders');
        
        $query = $this->db->get(); 

        $order  = $query->row();

        $this->db->where('order_id',$id);
        $this->db->select('product_in_order.product_id, product_in_order.quantity,product_in_order.currency,products.product_name,products.main_image,products.product_description');
        $this->db->from('product_in_order');
        $this->db->join('products','products.id = product_in_order.product_id');
        $query_= $this->db->get();
        
        $order_products = $query_->result_array();
        $prepared_order = array();
        
        $this->db->get_where('product_in_order',array('order_id'=>$id))->result_array(); // need to join the products table
        array_push($prepared_order,array('order'=>$order,'products'=>$order_products)); 
     

     return $this->output
         ->set_content_type('application/json')
         ->set_status_header(200)
         ->set_output(json_encode(array(
             'success' => true,
             'order' => $prepared_order
         )));

    }

    public function get_orders()
    {
        $this->db->select('orders.id, orders.order_number,orders.payment_type,orders.shipping_details,orders.phone,orders.network, orders.time_added');
        $this->db->from('orders');
        $query = $this->db->get();

        $orders = $query->result_array();

        $prepared_orders = array(); // prepare an array for these orders

        foreach($orders as $order){
            // for each order get the product in each of them
            // here we can get successful orders or failed orders

           $this->db->where('order_id',$order['id']);
           $this->db->select('product_in_order.product_id, product_in_order.quantity,product_in_order.currency,products.product_name,products.main_image,');
           $this->db->from('product_in_order');
           $this->db->join('products','products.id = product_in_order.product_id');
           $query = $this->db->get();
           
            $order_products = $query->result_array();
           
           $this->db->get_where('product_in_order',array('order_id'=>$order['id']))->result_array(); // need to join the products table
           array_push($prepared_orders,array('order'=>$order,'products'=>$order_products));
        }

        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => true,
                'orders' => $prepared_orders
            )));
    }
    
    public function get_user_orders($user){
        
         $this->db->select('orders.id, orders.order_number,orders.payment_status,orders.payment_type,orders.shipping_details,orders.phone,orders.network, orders.time_added');
         $this->db->where("user_id",$user);
        $this->db->from('orders');
        $query = $this->db->get();

        $orders = $query->result_array();

        $prepared_orders = array(); // prepare an array for these orders

        foreach($orders as $order){
            // for each order get the product in each of them
            // here we can get successful orders or failed orders

           $this->db->where('order_id',$order['id']);
           $this->db->select('product_in_order.product_id, product_in_order.quantity,product_in_order.currency,products.product_description,products.product_name,products.main_image,');
           $this->db->from('product_in_order');
           $this->db->join('products','products.id = product_in_order.product_id');
            
           $query = $this->db->get();
           
            $order_products = $query->result_array();
           
           $this->db->get_where('product_in_order',array('order_id'=>$order['id']))->result_array(); // need to join the products table
           array_push($prepared_orders,array('order'=>$order,'products'=>$order_products));
        }

        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => true,
                'orders' =>array_reverse( $prepared_orders)
            )));
    }
}
