<?php
include('paystack/config.php');
  // only a post with paystack signature header gets our attention
  if ((strtoupper($_SERVER['REQUEST_METHOD']) != 'POST' ) || !array_key_exists('HTTP_X_PAYSTACK_SIGNATURE', $_SERVER) )
      exit();

  // Retrieve the request's body
  $input = @file_get_contents("php://input");
  define('PAYSTACK_SECRET_KEY',$secret_key);

  // validate event do all at once to avoid timing attack
  if($_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] !== hash_hmac('sha512', $input, $secret_key))
      exit();

  http_response_code(200);
  
 
  $event = json_decode($input);
  
 // print_r($event);
  
  if($event){
  foreach($event as $evt){
      
      if($evt == "charge.success"){
          if($evt['data']['status'] = "success"){
         
         $paystack_id = $evt['data']['id'];
         
         $transaction_exist =  $db_handle->runBaseQuery("SELECT * FROM savings WHERE paystack_transaction_id = '$paystack_id'");

if($transaction_exist){
    if($transaction[0]['status'] != "success"){
    $db_handle->update("UPDATE savings SET status = ? WHERE paystack_transaction_id = ?","ss",array("success",$paystack_id));
      }
}else{
    
    $paystack_transaction_id = $evt['data']['id'];
    $refID = $evt['data']['id'];
    $userID = $evt['data']['userID'];
    $date = date("d-m-Y h:i:sa");
    $amount = $evt['data']['amount'];
    $status = $evt['data']['status'];
        
        
        
       $insert = $db_handle->insertRecord("INSERT INTO savings(userID, transactionID,paystack_reference_id,paystack_transaction_id,amount,method,date,status) VALUES (?,?,?,?,?,?,?,?)","issssssi",array($userID,$t_id,$refID,$paystack_transaction_id,$amount,"PAYSTACK",$date,$status));
       
       if($insert){
           header("location: dashboard.php?page=dashboard");
       }
}
      
 }


}
}

}
  exit();
?>