<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Constants
define('API_KEY', '76d2ea13-10e0-48e7-8e0e-7261bac5ced7');
define('API_SECRET', '0b15eb80a64d3528cbfc6cd76889b7e71af204aa');
define('BASE_URL', 'https://tumeny.herokuapp.com');

// Function to get the authentication token
function getAuthToken(): string {
    $ch = curl_init(BASE_URL . "/api/token");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'apiKey: ' . API_KEY,
        'apiSecret: ' . API_SECRET,
    ]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) {
        error_log("Token Error: $error");
        $_SESSION['payment_error'] = "Authentication failed.";
        return '';
    }

    $responseData = json_decode($response, true);
    if (isset($responseData['error'])) {
        $_SESSION['payment_error'] = "Authentication failed.";
        error_log("API Response Error: " . json_encode($responseData));
        return '';
    }

    return $responseData['token'] ?? '';
}

// Function to create a payment
function createPayment($authToken, $paymentData) {
    $ch = curl_init(BASE_URL . "/api/v1/payment");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $authToken,
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($paymentData));

    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) {
        error_log("Payment Error: $error");
        return ['error' => true];
    }

    return json_decode($response, true);
}

// Function to check payment status
function checkPaymentStatus($authToken, $paymentId) {
    $ch = curl_init(BASE_URL . "/api/v1/payment/$paymentId");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $authToken
    ]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) {
        error_log("Payment Status Error: $error");
        return ['error' => true];
    }

    return json_decode($response, true);
}

// Function to retry checking payment status
function getPaymentStatusWithRetry($authToken, $paymentId, $maxRetries = 10) {
    $retries = 0;
    while ($retries < $maxRetries) {
        $paymentStatus = checkPaymentStatus($authToken, $paymentId);
        error_log("Retry #$retries - Payment Status: " . json_encode($paymentStatus));

        if (isset($paymentStatus['payment']['status'])) {
            switch ($paymentStatus['payment']['status']) {
                case 'success':
                    $_SESSION['payment_success'] = true;
                    header('Location: success.php');
                    session_write_close();
                    exit;
                case 'failed':
                    $_SESSION['payment_error'] = "Payment failed.";
                    return false;
                case 'pending':
                    sleep(3);
                    $retries++;
                    continue 2;
                default:
                    $_SESSION['payment_error'] = "Unexpected payment status.";
                    return false;
            }
        }

        $retries++;
        sleep(3);
    }

    $_SESSION['payment_error'] = "Payment timed out.";
    return false;
}

// Handle POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $authToken = getAuthToken();

    if (!$authToken) {
        $_SESSION['payment_error'] = "Payment failed.";
    } else {
        $paymentData = [
            'description' => $_POST['description'],
            'customerFirstName' => htmlspecialchars(strip_tags(trim($_POST['firstName']))),
            'customerLastName' => htmlspecialchars(strip_tags(trim($_POST['lastName']))),
            'email' => filter_var($_POST['email'], FILTER_SANITIZE_EMAIL),
            'phoneNumber' => htmlspecialchars(strip_tags(trim($_POST['phone']))),
            'amount' => (int)$_POST['amount']
        ];

        $paymentResponse = createPayment($authToken, $paymentData);

        if (isset($paymentResponse['payment']['id'])) {
            $paymentId = $paymentResponse['payment']['id'];
            getPaymentStatusWithRetry($authToken, $paymentId);
        } else {
            $_SESSION['payment_error'] = "Payment creation failed.";
            error_log("Payment Response Error: " . json_encode($paymentResponse));
        }
    }
}

// Clear success flag if it exists
if (isset($_SESSION['payment_success'])) {
    unset($_SESSION['payment_success']);
}
?>
