<?php
session_start();
header('Content-Type: application/json');
if (!isset($_SESSION['admin_id']) && $_SESSION['role'] != 'admin') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}
include '../../../include/config.php';
include '../../../include/Flutterwave.php';

$tx_ref = $_GET['ref'] ?? '';

if (!$tx_ref) {
    echo json_encode(['success' => false, 'message' => 'No reference provided']);
    exit();
}

$flutterwave = new Flutterwave();
$verification = $flutterwave->verifyPayment($tx_ref);

if ($verification['success']) {
    $data = $verification['data'];
    $conn->query("UPDATE payments SET status = 'successful', payment_data = '" . json_encode($data) . "', completed_at = NOW() WHERE transaction_id = '$tx_ref'");
    echo json_encode(['success' => true, 'message' => 'Payment verified']);
} else {
    echo json_encode(['success' => false, 'message' => $verification['message']]);
}
?>