<?php
require_once(__DIR__ . '/../config/config.php');
require_once(__DIR__ . '/../classes/Database.php');
require_once(__DIR__ . '/../classes/Auth.php');
require_once(__DIR__ . '/../classes/Payment.php');

session_start();

$db = Database::getInstance();
$auth = new Auth($db);

if (!$auth->isLoggedIn() || !$auth->isAdmin()) {
    http_response_code(403);
    die(json_encode(['status' => 'error', 'message' => 'Unauthorized']));
}

header('Content-Type: application/json');

$data = json_decode(file_get_contents('php://input'), true);
$orderId = $data['order_id'] ?? null;

if (!$orderId) {
    die(json_encode(['status' => 'error', 'message' => 'Order ID required']));
}

$payment = new Payment();

$order = $db->fetch('SELECT * FROM payment_orders WHERE order_id = ?', [$orderId]);

if (!$order) {
    die(json_encode(['status' => 'error', 'message' => 'Order not found']));
}

// Confirm payment
$result = $payment->confirmPayment($orderId, $order['transaction_id'], 'manual_approval');

if ($result['status']) {
    echo json_encode(['status' => 'success', 'message' => 'Payment approved successfully']);
} else {
    echo json_encode(['status' => 'error', 'message' => $result['message']]);
}
?>
