<?php
require_once('../vendor/autoload.php');
require_once('../main_includes/init.php');

// $secret_key = 'FLWSECK-2ade3da9213bc244d50dca7eb604f191-189f60815f1vt-X';
$secret_key = ENVIRONMENT == 'prod'? 'FLWSECK-2ade3da9213bc244d50dca7eb604f191-189f60815f1vt-X': "FLWSECK_TEST-8d2b3d8d7dd3e172d8a2e044e1edf15d-X";
// $secret_key = 'FLWSECK_TEST-8d2b3d8d7dd3e172d8a2e044e1edf15d-X';
$public_key = 'FLWPUBK_TEST-208ead3734530317ca1cc3cb74fe4b1f-X';

$client = new \GuzzleHttp\Client();

function generate_reference()
{
    $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $nums = '0123456789';
    $nums_length = strlen($nums);
    $reference = '';
    for ($i = 0; $i < 12; $i++) {

        $reference .= $nums[rand(0, $nums_length - 1)];
    }
    for ($i = 0; $i < 2; $i++) {

        $reference .= $characters[rand(0, $charactersLength - 1)];
    }
    for ($i = 0; $i < 3; $i++) {

        $reference .= $nums[rand(0, $nums_length - 1)];
    }
    return $reference;
}


if (isset($_SESSION['user_id']) && $_SESSION['user_id'] != "") {
// if (isset($_POST['transaction_id'], $_SESSION['user_id']) && $_SESSION['user_id'] != "") {

    extract($_POST);

    $my_transaction = MyTransaction::find_by_id($transaction_id);
    $amount = $my_transaction->amount;

    if (intval($amount) < 500) {
        redirect(ROOT_URL);
        return false;
    }

    $user = User::find_by_id($_SESSION['user_id']);
    if (!$user) {
        header("Location: ".ROOT_URL);
    }
   
    // $reference = generate_reference();

    $payment_data = array(
        'amount' => $amount,
        'currency' => 'NGN',
        'tx_ref' => $my_transaction->reference,
        'payment_options' => 'card',
        'redirect_url' => ROOT_URL."/payment/flutterwave_callback.php?sasd=$_SESSION[user_id]",
        'customer' => array(
            'email' => $user->email,
            'name' => $user->first_name . " ". $user->last_name,
        ),
    );
    try {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api.flutterwave.com/v3/payments');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payment_data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Authorization: Bearer ' . $secret_key,
        ));
        $response = curl_exec($ch);
        // print_r($response);
        curl_close($ch);
    } catch (\Throwable $th) {
        header("Location: ".ROOT_URL);
    }



    if ($response) {
        $response_data = json_decode($response, true);
        if ($response_data && $response_data['status'] === 'success') {
            
            $payment_url = $response_data['data']['link'];

            curl_close($ch);

            header('Location: ' . $payment_url);
            exit();
        } else {
            // Handle error
            // print_r($response_data);
            // echo 'Payment initialization failed: ' . $response_data['message'];
            echo 'Payment initialization failed: ';
            // redirect("../user/billing");

        }
    } else {
        // Handle error
        echo 'Failed to communicate with the payment gateway.';
        // redirect("../user/billing");

    }


} else {
    header("Location: ".ROOT_URL);
}
