<?php
include_once ROOT_DIR.'/core/class/ssl.php';
$ssl=new SSL();
create_log('ssl_response',$_GET);
create_log('ssl_response',$_POST);
$jArray=[];
$ref=$_GET['payment_notice'];
$jArray[fl()]=$ref;
if(isset($_GET['status'])&&$_GET['status']=='success'){
    $request=explode('-',$ref);
    if($request[0]=='SC'){
        $request_id=intval(@$request[1]);
        $subscribe_request=$db->get_row('subscribe_request','id',$request_id);
        if(empty($subscribe_request)){
            $error=fl();
            $jArray[fl()]=1;
        }
        elseif($subscribe_request['is_paid']==1){
            $error=fl();
            $jArray[fl()]=1;
        }
        if(!isset($error)){
            $gateway_id=$subscribe_request['gateway_id'];
            $check=$ssl->payment_check($gateway_id,$jArray);
            $jArray[fl()]=$check;
            if($check['status']==1){
                $start=strtotime('today');
                
                $customer_last_subscribe=$db->get_row('customer_subscribe',"where customer_id=$subscribe_request[customer_id] and end_date>$start order by end_date desc");
                if(!empty($customer_last_subscribe)){
                    $last_date=date('d-m-Y',$customer_last_subscribe['end_date']);
                    $last_date=strtotime($last_date);
                    $start=strtotime('+1 day',$last_date);
                }
                $end=strtotime('+30 day',$start);
                $data=[
                    'request_id'    => $request_id,
                    'customer_id'   => $subscribe_request['customer_id'],
                    'amount'        => $subscribe_request['amount'],
                    'start_date'    => $start,
                    'end_date'      => $end,
                    'created_on'    => TIME
                ];
                try{
                $insert=$db->insert('customer_subscribe',$data);
                if($insert){
                    $customer=$db->get_row('customers','customer_id',$subscribe_request['customer_id']);
                    $jArray[fl()]=1;
                    $data=[
                        'is_paid'=>1,
                        'pay_time'=>TIME
                    ];
                    $update=$db->update('subscribe_request',$data,['id'=>$request_id]);
                    if($update){
                        $jArray[fl()]=1;
                    }
                    else{
                        $error=fl();
                        $jArray[fl()]=1;
                    }
                }
                else{
                    $error=fl();
                    $jArray[fl()]=1;
                }
            }
            catch(Exception $e){
                $jArray[fl()]=$e->getCode();
                $jArray[fl()]=$e->getMessage();
            }
            }
            
        }
    }
}
create_log('ssl_response',$jArray);
$link=URL."?bil-history=1";
if(isset($customer)){
    $link.="&customer_code=$customer[customer_code]";
}
redirect($link);