<?php
session_start();
$userlogin=$_SESSION['organization'];
$district=$_SESSION['district'];
$email=$_SESSION['email'];
include "include/config.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']);
}
?>

<?php
$query = mysqli_query($conn, "SELECT * FROM ufez_pay WHERE organization='$userlogin'");

if (mysqli_num_rows($query) > 0) {
    while ($row = mysqli_fetch_array($query)) {?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>UFEZ - Payment</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300&family=Source+Sans+Pro:wght@300&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <style>
        body { 
            background-color: #f8f9fa;
            font-family: 'Montserrat', sans-serif;
        }
        .payment-card {
            max-width: 500px;
            margin: 2rem auto;
            padding: 2rem;
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
        }
        .logo-container {
            text-align: center;
            margin-bottom: 2rem;
        }
        .btn-payment {
            background: #54B68F;
            color: white;
            width: 100%;
            padding: 10px;
            border: none;
            border-radius: 5px;
            margin-top: 1rem;
        }
        .btn-payment:hover {
            background: #469e7a;
            color: white;
        }
        .form-control {
            margin-bottom: 1rem;
        }
        .alert {
            margin-bottom: 1rem;
        }
        .payment-methods {
            text-align: center;
            margin: 1rem 0;
        }
        .loading {
            display: none;
            text-align: center;
            margin: 1rem 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="payment-card">
            <div class="logo-container">
                <img src="logo1.png" alt="logo" width="100">
            </div>
            
            <?php if (isset($_SESSION['payment_error'])): ?>
                <div class="alert alert-danger">
                    <?php 
                    echo $_SESSION['payment_error'];
                    unset($_SESSION['payment_error']);
                    ?>
                </div>
            <?php endif; ?>

            <h2 class="text-center mb-4">Make Payment</h2>
            
            <form id="paymentForm" action="" method="POST">
                <div class="mb-3">
                            <?php
$query=mysqli_query($conn, "select *from ufez_pay where organization='$userlogin'");
 while($row=mysqli_fetch_array($query)){?>


                    <label for="subscriptionType" class="form-label">Payment Type:</label>
             
                    <select class="form-control" id="subscriptionType" name="amount" onchange="updatePrice()" required>
    <?php 
    $id = $_GET['id'];
    if ($id == "payment") { ?>
        <option value="<?php echo $row['membership_fee']; ?>">
            <?php echo $row['membership_fee']; ?> - Membership
        </option>
    <?php } else { ?>
        <option value="<?php echo $row['subscription_fee']; ?>">
            <?php echo $row['subscription_fee']; ?> - Subscription
        </option>
    <?php } ?>
</select>
                        
                        
                        
                        
                        
                        
                       
                    </select>
                    
                    <?php
 }
                     ?>
                </div>

                <div class="mb-3" hidden>
                    <label for="firstName" class="form-label">Organization:</label>
                    <input class="form-control" type="text" id="firstName" name="firstName"  value="<?php echo isset($userlogin) ? $userlogin : ''; ?>" readonly>
                </div>

                <div class="mb-3" hidden>
                    <label for="lastName" class="form-label">District:</label>
                    <input class="form-control" type="text" id="lastName" name="lastName"  value="<?php echo isset($district) ? $district : ''; ?>" readonly>
                </div>

                <div class="mb-3" hidden>
                    <label for="email" class="form-label">Email:</label>
                    <input class="form-control" type="email" id="email" name="email"  value="<?php echo isset($email) ? $email : ''; ?>" readonly>
                </div>

                <div class="mb-3">
                    <label for="phone" class="form-label">Mobile Money Number:</label>
                    <input class="form-control" type="text" id="phone" name="phone" required placeholder="09******23">
                </div>

                <div class="payment-methods">
                    <img src="money.png" alt="Payment methods" class="img-fluid" style="max-width: 200px">
                </div>

                <input type="hidden" id="description" name="description" value=" Ufez subscription fee">
                

                <button type="submit" class="btn btn-payment">
                    <i class="fa fa-credit-card"></i> PAY NOW
                </button>
            </form>

            <div id="loading" class="loading">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-2">Processing payment...</p>
            </div>
        </div>
    </div>

    <script>
        

        document.getElementById('paymentForm').addEventListener('submit', function() {
            document.getElementById('loading').style.display = 'block';
            this.querySelector('button[type="submit"]').disabled = true;
        });
    </script>
</body>
</html>
<?php
}
} else {
    header("Location:staff/dashboard.php?payid=No PayID found. Please create one first.");
}
?>