<?php
session_start();
ob_start();
include_once "./bkashconfig.php";
require_once '../../config.php'; // Include main config that has $pdo

if(!isset($_GET['paymentID']) || empty($_GET['paymentID']) ){
    $_SESSION['Error'] = "ভুল রিকুয়েস্ট।";
    header("Location: ../../recharge.php?statusMessage=error&id=0");
    die();
}

// Check if user is logged in
if(!isset($_SESSION['user_id'])) {
    $_SESSION['Error'] = "লগইন সেশন শেষ হয়েছে। আবার লগইন করুন।";
    header("Location: ../../recharge.php?statusMessage=error&id=5");
    die();
}

$curl = curl_init();

$data = json_encode([
    "paymentID" => $_GET['paymentID'],
]);

curl_setopt_array($curl, [
    CURLOPT_URL => BASEURL . "/tokenized/checkout/execute",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => $data,
    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) {
    $_SESSION['Error'] = "Payment execution error: " . $err;
    header("Location: ../../recharge.php?statusMessage=error&id=1");
    die();
} else {
    $response = json_decode($response);
    
    // Debug logging
    error_log("bKash Execute Response: " . print_r($response, true));
    error_log("User ID: " . $_SESSION['user_id']);
    
    // Validate payment response
    if(!isset($response->statusMessage) || !isset($response->transactionStatus)) {
        $_SESSION['Error'] = "অবৈধ পেমেন্ট রেসপন্স।";
        header("Location: ../../recharge.php?statusMessage=error&id=2");
        die();
    }
    
    if($response->statusMessage !== 'Successful' || $response->transactionStatus !== 'Completed'){
        $_SESSION['Error'] = "পেমেন্ট হয়নি। Status: " . $response->statusMessage;
        header("Location: ../../recharge.php?statusMessage=error&id=3");
        die();
    }
    
    // Payment is successful, update database
    if($response->statusMessage === 'Successful' && $response->transactionStatus === 'Completed'){
        try {
            $user_id = $_SESSION['user_id'];
            $amount = $response->amount;
            $payment_id = $response->paymentID;
            
            // Start transaction
            $pdo->beginTransaction();
            
            // 1. Update user balance
            $stmt = $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
            $stmt->execute([$amount, $user_id]);
            
            // Check if balance was updated
            if($stmt->rowCount() == 0) {
                throw new Exception("ব্যবহারকারী পাওয়া যায়নি বা ব্যালেন্স আপডেট হয়নি");
            }
            
            // 2. Record transaction in recharges table
            $stmt = $pdo->prepare("INSERT INTO recharges (user_id, amount, txn_id, status) VALUES (?, ?, ?, 'completed')");
            $stmt->execute([$user_id, $amount, $payment_id]);
            
            // Commit transaction
            $pdo->commit();
            
            // Log success
            error_log("Payment successful: User $user_id recharged $amount Taka");
            
            $_SESSION['Success'] = $amount . " টাকা সফলভাবে রিচার্জ হয়েছে।";
            header("Location: ../../recharge.php?statusMessage=success");
            die();
            
        } catch (Exception $e) {
            // Rollback transaction on error
            $pdo->rollBack();
            
            error_log("Database error in execute-payment: " . $e->getMessage());
            $_SESSION['Error'] = "ডাটাবেস আপডেটে সমস্যা: " . $e->getMessage();
            header("Location: ../../recharge.php?statusMessage=error&id=4");
            die();
        }
    }
}
?>