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

class OrderPaypalController extends CI_Controller {
	
	function  __construct(){
        parent::__construct();
        $this->load->library('Paypal_lib');
        $this->load->model('GuestModel');
		$this->load->model('SiteModel');
		$this->load->model('CartModel');
		$this->load->model('OrderModel');
		$this->load->model('AuthModel');
		$this->load->model('CartModel');
		$this->load->model('NotificationModel');
    }
     
     function success(){
        $userdata = $this->session->userdata('makeabl2020');
		if (empty($userdata) || !isset($userdata["id"]))
			redirect('login', 'refresh');
			
		$site_id = $this->input->get("site_id", TRUE);
		$id = $this->input->get("id",TRUE);	
		$get_site_name = $this->SiteModel->get_row($site_id);
	    if(count($get_site_name) > 0){
	        $notification_data = "Thank you for purchasing merchandise from ".$get_site_name['title'].". Please check your email for further updates.";
    	    $insert_notification_data = array(
    	        'class_info' => 'bx bx-gift',
    	        'notification' => $notification_data,
    	        'guest_id' => $userdata['id'],
    	        'created_at' => date('Y-m-d H:i:s')
    	    );
    	    
    	    $this->NotificationModel->insert_row($insert_notification_data);
    	    
    	    /////////////////////////////////////////
    	    
    	    $url_path  = 'https://mymakeabl.com/api/send_push_notification';
            $data = array(
                'guest_id' => $userdata['id'], 
                'msg_content' => $notification_data
            ); 
            
            $query = http_build_query($data);
            $options = array(
                'http' => array(
                    'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
                                "Content-Length: ".strlen($query)."\r\n".
                                "User-Agent:MyAgent/1.0\r\n",
                    'method'  => "POST",
                    'content' => $query,
                ),
            );
            
            $stream = stream_context_create($options); 
            file_get_contents($url_path, false, $stream); 
            
            //////////////////////////////////////////
	    }
			
		$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>';
    	
    	$data['title'] = 'Cart | MAKEABL';
		$data['userdata'] = $userdata;
		$site_data = $this->SiteModel->get_row($userdata['site_id']);
		$data['site_logo'] =  'http://d1z6a3vjnfowyr.cloudfront.net/'.trim(preg_replace('/\s\s+/', ' ', $site_data['logo'])); 
		$data['msg'] = $msg;
		$data['guest_detail'] = $this->GuestModel->get_row($userdata['id']);
		$data['country_list'] = $this->CartModel->get_country_rows();
		$update_data = array(
	        'isCheckout' => 1
	    );
	    $site_row = $this->SiteModel->get_row($userdata['site_id']);
	    $data['is_single_gallery'] = $site_row['is_single_gallery'];
	    $cart_ids = $this->input->get("cart_ids", TRUE);
	    foreach(explode(",",$cart_ids) as $key => $val){
	        $this->CartModel->update_row($update_data,array('id'=>$val));
	    }
	    $data['cart_list'] = $this->CartModel->get_rows(" where cart_tb.id > 0 and cart_tb.isCheckout = 0 and cart_tb.user_id = '".$userdata["id"]."' 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['pay']="re";
		$this->load->view('template/header', $data);
		$this->load->view('template/sidebar', $data);		
		$this->load->view('cart', $data);		
		$this->load->view('template/footer', $data);
	
    }   
    
    function cancel(){
        $userdata = $this->session->userdata('makeabl2020');
		if (empty($userdata) || !isset($userdata["id"]))
			redirect('login', 'refresh');

        $msg = '<div class="alert alert-info fade in alert-dismissible show">
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true" style="font-size:20px">×</span>
                    </button>Sorry, Please try again.
                </div>';

		$data['title'] = 'Cart | MAKEABL';
		$data['userdata'] = $userdata;
		$data['msg'] = $msg;
		$data['guest_detail'] = $this->GuestModel->get_row($userdata['id']);
		$data['country_list'] = $this->CartModel->get_country_rows();
		$data['cart_list'] = $this->CartModel->get_rows(" where cart_tb.id > 0 and cart_tb.isCheckout = 0 and cart_tb.user_id = '".$userdata["id"]."' 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");
		redirect("cart", 'refresh');
// 		$this->load->view('template/header', $data);
// 		$this->load->view('template/sidebar', $data);		
// 		$this->load->view('cart', $data);		
// 		$this->load->view('template/footer', $data);
// 		redirect("cart", 'refresh');
		
    }
    
    function ipn(){
        $paypalInfo = $this->input->post();
        // redirect("cart", 'refresh');
        if(!empty($paypalInfo)){
            $ipnCheck = $this->paypal_lib->validate_ipn($paypalInfo);
            if($ipnCheck){
                $curl = curl_init();
                $orderID = $this->input->get("orderID", TRUE);
                $isDelivery = $this->input->get("isDelivery", TRUE);
                $total_price = $this->input->get("total_price", TRUE);
                $total_price_usd = $this->input->get("total_price_usd", TRUE);
                $currency = $this->input->get("currency", TRUE);
                $user_id = $this->input->get("user_id", TRUE);
                $site_id = $this->input->get("site_id", TRUE);
                $is_paid = $this->input->get("is_paid", TRUE);
                $name = $this->input->get("name", TRUE);
                $phone = $this->input->get("phone", TRUE);
                $address = $this->input->get("address", TRUE);
                $created_at = $this->input->get("created_at", TRUE);
                $cart_ids = $this->input->get("cart_ids",TRUE);
                $guest_id       = $paypalInfo["custom"];
                $txn_id         = $paypalInfo["txn_id"];
                $payment_gross  = $paypalInfo["mc_gross"];
                $currency_code  = $paypalInfo["mc_currency"];
                $payer_email   = $paypalInfo["payer_email"];
                $payment_status = $paypalInfo["payment_status"];
                $created_at     = date('Y-m-d H:i:s');
                
                
                
                curl_setopt_array($curl, array(
                  CURLOPT_URL => 'https://mymakeabl.com/api/paypal_order_pay',
                  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 => 'transaction_id='.$txn_id.'&currency_code='.$currency_code.'&paypal_amount='.$payment_gross.'&payer_email='.$payer_email.
                  '&orderID='.$orderID.'&isDelivery='.$isDelivery.'&total_price='.$total_price.'&currency='.$currency.'&total_price_usd='.$total_price_usd.
                  '&user_id='.$user_id.'&site_id='.$site_id.'&cart_ids='.$cart_ids.'&name='.$name.'&phone='.$phone.'&address='.$address,
                  CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/x-www-form-urlencoded'
                  ),
                ));
                
                $response = curl_exec($curl);
                
                curl_close($curl);
                
               // redirect($_SERVER['REQUEST_URI'], 'refresh'); 
                if(strpos($response, 'success')){
					try {
					 
                	
                		$order_data = $this->OrderModel->get_for_order_row($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']    = 'makeablmoments.com';
                		$config['smtp_port']    = '587';
                		$config['smtp_timeout'] = '60';
                		$config['smtp_user']    = 'service@makeablmoments.com';
                		$config['smtp_pass']    = 'makeabl2020!';
                		$config['mailtype']     = 'html';
                		$config['charset']      = 'utf-8';
                		$config['newline']      = '\r\n';
                
                		$this->email->initialize($config);
                
                		$this->email->from('service@makeablmoments.com', 'HKOW Photo Team');
                		$this->email->to($order_data["email"]);
                		$this->email->subject("HKOW Photo Product 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:service@makeablmoments.com" target="_blank">service@makeablmoments.com</a>.<br/><br/>';
                        $message .= 'Have a great day!<br/>';
                        $message .= 'HKOW Photo Team<br/>';
                        $message .= '<a href="http://www.hkow.makeablmoments.com" target="_blank" >hkow.makeablmoments.com</a><br/>';
                        $this->email->message($message); 
                		$this->email->send();
					} catch (Exception $e) {
						echo $e->getMessage();
					}
                }
            
                
            }
        }
    }
}