<?php
session_start();
require_once '../../config.php';
include_once "./bkashconfig.php";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        http_response_code(403);
        echo "Invalid CSRF token";
        exit;
    }
    
    $amount = floatval($_POST['amount']);
    $user_id = $_SESSION['user_id'];
    
    // Validate amount
    if ($amount < 1) {
        echo "সর্বনিম্ন 100 টাকা রিচার্জ করুন";
        exit;
    }
    
    // Get user details
    $stmt = $pdo->prepare("SELECT id, email, name FROM users WHERE id=?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();
    
    if (!$user) {
        echo "User not found";
        exit;
    }
    
    // Check if bKash token exists, if not try to generate one
    if (!isset($_SESSION['id_token']) || empty($_SESSION['id_token'])) {
        echo "bKash token not available. Please refresh the page.";
        exit;
    }
    
    // Generate unique invoice number
    $invoice_no = "INV" . time() . rand(1000, 9999);
    
    // Prepare request body for bKash
    $requestbody = array(
        'mode'                  => '0011',
        'amount'                => (string)$amount,
        'currency'              => 'BDT',
        'intent'                => 'sale',
        'payerReference'        => substr($user['email'], 0, 50), // bKash has character limits
        'merchantInvoiceNumber' => $invoice_no,
        'callbackURL'           => CALLBACK,
    );
    
    $curl = curl_init();
    
    curl_setopt_array($curl, [
        CURLOPT_URL => BASEURL."/tokenized/checkout/create",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => json_encode($requestbody),
        CURLOPT_HTTPHEADER => [
            "Authorization: ". $_SESSION['id_token'],
            "X-APP-Key: ". APPKEY,
            "accept: application/json",
            "content-type: application/json"
        ],
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    
    if ($err) {
        echo "Connection Error: " . $err;
    } else {
        $result = json_decode($response);
        
        if (isset($result->bkashURL) && !empty($result->bkashURL)) {
            // Store payment details temporarily in session
            $_SESSION['pending_payment'] = [
                'amount' => $amount,
                'invoice_no' => $invoice_no,
                'user_id' => $user_id,
                'payment_id' => $result->paymentID ?? ''
            ];
            
            // Return the payment URL directly
            echo $result->bkashURL;
        } else {
            // Handle bKash API errors
            $error_message = "Payment creation failed";
            
            if (isset($result->statusMessage)) {
                $error_message .= ": " . $result->statusMessage;
            }
            if (isset($result->errorMessage)) {
                $error_message .= " - " . $result->errorMessage;
            }
            if (isset($result->message)) {
                $error_message .= " - " . $result->message;
            }
            
            // If token is invalid, clear it so it can be regenerated
            if (isset($result->statusCode) && $result->statusCode == '401') {
                $_SESSION['id_token'] = null;
                $error_message .= " (Token expired)";
            }
            
            echo $error_message;
        }
    }
} else {
    echo "Invalid request method";
}
?>