<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminReports extends pjAdmin
{
	
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if (!$this->isAdmin() && !$this->isOwner())
		{
			$this->set('status', 2);
			return;
		}
		
		$pjCalendarModel = pjCalendarModel::factory()
		->join('pjMultiLang', sprintf("t2.model='pjCalendar' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='%u'", $this->getLocaleId()), 'left outer')
		->join('pjUser', 't3.id=t1.user_id', 'left outer');
		if ($this->isOwner())
		{
		    $pjCalendarModel->where('t1.user_id', $this->getUserId());
		}
		$calendar_arr = $pjCalendarModel
		->select("t1.id, t1.user_id, t2.content AS `title`")
		->orderBy("title ASC")
		->findAll()->getData();
		$this->set('calendar_arr', $calendar_arr);
		
		$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
		$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
		$this->appendJs('pjAdminReports.js');
	}
	
	public function pjActionGenerate()
	{
	    $this->checkLogin();
	    
	    $this->setAjax(true);
	    
	    if ($this->isXHR() && $this->isLoged())
	    {
	        $option_arr = pjOptionModel::factory()->getPairs($_POST['calendar_id']);
	        
	        $date_from = pjUtil::formatDate($_POST['date_from'], $option_arr['o_date_format'], "Y-n-j");
	        $date_to = pjUtil::formatDate($_POST['date_to'], $option_arr['o_date_format'], "Y-n-j");
	        
	        list($year_from, $month_from, $day_from) = explode("-", $date_from);
	        list($year_to, $month_to, $day_to) = explode("-", $date_to);
	        
	        $queryString = http_build_query(array(
	            'created' => array(
	                'gte' => mktime(0, 0, 0, $month_from, $day_from, $year_from),
	                'lte' => mktime(23, 59, 59, $month_to, $day_to, $year_to),
	            ),
	            'limit' => 10000
	        ), null, '&');
	        
	        $url = "https://api.stripe.com/v1/payment_intents?" . $queryString;
      
	        $http = new pjHttp();
	        $http
	        ->setMethod("GET")
	        ->addHeader("Authorization: Basic " . base64_encode($option_arr['o_stripe_secret_key'] . ":"))
	        ->curlRequest($url);
	        
	        $response = $http->getResponse();
	        $response = json_decode($response, true);
	        $events = $response;
	   
	        $transaction_arr = array();
	        
	        $pjBookingModel = pjBookingModel::factory();
	        $booking_statuses = __('booking_statuses', true);
	        
	        if(isset($events['data']))
	        {
    	        foreach ($events['data'] as $item)
    	        {

    	            if ($item['object'] == 'payment_intent')
    	            {
    	                $record = array();
    	                $record['amount'] = (float) $item['amount_received'] / 100;
    	                $record['started'] = $item['created'];
    	                $record['txn_id'] = $item['id'];
    	                $record['status'] = $item['status'];
    	                $record['uuid'] = $item['description'];
    	                $record['highlight'] = 0;
    	                $record['booking_status'] = '';
						
						$matches = array();
						//$pattern = '/[A-Z]{2}(\d{10})/';  
						$pattern = '/[A-Z]{2}(\d{10})((\-\d{1})*)/';
						preg_match($pattern, $record['uuid'], $matches);
    	                if(isset($matches[0])) 
    	                {
							$uuid = $matches[0];
    	                    $booking = $pjBookingModel->reset()->where('uuid', $uuid)->limit(1)->findAll()->getDataIndex(0);
    	                    if(!empty($booking))
    	                    {
    	                        if($booking['booking_status'] != 'confirmed' && $item['status'] == 'succeeded')
    	                        {
    	                            $record['highlight'] = 1;
    	                        }
    	                        $record['booking_status'] = $booking_statuses[$booking['booking_status']];
    	                    }else{
    	                        $record['highlight'] = 1;
    	                    }
                        }
						
if ($record['highlight'] == 1){

$transaction_arr[] = $record;

}


    	            }    	            
    	        }
	        } elseif (isset($events['error'])){
				echo "<div style='color:red'>".$events['error']['message'].'</div>'; 
			}
	        $this->set('transaction_arr', $transaction_arr);
	    }
	}
}
?>