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

class PurchaseController extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model('GuestModel');
		$this->load->model('SiteModel');
		$this->load->model('PackageModel');
		$this->load->model('PrepackageModel');
		$this->load->model('AuthModel');
		$this->load->model('NotificationModel');
		//$this->load->library('Paypal_lib');

        $this->load->model('SiteDataModel');
        // $this->SiteDataModel->insert_row();
	}

	public function index()
	{
		$userdata = $this->session->userdata('makeabl2020');
		if (empty($userdata) || !isset($userdata["id"]))
			redirect('login', 'refresh');
			
        $site_row = $this->SiteModel->get_row($userdata['site_id']);
		$where = " where package_tb.id > 0 and package_tb.is_display = 0 and package_tb.isDeleted = 0 ";

		$data['title'] = 'Purchase Pass | MAKEABL';
		$data['userdata'] = $userdata;
		$data['guest_detail'] = $this->GuestModel->get_row($userdata['id']);
		$data['purchase_list'] = $this->PackageModel->get_purchase_rows($where."and site_tb.id = '".$userdata["site_id"]."' group by package_tb.id order by package_tb.id desc");
		$data['notification_list'] = $this->NotificationModel->get_rows(" where id > 0 and isDeleted = 0 and guest_id = '".$userdata["id"]."' order by id desc");
		$data['new_notification_count'] = $this->NotificationModel->get_count(" where id > 0 and isDeleted = 0 and guest_id = '".$userdata["id"]."' and isShow = 0");
        $data['site_logo'] = 'http://d38x82mkkml5o1.cloudfront.net/'.$site_row['logo'];
		$data['is_single_gallery'] = $site_row['is_single_gallery'];
            
        $data['header_title'] = 'Package';

		$this->load->view('template/header', $data);
		$this->load->view('template/sidebar', $data);
		$this->load->view('digital-pass', $data);
		$this->load->view('template/footer', $data);
	}


    public function getPurchaseDate()
    {
        $userdata = $this->session->userdata('makeabl2020');   
        $where = " where package_tb.id > 0 and package_tb.is_display = 0 and package_tb.isDeleted = 0 ";
        $purchase_list = $this->PackageModel->get_purchase_rows($where."and site_tb.id = '".$userdata["site_id"]."' and package_tb.id = '".$this->input->post('id')."' group by package_tb.id order by package_tb.id desc");

        $data['val'] = $purchase_list[0];

        $html = $this->load->view('parts/_purchase_date', $data, TRUE);

        $json['html'] = $html;
        echo json_encode($json);
    }
	
	public function purchase() {
	    
    
	   $userdata = $this->session->userdata('makeabl2020');
	   
        if(empty($userdata) || !isset($userdata["id"]))
        {
            redirect('login', 'refresh');
        }
        

        $token      = $userdata['qr_token'];
        $guest_id   = $this->input->post("guest_id", TRUE);
        $package_id = $this->input->post("package_id", TRUE);
        $from_date  = $this->input->post('from_date', TRUE);
        $validity   = $this->input->get('validity', TRUE);
        $price      = $this->input->post('price', TRUE);
        $usd_price  = $this->input->post('usd_price', TRUE);
        $currency   = $this->get_currency_rows($userdata['site_id']);
        $currency   = strtolower($currency['iso_code']);
        $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);

        //        Set variables for paypal form
        //        $returnURL = base_url() . 'packagepaypal/success?guest_id=' . $guest_id . '&package_id=' . $package_id . '&from_date=' . $from_date . '&validity=' . $validity;
        //        $cancelURL = base_url() . 'packagepaypal/cancel?guest_id=' . $guest_id . '&package_id=' . $package_id . '&from_date=' . $from_date . '&validity=' . $validity;
        //        $notifyURL = base_url() . 'packagepaypal/ipn?guest_id=' . $guest_id . '&package_id=' . $package_id . '&from_date=' . $from_date . '&validity=' . $validity . '&user_email=' . $userdata["email"];

        require_once('application/libraries/stripe-php/init.php');
        \Stripe\Stripe::setApiKey($this->config->item('stripe_secret'));
        
        // $currency = 'INR';
        $stripeInfo = \Stripe\Charge::create(
            [
                "amount" => $price * 100,
                "currency" => 'HKD',
                "source" => $this->input->post('stripeToken'),
                "description" => "HKOW Photo.",
            ]
        );
        
        
        // make a get request to api
        $this->session->set_flashdata('success', 'Payment is successful.');
        
        $data['guest_id']          = $guest_id;
        $data['package_id']        = $package_id;
        $data['charge_id']         = $stripeInfo["id"];
        $data['txn_id']            = $stripeInfo["balance_transaction"];
        $data['payment_gross']     = $price;
        $data['payment_gross_usd'] = $usd_price;
        $data['currency_code']     = $currency;
        if($stripeInfo['outcome']['seller_message'] == 'Payment complete.')
        {
            $data['payment_status'] = "Completed";
        }
        else
        {
            $data['payment_status'] = "failed";
        }

        $data['created_at'] = date('Y-m-d H:i:s');
        $this->PackageModel->insertTransaction($data);
        
        $insert_data = array(
                'package_id' => $package_id,
                'from_date' => $from_date,
                'to_date' => $to_date,
                's_from_date' => $s_from_date,
                's_to_date' => $s_to_date,
                'user_id' => $guest_id,
                'txn_id' => $data['txn_id'],
                'created_at' => date('Y-m-d H:i:s'),
            );

        $resp = $this->PackageModel->insert_history_row($insert_data);

        $prepackage_data = $this->PrepackageModel->get_row_with_token($token);
        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($userdata['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();
        }
            
        if($prepackage_data['isUse'] == 0)
        {
            $package_data = $this->PrepackageModel->get_row($prepackage_data['prepackage_id']);
            if($package_data)
            {
                $result = $this->PackageModel->get_row($package_data['package_id']);
                if($result)
                {
                    $prepackage_history_data = array(
                        'prepackage_id' => $prepackage_data['prepackage_id'],
                        'user_id' => $userdata['id'],
                        'token' => $token,
                        'price' => $result['price'],
                        'created_at' => date('Y-m-d H:i:s'),
                    );
                    
                    $add_prepackage_history = $this->PrepackageModel->insert_prepackage_history_row($prepackage_history_data);
                 
                    if($add_prepackage_history)
                    {

                        $update_data = array(
                            'isUse' => 1,
                        );
                        $this->PrepackageModel->update_detail_row($update_data, array('id' => $prepackage_data['id']));

                        echo json_encode(
                            array(
                                'code' => '200',
                                'msg' => '<div class="alert alert-success 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>
                						Prepackage has purchased successfully!
                					</div>',
                            )
                        );
                    }
                    else
                    {
                        echo json_encode(
                            array(
                                'code' => '202',
                                'msg' => '<div class="alert alert-danger 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>
                						Prepackage failed!
                					</div>',
                            )
                        );
                    }
                }
            }
        }
        else
        {
            echo json_encode(
                array(
                    'code' => '201',
                    'msg' => '<div class="alert alert-danger 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>
    						Prepackage is invalid!
    					</div>',
                )
            );
        }
        
        $this->session->set_userdata('payg-gallery', $data);

        redirect('/purchase', 'refresh');
	}
	
	function get_currency_rows($id)
    {
        $sql   = "SELECT iso_code, country_id FROM site_tb st
                INNER JOIN country_tb ct ON ct.id = st.country_id
                WHERE st.id = $id";
        $query = $this->db->query($sql);

        return $query->row_array();
    }
}
