<?php
if(isset($_POST['pay']))
{
    $_SESSION['customerid'] = $_POST[CUSTOMER_UNIQUE_FIELD_CODE];
    $_SESSION['packageid'] = $_POST[PACKAGE_FIELD_CODE];       
    $_SESSION['tranactionreference'] = $_SESSION['businesscode'].date('d').date('N').date('m').microtime().$randomno;
    if(isset($_POST[EMAIL_FIELD_CODE]))
    {
        $email = $_POST[EMAIL_FIELD_CODE];
    }
    else if(isset($_POST['customername']))
    {
        $email = $_POST['customername']; 
    }
    else 
    {
        $email = $businessemail;
    }
    $_SESSION['customername'] = isset($_POST['customername']) ? $_POST['customername'] : $email;
    $_SESSION['customeremail'] = $email;
    $amountkobo = 0;
    if($_POST[AMOUNT_FIELD_CODE] > 0)
    {
        $amountkobo = $_POST[AMOUNT_FIELD_CODE] * 100;
    }
    
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    
    curl_setopt_array($curl, array(
      CURLOPT_URL => "https://api.paystack.co/transaction/initialize",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => json_encode([
        'amount'=>$amountkobo,
        'email'=>$_POST[EMAIL_FIELD_CODE],
        'subaccount'=>$_POST['subacctcode'],
        'callback_url'=>CALLBACK_URL
      ]),
      CURLOPT_HTTPHEADER => [
        "authorization: Bearer ".SECRET_KEY,
        "content-type: application/json",
        "cache-control: no-cache"
      ],
    ));
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    if($err){
      // there was an error contacting the Paystack API
      die('Curl returned error: ' . $err);
    }
    
    $tranx = json_decode($response);
    
    if(!$tranx->status){
      // there was an error from the API
      die('API returned error: ' . $tranx->message);
    }
    
    // store transaction reference so we can query in case user never comes back
    // perhaps due to network issue
    //save_last_transaction_reference($tranx->data->reference);
    
    // redirect to page so User can pay
     //header('Location: ' . $tranx->data->authorization_url);
     echo '<script>window.location="'.$tranx->data->authorization_url.'"</script>';
}
?>