<?php
require_once '../config/conn.php';
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// Authenticate request
session_start();
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$input = json_decode(file_get_contents('php://input'), true);
$reference = $input['reference'];
$gateway = $input['gateway'];

// Initialize cURL for Paystack verification
if ($gateway === 'paystack') {
    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://api.paystack.co/transaction/verify/" . rawurlencode($reference),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "accept: application/json",
            "authorization: Bearer sk_test_e961ecf6ab503d4b5d63853a2dfc0c9ec6ac78e6", // Replace with your actual secret key
            "cache-control: no-cache"
        ],
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) {
        echo json_encode(['success' => false, 'message' => 'cURL Error: ' . $err]);
        exit();
    }

    $result = json_decode($response, true);

    if (!$result['status']) {
        echo json_encode(['success' => false, 'message' => 'Paystack API Error: ' . ($result['message'] ?? 'Unknown error')]);
        exit();
    }

    $amount = $result['data']['amount'] / 100; // Convert to Naira
    $status = $result['data']['status'];
} 
// Add other payment gateways as needed
else {
    echo json_encode(['success' => false, 'message' => 'Unsupported payment gateway']);
    exit();
}

if ($status !== 'success') {
    echo json_encode(['success' => false, 'message' => 'Payment not successful']);
    exit();
}

try {
    $student_id = $_SESSION['user_id'];
    
    $conn->begin_transaction();
    
    // Get wallet ID
    $wallet_stmt = $conn->prepare("SELECT id FROM student_wallets WHERE student_id = ?");
    $wallet_stmt->bind_param("i", $student_id);
    $wallet_stmt->execute();
    $wallet_result = $wallet_stmt->get_result();
    $wallet = $wallet_result->fetch_assoc();
    
    if (!$wallet) {
        throw new Exception("Wallet not found");
    }
    
    // Update wallet balance - using POSITIVE amount for deposit
    $update_stmt = $conn->prepare("UPDATE student_wallets SET balance = balance + ? WHERE student_id = ?");
    $update_stmt->bind_param("di", $amount, $student_id);
    $update_stmt->execute();
    
    if ($update_stmt->affected_rows === 0) {
        throw new Exception("Failed to update wallet balance");
    }
    
    // Create transaction record - using 'credit' type for deposit
    $txn_stmt = $conn->prepare("INSERT INTO wallet_transactions 
        (student_id, wallet_id, amount, transaction_type, reference, status, description, gateway) 
        VALUES (?, ?, ?, 'credit', ?, 'completed', 'Wallet deposit', ?)");
    $txn_stmt->bind_param("iidss", $student_id, $wallet['id'], $amount, $reference, $gateway);
    $txn_stmt->execute();
    
    $conn->commit();
    
    echo json_encode([
        'success' => true, 
        'message' => 'Payment verified and wallet credited successfully',
        'amount' => $amount,
        'new_balance' => getWalletBalance($conn, $student_id) // Helper function to get updated balance
    ]);
} catch (Exception $e) {
    $conn->rollback();
    error_log("Payment verification error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}

// Helper function to get current wallet balance
function getWalletBalance($conn, $student_id) {
    $stmt = $conn->prepare("SELECT balance FROM student_wallets WHERE student_id = ?");
    $stmt->bind_param("i", $student_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $wallet = $result->fetch_assoc();
    return $wallet ? $wallet['balance'] : 0;
}
?>