<?php
session_start();
require_once "../SystemController/DbConnection.php";
include('paystack/config.php');
if(!isset($_SESSION['id'])){
    header("Location: ../login.php");
}

$id = $_SESSION['id'];

$msg = "";


$db_handle = new Dbconnection();
$user = $db_handle->runBaseQuery("SELECT * FROM users WHERE id = $id ");
$fname = $user[0]['first_name'];
$surname = $user[0]['surname'];
$email = $user[0]['email'];

$t_id = "OVOH".mt_rand(10000,99999);

if(!isset($_GET['reference'])){
    
    header("location: dashboard.php");
}else{
    
    $refID = $_GET['reference'];
    

    
 
  $curl = curl_init();
  
  
  curl_setopt_array($curl, array(
    CURLOPT_URL => "https://api.paystack.co/transaction/verify/$refID",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
      "Authorization: Bearer $secret_key",
      "Cache-Control: no-cache",
    ),
  ));
  
  $response = curl_exec($curl);
  $err = curl_error($curl);

  curl_close($curl);
  
  if ($err) {
    echo "cURL Error #:" . $err;
  } else {
    $data =  json_decode($response);
    $paystack_transaction_id = $data->data->id;
    $date = date("d-m-Y h:i:sa");
    $amount = $data->data->amount;
    
    if($data->data->status = true){
        $status = $data->data->status;
        
        $transaction_exist = $db_handle->runBaseQuery("SELECT * FROM savings WHERE paystack_reference_id = '$refID' AND paystack_transaction_id = '$paystack_transaction_id'");
        
        if(!$transaction_exist){
        
       $insert = $db_handle->insertRecord("INSERT INTO savings(userID, transactionID,paystack_reference_id,paystack_transaction_id,amount,method,date,status) VALUES (?,?,?,?,?,?,?,?)","issssssi",array($id,$t_id,$refID,$paystack_transaction_id,$amount,"PAYSTACK",$date,$status));
       
       if($insert){
           header("location: dashboard.php?page=dashboard");
       }
    }
  }
  }
}
?>