<?php
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Authorization, Content-Type, Accept');

require_once "../database.php"; // Make sure this file sets $conn

// Only POST is allowed
if ($_SERVER["REQUEST_METHOD"] !== 'POST') {
    http_response_code(400);
    echo json_encode(["status" => "fail", "msg" => "Only POST method is allowed"]);
    exit;
}

// Read Headers
$headers = getallheaders();
$authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? $headers['Token'] ?? $headers['token'] ?? null;

if (!$authHeader) {
    http_response_code(401);
    echo json_encode(["status" => "fail", "msg" => "Authorization token is required."]);
    exit;
}

$token = trim(str_replace("Token", "", $authHeader));

// Validate token from DB
try {
    $stmt = $conn->prepare("SELECT name, email FROM users WHERE token = :token LIMIT 1");
    $stmt->execute(['token' => $token]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        http_response_code(401);
        echo json_encode(["status" => "fail", "msg" => "Invalid authorization token."]);
        exit;
    }

    // Extract user data
    $customerName = $user["name"] ?? '';
    $customerEmail = $user["email"];

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(["status" => "fail", "msg" => "Database error: " . $e->getMessage()]);
    exit;
}

// Get amount from request body
$input = json_decode(file_get_contents("php://input"), true);
if (!isset($input['amount'])) {
    http_response_code(400);
    echo json_encode(["error" => "Missing required field: amount"]);
    exit;
}

$amount = floatval($input['amount']);

// === CONFIGURATION ===
$apiKey = 'MK_PROD_YU6AWBHUCK';
$clientSecret = 'QNP6Q55DFTVX76BNS7G4A7WQWY52WKPC';
$contractCode = '904128982252';
$baseUrl = 'https://api.monnify.com';
$currencyCode = 'NGN';
$redirectUrl = 'https://yourdomain.com/payment-success';
$bankCode = '058'; // e.g. GTBank
$paymentReference = uniqid('txn_', true);

// === STEP 1: AUTHENTICATE WITH MONNIFY ===
$authHeaders = [
    "Content-Type: application/json",
    "Authorization: Basic " . base64_encode("$apiKey:$clientSecret")
];

$authCh = curl_init("$baseUrl/api/v1/auth/login");
curl_setopt($authCh, CURLOPT_RETURNTRANSFER, true);
curl_setopt($authCh, CURLOPT_HTTPHEADER, $authHeaders);
curl_setopt($authCh, CURLOPT_POST, true);
curl_setopt($authCh, CURLOPT_POSTFIELDS, '{}');

$authResponse = json_decode(curl_exec($authCh), true);
curl_close($authCh);

if (!$authResponse['requestSuccessful']) {
    http_response_code(500);
    echo json_encode(["error" => "Auth failed", "message" => $authResponse['responseMessage']]);
    exit;
}

$accessToken = $authResponse['responseBody']['accessToken'];

// === STEP 2: INITIALIZE TRANSACTION ===
$initHeaders = [
    "Content-Type: application/json",
    "Authorization: Bearer $accessToken"
];

$initPayload = json_encode([
    "amount" => $amount,
    "customerName" => $customerName,
    "customerEmail" => $customerEmail,
    "paymentReference" => $paymentReference,
    "paymentDescription" => "Monnify API Payment",
    "currencyCode" => $currencyCode,
    "contractCode" => $contractCode,
    "redirectUrl" => $redirectUrl,
    "paymentMethods" => ["CARD", "ACCOUNT_TRANSFER"]
]);

$initCh = curl_init("$baseUrl/api/v1/merchant/transactions/init-transaction");
curl_setopt($initCh, CURLOPT_RETURNTRANSFER, true);
curl_setopt($initCh, CURLOPT_HTTPHEADER, $initHeaders);
curl_setopt($initCh, CURLOPT_POST, true);
curl_setopt($initCh, CURLOPT_POSTFIELDS, $initPayload);

$initResponse = json_decode(curl_exec($initCh), true);
curl_close($initCh);

if (!$initResponse['requestSuccessful']) {
    http_response_code(500);
    echo json_encode(["error" => "Transaction init failed", "message" => $initResponse['responseMessage']]);
    exit;
}

$transactionReference = $initResponse['responseBody']['transactionReference'];

// === STEP 3: GENERATE VIRTUAL ACCOUNT ===
$acctPayload = json_encode([
    "transactionReference" => $transactionReference,
    "bankCode" => $bankCode
]);

$acctCh = curl_init("$baseUrl/api/v1/merchant/bank-transfer/init-payment");
curl_setopt($acctCh, CURLOPT_RETURNTRANSFER, true);
curl_setopt($acctCh, CURLOPT_HTTPHEADER, $initHeaders);
curl_setopt($acctCh, CURLOPT_POST, true);
curl_setopt($acctCh, CURLOPT_POSTFIELDS, $acctPayload);

$acctResponse = json_decode(curl_exec($acctCh), true);
curl_close($acctCh);

if (!$acctResponse['requestSuccessful']) {
    http_response_code(500);
    echo json_encode(["error" => "Virtual account generation failed", "message" => $acctResponse['responseMessage']]);
    exit;
}

// === FINAL RESPONSE ===
echo json_encode([
    "success" => true,
    "paymentDetails" => $acctResponse['responseBody'],
    "checkoutUrl" => $initResponse['responseBody']['checkoutUrl']
]);

?>