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

class AccountController extends CI_Controller {

	public function __construct()
	{
		parent::__construct();		
		$this->load->model('GuestModel');
		$this->load->model('SiteModel');		
		$this->load->model('CartModel');		
		$this->load->model('GalleryModel');
		$this->load->model('AuthModel');
		$this->load->model('OrderModel');
		$this->load->model('PackageModel');
		$this->load->model('PrepackageModel');
		$this->load->model('BackgroundModel');
		$this->load->model('NotificationModel');
		$this->load->library('ciqrcode');
	}

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

        $msg = '';

		$save_btn = $this->input->post('save_btn', TRUE);
		if($save_btn == "ok"){
			$password = $this->input->post('password', TRUE);
			$phone = $this->input->post('phone', TRUE);
			$address = $this->input->post('address', TRUE);

			if($password == ""){
				$guest_data = array(
					'address' => $address,
					'phone' => $phone
				);				
				$this->AuthModel->update_guest_row($guest_data, array('id'=>$userdata['id']));
			}else{
				$guest_data = array(
					'password' => md5($password),
					'address' => $address,
					'phone' => $phone
				);				
				$this->AuthModel->update_guest_row($guest_data, array('id' => $userdata['id']));
			}
		}
		
		$refund_package_btn = $this->input->post('refund_package_btn', TRUE);
		if($refund_package_btn == "ok"){
			$package_history_id = $this->input->post('package_history_id', TRUE);
			$txn_id = $this->input->post('txn_id', TRUE);
			
			$package_status_data = array(
			    'package_status' => 1
			);
			
			$this->AuthModel->update_guest_row($package_status_data, array('id' => $userdata['id']));
			
			$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>
						Your refund request was received successfully!
					</div>';
		}
		
		$site_row = $this->SiteModel->get_row($userdata['site_id']);

		$data['title'] = 'Account | MAKEABL';
		$data['msg'] = $msg;
		$data['userdata'] = $userdata;
		$data['guest_detail'] = $this->GuestModel->get_row($userdata['id']);
		if($site_row['is_single_gallery'] == 1){
		    $data['photo_count'] = $this->GalleryModel->get_count(" where isDeleted = 0 and user_id = '".$userdata['id']."' and site_id = '".$userdata['site_id']."' and location_id <> 0");
		}else{
		    $data['photo_count'] = $this->GalleryModel->get_count(" where isDeleted = 0 and user_id = '".$userdata['id']."' and site_id = '".$userdata['site_id']."'");
		}
		$data['video_count'] = $this->BackgroundModel->get_count(" where background_tb.id > 0 and background_tb.isDeleted = 0 and location_tb.type_id = 1 and background_tb.site_id = '".$userdata['site_id']."'");
		$data['album_count'] = $this->GalleryModel->get_album_count(" where album_tb.id > 0 and album_tb.isDeleted = 0 and gallery_tb.user_id = '".$userdata['id']."'");
		$data['package_list'] = $this->PackageModel->get_package_rows(" where package_history_tb.id > 0 and package_history_tb.isDeleted = 0 and package_history_tb.user_id = '".$userdata['id']."' order by package_history_tb.id desc");
		$data['prepackage_list'] = $this->PrepackageModel->get_prepackage_rows(" where prepackage_history_tb.id > 0 and prepackage_history_tb.isDeleted = 0 and prepackage_history_tb.user_id = '".$userdata['id']."' order by prepackage_history_tb.id desc");
		$data['order_list'] = $this->OrderModel->get_rows(" where order_tb.id > 0 and order_tb.isDeleted = 0 and order_tb.user_id = '".$userdata['id']."' order by order_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://d1z6a3vjnfowyr.cloudfront.net/'.$site_row['logo'];
		$data['is_single_gallery'] = $site_row['is_single_gallery'];
		
		$this->load->view('account', $data);
	}
	
	public function get_order_info()
    { 
		$order_id = $this->input->post("order_id");
		$order_detail_info = $this->OrderModel->get_detail_rows($order_id);
		echo(json_encode($order_detail_info));
	}
	
	public function package_refund(){
	    $txn_id = $this->input->post('txn_id', TRUE);
	    $guest_id = $this->PackageModel->get_guest_id(" where txn_id = '".$txn_id."'");
	    
	    $refund_data = array(
	        'txn_id' => $txn_id,
	        'created_at' => date('Y-m-d')
	    );
	    
	    $this->PackageModel->insert_refund_row($refund_data);
	    
	    $update_status = array(
	        'refund_status' => 1
	    );
	    
	    $payment_id = $this->PackageModel->get_payment_id($txn_id);
	    
	    $this->PackageModel->updateTransaction($update_status, array('payment_id' => $payment_id));
	    
	   // $update_guest_data = array(
	   //     'package_status' => 1  
	   // );
	    
	   // $this->AuthModel->update_guest_row($update_guest_data, array('id' => $guest_id));
	    
	    echo 'success';
	}
	
	public function order_refund(){
	    $order_id = $this->input->post('id', TRUE);
	    $paymentid = $this->OrderModel->get_payment_id_byorderid($order_id);
	    $refund_data = array(
	        'payment_id' =>intval($paymentid),
	        'created_at' => date('Y-m-d')
	    );
	    
	    $this->OrderModel->insert_refund_row($refund_data);
	    
	    $update_status = array(
	        'refund_status' => 1
	    );
	    $userdata = $this->session->userdata('makeabl2020');
	    $this->OrderModel->update_order_row($update_status, array('payment_id' => $paymentid));
	    $title = 'Invoice | MAKEABL';
		$site = $this->SiteModel->get_row($userdata['site_id']);
		$order_data = $this->OrderModel->get_for_order_row($order_id);
		$order_list = $this->OrderModel->get_for_order_rows($order_id);
		$country_data = $this->CartModel->get_country_row($userdata['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', 'Makeabl Team');
		$this->email->to($order_data["email"]);

		$this->email->subject('Refund requested');

		$message .='<div class="invoice overflow-auto" id="print_invoice">';
	    $message .='<div style="min-width: 600px">';
		$message .='<header>';
		$message .='<div class="row">';
		$message .='<div class="col company-details">';
		$message .='<h2 class="name">';
		$message .= $title;
		$message .='</h2>';												
		$message .='</div>';
		$message .='</div>';
		$message .='</header>';
		$message .='<main>';
		$message .='<div class="row contacts">';
		$message .='<div class="col invoice-to">';
		$message .='<div class="text-gray-light">INVOICE TO:</div>';
		$message .='<h6>Dear Valued Customer</h6>';		
		$message .='<h6>Refund requested</h6>';		
		$message .='<h6>If you have any questions or concerns please send us an email at service@makeablmoments.com.</h6>';		
		$message .='<h6>Have a great day!HKOW Photo Team</h6>';		
		$message .='<h6>hkow.makeablmoments.com</h6>';		
											
		$message .='</div>';
		$message .='<div class="col invoice-details">';
		$message .='<h1 class="invoice-id">'.$order_data["orderID"].'</h1>';
		$message .='<div class="date">Date of Invoice: '.date("d/m/Y", strtotime($order_data["orderDate"])).'</div>';												
		$message .='</div>';
		$message .='</div>';
		$message .='<table>';
		$message .='<thead>';
		$message .='<tr>';
		$message .='<th>#</th>';
		$message .='<th class="text-left">Merchandise Name</th>';
		$message .='<th class="text-right">PRICE</th>';
		$message .='<th class="text-right">QUANTITY</th>';
		$message .='<th class="text-right">TOTAL</th>';
		$message .='</tr>';
		$message .='</thead>';
		$message .='<tbody>';	
		if(count($order_list) > 0){
		    foreach($order_list as $key => $val)
		    {
		        $message .='<tr>';
		        $message .='<td class="no">'.($key + 1).'</td>';
        		$message .='<td class="text-left">';
        		$message .='<h3>'.$val["deliver"];
        		$message .='<h3>';
        		$message .= $val["deliver"].'</h3>'.$val["merchandise_desc"];
        		$message .='</td>';
        		$message .='<td class="unit">'.$country_data["symbol"].number_format(($val["price"]*(100-$val["discount"])/100), 2).'</td>';
        		$message .='<td class="qty">'.$val["quantity"].'</td>';
        		$message .='<td class="total">'.$country_data["symbol"].number_format(($val["price"]*(100-$val["discount"])/100 * $val["quantity"]), 2).'</td>';
        		$message .='</tr>';
		    }
		}
	
		$message .='</tbody>';
		$message .='<tfoot>';
		$message .='<tr>';
		$message .='<td colspan="2"></td>';
		$message .='<td colspan="2">SUBTOTAL</td>';
		$message .='<td>'.$country_data["symbol"].number_format($order_data["total_price"]-$country_data["tax"], 2).'</td>';
		$message .='</tr>';	
		$message .='<tr>';
		$message .='<td colspan="2"></td>';
		$message .='<td colspan="2">SHIPPING FEE</td>';
		$message .='<td>'; 
		if($order_data["delivery"]=="0"){
		    $message .= $country_data["symbol"]."0";
		}
		else{
		    $message .=$country_data["symbol"].number_format($country_data["tax"], 2);
		}
		$message .='</td>';
		$message .='</tr>';											
		$message .='<tr>';
		$message .='<td colspan="2"></td>';
		$message .='<td colspan="2">GRAND TOTAL</td>';
		$message .='<td>';
		$message .=$country_data["symbol"].number_format(($order_data["total_price"]), 2);
		$message .='</td>';
		$message .='</tr>';
		$message .='</tfoot>';
		$message .='</table>';
		$message .='<div class="thanks">Thank you!</div>';										
		$message .='</main>';
		$message .='<footer></footer>';
		$message .='</div>';
		$message .='</div>';

		$this->email->message($message); 
		$this->email->send();
	    echo 'success';
	}
	
	public function buy_prepackage_qr(){
	    $userdata = $this->session->userdata('makeabl2020');
	    $token = $this->input->post('token', TRUE);
	    
	    $prepackage_data = $this->PrepackageModel->get_row_with_token($token);
	    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>'
	        ));
	    }
	}
}
