<?php
header("Content-Type: application/json");
require_once 'db.php';
$config = include('payment_point_config.php');

$user_id = $_POST['user_id'] ?? '';
if (empty($user_id)) {
    echo json_encode(['status' => 'error', 'message' => 'Missing user_id']);
    exit;
}

// Fetch user info
$stmt = $conn->prepare("SELECT first_name, email, phone FROM users WHERE id = ?");
$stmt->bind_param("s", $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(['status' => 'error', 'message' => 'User not found']);
    exit;
}

$user = $result->fetch_assoc();
$first_name = $user['first_name'];
$email = $user['email'];
$phone = $user['phone'];

// Bank code for Palmpay only
$bank_codes = ['20946']; // Palmpay only

// Prepare API request
$headers = [
    'Authorization: Bearer ' . $config['secret_key'],
    'api-key: ' . $config['api_key'],
    'Content-Type: application/json',
];

$apiBody = [
    'email' => $email,
    'name' => $first_name,
    'phoneNumber' => $phone,
    'bankCode' => $bank_codes,
    'businessId' => $config['business_id'],
];

// Send to PaymentPoint
$ch = curl_init($config['api_url']);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($apiBody),
    CURLOPT_TIMEOUT => 30,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false,
]);

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
curl_close($ch);

// Handle API response
$result = json_decode($response, true);
if (in_array($http_code, [200, 201]) && isset($result['status']) && $result['status'] === 'success') {
    $bankAccounts = $result['bankAccounts'] ?? [];
    
    if (!empty($bankAccounts)) {
        $createdAccounts = [];
        
        foreach ($bankAccounts as $account) {
            $bank_code = $account['bankCode'] ?? '';
            $bank_name = $account['bankName'] ?? '';
            $account_number = $account['accountNumber'] ?? '';
            $account_name = $account['accountName'] ?? '';
            $Reserved_Account_Id = $account['Reserved_Account_Id'] ?? '';
            
            // Only process Palmpay accounts
            if ($bank_code === '20946') {
                $bank_id = 'PALMPAY';
                
                $reference = $Reserved_Account_Id;
                $created_at = date('Y-m-d H:i:s');
                $provider = 'paymentpoint';

                // Check if account already exists for this user and bank
                $checkStmt = $conn->prepare("SELECT id FROM virtual_accounts WHERE user_id = ? AND bank_id = ?");
                $checkStmt->bind_param("ss", $user_id, $bank_id);
                $checkStmt->execute();
                $checkResult = $checkStmt->get_result();
                
                if ($checkResult->num_rows === 0) {
                    // Insert new account
                    $stmt = $conn->prepare("INSERT INTO virtual_accounts 
                        (Reserved_Account_Id, user_id, bank_id, bank_name, account_number, account_name, reference, created_at, provider) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->bind_param("sisssssss", $Reserved_Account_Id, $user_id, $bank_id, $bank_name, $account_number, $account_name, $reference, $created_at, $provider);

                    if ($stmt->execute()) {
                        $createdAccounts[] = [
                            'account_number' => $account_number,
                            'account_name' => $account_name,
                            'bank_name' => $bank_name,
                            'bank_id' => $bank_id
                        ];
                    }
                    $stmt->close();
                } else {
                    // Account already exists, fetch and return it
                    $fetchStmt = $conn->prepare("SELECT account_number, account_name, bank_name, bank_id FROM virtual_accounts WHERE user_id = ? AND bank_id = ?");
                    $fetchStmt->bind_param("ss", $user_id, $bank_id);
                    $fetchStmt->execute();
                    $fetchResult = $fetchStmt->get_result();
                    if ($existingAccount = $fetchResult->fetch_assoc()) {
                        $createdAccounts[] = $existingAccount;
                    }
                    $fetchStmt->close();
                }
                $checkStmt->close();
            }
        }
        
        if (!empty($createdAccounts)) {
            echo json_encode([
                'status' => 'success',
                'message' => 'Palmpay virtual account processed successfully',
                'data' => $createdAccounts
            ]);
        } else {
            echo json_encode([
                'status' => 'success', 
                'message' => 'Palmpay account already exists',
                'data' => []
            ]);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'No account data received from API for Palmpay']);
    }
} else {
    $errorMessage = $result['message'] ?? 'Unknown API error for Palmpay';
    echo json_encode(['status' => 'error', 'message' => $errorMessage, 'curl_error' => $curl_error]);
}

$conn->close();
?>