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

class PackagePaypalController extends CI_Controller {
	
	function  __construct(){
        parent::__construct();
        $this->load->library('Paypal_lib');
        $this->load->model('GuestModel');
		$this->load->model('SiteModel');
		$this->load->model('PackageModel');
		$this->load->model('AuthModel');
		$this->load->model('NotificationModel');

		$this->load->model('SiteDataModel');
		// $this->SiteDataModel->insert_row();
    }
     
    function success(){
        $userdata = $this->session->userdata('makeabl2020');
		$msg = '';
		$guest_id = $this->input->get('guest_id', TRUE);
        $package_id = $this->input->get('package_id', TRUE);
		$from_date  = $this->input->get('from_date', TRUE);
		$validity   = $this->input->get('validity', TRUE);
        $timestamp = strtotime($from_date) + $validity * 3600;
		$to_date = date('Y-m-d', $timestamp);
		$timezone = $this->PackageModel->get_timezone($package_id);
		$s_from_timestamp = strtotime($from_date." 07:00:00") - $timezone * 3600;
		$s_from_date = date('Y-m-d H:i:s', $s_from_timestamp);
		$s_timestamp = strtotime($s_from_date) + $validity * 3600;
		$s_to_date   = date('Y-m-d H:i:s', $s_timestamp);
		
		$where = " where CAST('".$from_date."' AS datetime) >= from_date and CAST('".$from_date."' AS datetime) <= to_date and user_id = '".$guest_id."'";
		
    	$resp = $this->PackageModel->get_site_info_row($where);
    	if(count($resp) > 0){
    	    $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, You have already activated package.
                    </div>';
    	}else{
    	    $get_site_name = $this->PackageModel->get_site_row(" where package_tb.id = '".$package_id."'");
    	    if(count($get_site_name) > 0){
    	        $notification_data = "Thank you for purchasing a Digital Package for ".$get_site_name['site_name']." that is valid from ".$from_date." 07:00:00 to ".$to_date." 06:59:59";
        	    $insert_notification_data = array(
        	        'class_info' => 'bx bx-box',
        	        'notification' => $notification_data,
        	        'guest_id' => $guest_id,
        	        'created_at' => date('Y-m-d H:i:s')
        	    );
        	    $this->NotificationModel->insert_row($insert_notification_data);
        	    /////////////////////////////////////////
        	    $url_path  = 'https://makeabl.net/api/send_push_notification';
                $data = array(
                    'guest_id' => $guest_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); 
                //////////////////////////////////////////
    	    }
    	    
    	    // $txn_id = $this->PackageModel->get_txn_id();
			// $insert_data = array(
			// 	'package_id' => $package_id,
			// 	'from_date' => $from_date." 07:00:00",
			// 	'to_date' => $to_date." 06:59:59",
			// 	's_from_date' => $s_from_date,
			// 	's_to_date' => $s_to_date,
			// 	'user_id' => $guest_id,
			// 	'txn_id' => $txn_id,
			// 	'created_at' => date('Y-m-d H:i:s')
			// );
			
			//remove water mark
            // $guest_qr_token  = $userdata['qr_token'];
            // $qr_token        = explode("/", parse_url($guest_qr_token, PHP_URL_PATH));
            // $qr_token        = rtrim($qr_token[4], '"');
            // $prepackage_data = $this->PrepackageModel->get_row_with_token($qr_token);

            // $update_data = array(
            //     'package_id' => $package_id,
            // );

            // $this->PrepackageModel->update_row($update_data, array('id' => $prepackage_data['prepackage_id']));

			
        	// $resp = $this->PackageModel->insert_history_row($insert_data);
        	// if($resp['status'] == 200){
        	    $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>Congratulation! You have bought this package successfully!
                        </div>';
        	// }else{
        	//     $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>';
        	// }
    	}
    	
    	return redirect('sgallery');
    	
    	$where = " where package_tb.id > 0 and package_tb.isDeleted = 0 and package_tb.is_display = 0 ";
        $site_data = $this->SiteModel->get_row($userdata['site_id']);
        $data['is_single_gallery'] = $site_data['is_single_gallery'];
		$data['title'] = 'Purchase Pass | MAKEABL';
		$data['userdata'] = $userdata;
		$data['msg'] = $msg;
		$data['guest_detail'] = $this->GuestModel->get_row($guest_id);
		$data['purchase_list'] = $this->PackageModel->get_purchase_rows($where."and guest_tb.id = '".$guest_id."' order by package_tb.id desc");
		$data['notification_list'] = $this->NotificationModel->get_rows(" where id > 0 and isDeleted = 0 and guest_id = '".$guest_id."' order by id desc");
		$data['new_notification_count'] = $this->NotificationModel->get_count(" where id > 0 and isDeleted = 0 and guest_id = '".$guest_id."' and isShow = 0");
		$data['site_logo'] =  'http://d38x82mkkml5o1.cloudfront.net/'.trim(preg_replace('/\s\s+/', ' ', $site_data['logo'])); 

		$this->load->view('template/header', $data);
		$this->load->view('template/sidebar', $data);
		$this->load->view('digital-pass', $data);
		$this->load->view('template/footer', $data);
    }
     
    function cancel(){
       $userdata = $this->session->userdata('makeabl2020');

        $guest_id = $this->input->get('guest_id', TRUE);
        
        $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>';
        
		$where = " where package_tb.id > 0 and package_tb.isDeleted = 0 ";
        $site_data = $this->SiteModel->get_row($userdata['site_id']);
		$data['title'] = 'Purchase Pass | MAKEABL';
		$data['userdata'] = $userdata;
		$data['msg'] = $msg;
		$data['guest_detail'] = $this->GuestModel->get_row($guest_id);
		$data['purchase_list'] = $this->PackageModel->get_purchase_rows($where."and guest_tb.id = '".$guest_id."' order by package_tb.id desc");
		$data['is_single_gallery'] = $site_data['is_single_gallery'];
		$data['notification_list'] = $this->NotificationModel->get_rows(" where id > 0 and isDeleted = 0 and guest_id = '".$guest_id."' order by id desc");
		$data['new_notification_count'] = $this->NotificationModel->get_count(" where id > 0 and isDeleted = 0 and guest_id = '".$guest_id."' and isShow = 0");
        $data['site_logo'] =  'http://d38x82mkkml5o1.cloudfront.net/'.trim(preg_replace('/\s\s+/', ' ', $site_data['logo'])); 
	    redirect("purchase", 'refresh');
// 		$this->load->view('template/header', $data);
// 		$this->load->view('template/sidebar', $data);
// 		$this->load->view('digital-pass', $data);
// 		$this->load->view('template/footer', $data);
    }
     
    function ipn(){
        $paypalInfo = $this->input->post();        
        if(!empty($paypalInfo)){
            $ipnCheck = $this->paypal_lib->validate_ipn($paypalInfo);
            if($ipnCheck){

				$curl = curl_init();
                $txn_id         = $paypalInfo["txn_id"];
                $currency_code  = $paypalInfo["mc_currency"];
                $payment_gross  = $paypalInfo["mc_gross"];
                $payer_email   = $paypalInfo["payer_email"];
                $package_id     = $paypalInfo["item_number"];
               
                
				$guest_id = $this->input->get('guest_id', TRUE);
				$package_id = $this->input->get('package_id', TRUE);
				$from_date  = $this->input->get('from_date', TRUE);
				$validity   = $this->input->get('validity', TRUE);	
				$user_email = $this->input->get('user_email', TRUE);
				$timestamp = strtotime($from_date) + $validity * 3600;				
				$to_date = date('Y-m-d', $timestamp);				
				$timezone = $this->PackageModel->get_timezone($package_id);				
				$s_from_timestamp = strtotime($from_date." 07:00:00") - $timezone * 3600;				
				$s_from_date = date('Y-m-d H:i:s', $s_from_timestamp);
				$s_timestamp = strtotime($s_from_date) + $validity * 3600;
				$s_to_date   = date('Y-m-d H:i:s', $s_timestamp);

				curl_setopt_array($curl, array(
                  CURLOPT_URL => 'https://makeabl.net/api/paypal_package_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.'&payment_gross='.$payment_gross.'&payer_email='.$payer_email.              
                  '&user_id='.$guest_id.'&package_id='.$package_id.'&from_date='.$from_date.'&to_date='.$to_date.'&s_from_date='.$s_from_date.'&s_to_date='.$s_to_date,
                  CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/x-www-form-urlencoded'
                  ),
                ));
                
                $response = curl_exec($curl);                
                curl_close($curl);	
                
               if(strpos($response, 'success')){
					try {
						$this->load->library('email');
						
						$config['protocol']     = 'smtp';
						$config['smtp_host']    = 'makeabl.io';
						$config['smtp_port']    = '587';
						$config['smtp_timeout'] = '60';
						$config['smtp_user']    = 'service@makeabl.io';
						$config['smtp_pass']    = 'makeabl2020!';
						$config['mailtype']     = 'html';
						$config['charset']      = 'utf-8';
						$config['newline']      = '\r\n';
		
						$this->email->initialize($config);
		
						$this->email->from('service@makeabl.io', 'HKOW Photo Team');
						$this->email->to($user_email);
		
						$this->email->subject('HKOW Digital Package Purchase');
						$message = 'Dear Valued Customer,<br/><br/>';
						$message .= 'Thank you for completing your purchase. Remember to log on to <a href="http://www.hkow.makeabl.io" target="_blank" >hkow.makeabl.io</a> to register before your photos are captured to enjoy a seamless experience!<br/><br/>';
		                $message .= 'You will find a copy of your purchase record in the My Account page.<br/><br/>';
						$message .= 'If you have any questions or concerns please send us an email at <a href="mailto:service@makeabl.io" target="_blank">service@makeabl.io</a>.<br/><br/>';
		                $message .= 'Have a great day!<br/>';
		                $message .= 'HKOW Photo Team<br/>';
		                $message .= '<a href="http://www.hkow.makeabl.io" target="_blank" >hkow.makeabl.io</a><br/>';
		                
						$this->email->message($message);
						$this->email->send();
					} catch (Exception $e) {
						echo $e->getMessage();
					}
                }
            }
        }
    }
}