<?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');

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

	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['TotalImageUpload'] = $site_row['max_number_of_faces'];
	

		$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 album_tb.user_id = '".$userdata['id']."'");

        //$data['package_list'] = $this->PackageModel->get_qrscan_package_rows(" where pht.user_id = '" . $userdata['id'] . "' and pt.price > 0 order by pht.id desc");
        //$data['prepackage_list'] = $this->PrepackageModel->get_paid_prepackage_rows(" where package_history_tb.user_id = '" . $userdata['id'] . "' and package_tb.price > 0 order by package_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");
		$aa = explode('/',$userdata['qr_token']);
		$token = rtrim($aa[4],'"');  
		
		$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['prepackage_list'] = $this->PrepackageModel->get_qrscan_prepackage_rows(" where ppqt.token = ppht.token and pt.price > 0 order by ppqt.id desc" , $userdata['id']);

		$data['package_list'] = $this->PackageModel->get_paid_package_rows(" where pht.user_id = '" . $userdata['id'] . "' and pt.price > 0 order by pht.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['getGuest'] = $this->db->where('id', $userdata['id'])->get('guest_tb')->row();
		$data['getExtraFace'] = $this->db->where('guest_id', $userdata['id'])->get('extra_faces_tb')->result();

		$data['header_title'] = 'Profile';


		// $this->SiteDataModel->insert_row();

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

	public function profile_delete($id)
	{
		if(!empty($_GET['guest']))
		{
			$this->db->where('id', $id);
			$this->db->set('photo_url', '');
			$this->db->update('guest_tb');
		}
		else
		{
			$this->db->where('id', $id);
			$this->db->delete('extra_faces_tb');
		}

		$this->session->set_flashdata('success', 'Profile successfully deleted');
		redirect(base_url('account'));
	}
	
	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));
	    
	    $this->SiteDataModel->insert_row('', 'Refund', 'Online Purchased Packages');

	    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']);
		
        
	    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' => 'Prepackage has purchased successfully!'
            	        ));

            	        // 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' => 'Prepackage failed!'
            	        ));

            	        // 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' => 'Prepackage is invalid!'
	        ));

	        // 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>'
	        // ));
	    }
	}
	public function add_image_qr()
    {
        $userdata     = $this->session->userdata('makeabl2020');
        $token        = $this->input->post('token', TRUE);
        $guest_detail = $this->GuestModel->get_qr_row($token);

        $album_lists = $this->GalleryModel->get_qr_album_row($guest_detail['id']);
        foreach($album_lists as $album_list)
        {
            $update_data = array(
                'user_id' => $userdata['id'],
            );
            $this->GalleryModel->update_album_row($update_data, array('id' => $album_list['id']));
        }

        $gallery_lists = $this->GalleryModel->get_qr_row($guest_detail['id']);
        foreach($gallery_lists as $gallery_list)
        {
            $update_data = array(
                'user_id' => $userdata['id'],
            );
            $this->GalleryModel->update_row($update_data, array('id' => $gallery_list['id']));
        }
        
        $aa = base_url().'register/';
        $segments = str_replace($aa, '', $token);
        $segments2 = str_replace('"', '', $segments);
        
        $prepackage_data = $this->PrepackageModel->get_row_with_token($segments2);
        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' => $segments2,
                        '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>',
                        //                  ));

                          echo json_encode(array(
                             'code' => '200',
                             'msg' => 'Prepackage has purchased successfully!',
                         ));
                    }
                    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>',
                             //             ));

                         echo json_encode(array(
                             'code' => '202',
                             'msg' => 'Prepackage failed!',
                         ));
                    }
                }
            }
        }

        echo  '200';
    }
}
