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

// Only allow POST method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(["error" => "Method Not Allowed"]);
    exit();
}

require_once("../database.php"); // Ensure $conn = new PDO(...)

// === Get Headers and Body ===
$headers = getallheaders();
$input = file_get_contents("php://input");
$res = json_decode($input, true);

$logData = [
    'headers' => $headers,
    'body' => $res,
];
file_put_contents("shshs.txt", json_encode($logData, JSON_PRETTY_PRINT));


// Validate payload
if (!is_array($res)) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid payload"]);
    exit();
}

// Compute Monnify Signature
function computeMonnifyHash($stringifiedData, $clientSecret) {
    return hash_hmac('sha512', $stringifiedData, $clientSecret);
}

$monifySecret = "QNP6Q55DFTVX76BNS7G4A7WQWY52WKPC";
$receivedSignature = $headers["Monnify-Signature"] ?? $headers["monnify-signature"] ?? '';
$generatedSignature = computeMonnifyHash($input, $monifySecret);

// Check signature
if ($receivedSignature !== $generatedSignature) {
    http_response_code(401);
    echo json_encode(["error" => "Unauthorized - Signature mismatch"]);
    exit();
}


// Extract transaction data
$eventData = $res["eventData"];
$eventType = $res["eventType"] ?? "";
$amountPaid = $eventData["amountPaid"] ?? 0;
$transactionReference = $eventData["transactionReference"] ?? "";
$paymentStatus = $eventData["paymentStatus"] ?? "";
$email = $eventData["customer"]["email"] ?? "";

// Lookup user by email
$stmt = $conn->prepare("SELECT id, name, email, phone, balance FROM users WHERE email = :email LIMIT 1");
$stmt->execute(['email' => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    http_response_code(403);
    echo json_encode(["error" => "User not found"]);
    exit();
}

$userid = $user["id"];
$userbalance = (float) $user["balance"];
$charges = 2; // flat fee, update if needed

if ($eventType === "SUCCESSFUL_TRANSACTION" && $paymentStatus === "PAID") {
    $amountToCredit = $amountPaid - $charges;

    $description = "Wallet funding of ₦{$amountPaid} with ₦{$charges} service charge. Wallet credited with ₦{$amountToCredit}.";

    // Record transaction
    $insert = $conn->prepare("INSERT INTO transactions (user_id, amount, description, reference, status) VALUES (?, ?, ?, ?, ?)");
    $insert->execute([$userid, $amountToCredit, $description, $transactionReference, "success"]);

    // Update wallet balance
    $newBalance = $userbalance + $amountToCredit;
    $update = $conn->prepare("UPDATE users SET balance = ? WHERE id = ?");
    $update->execute([$newBalance, $userid]);

    // Send notification email
    $mailPayload = json_encode([
        "to" => $email,
        "subject" => "Wallet Topup Successful",
        "message" => $description . "\nReference: " . $transactionReference,
    ]);

    $ch = curl_init("https://schoolmata.com.ng/mobile/api/mail/send_mail.php");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $mailPayload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Content-Length: ' . strlen($mailPayload)
    ]);
    curl_exec($ch);
    curl_close($ch);

    echo json_encode(["status" => "success", "message" => "Wallet credited"]);
    http_response_code(200);
    exit();
}

// Record failed transaction
$failMsg = "Failed wallet funding of ₦{$amountPaid}.";
$insert = $conn->prepare("INSERT INTO transactions (user_id, amount, description, reference, status) VALUES (?, ?, ?, ?, ?)");
$insert->execute([$userid, $amountPaid, $failMsg, $transactionReference, "failed"]);

echo json_encode(["status" => "fail", "message" => $failMsg]);
http_response_code(400);
exit();
?>
