<?php
// api-refund.php - Tandai / batalkan refund order (hanya pusat = admin)
require_once __DIR__ . '/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(['status' => 'error', 'message' => 'POST only'], 405);
}

$admin = requireAdmin();
$db = getDB();

$input = json_decode(file_get_contents('php://input'), true);
$orderId = (int)($input['order_id'] ?? 0);
$action = $input['action'] ?? 'refund'; // 'refund' | 'cancel_refund'

if ($orderId <= 0) {
    jsonResponse(['status' => 'error', 'message' => 'order_id wajib diisi'], 400);
}

$status = $action === 'cancel_refund' ? 'completed' : 'refund';
$refundedAt = $status === 'refund' ? date('Y-m-d H:i:s') : null;
$refundedBy = $status === 'refund' ? $admin['name'] : null;

try {
    $stmt = $db->prepare('UPDATE orders SET status = ?, refunded_at = ?, refunded_by = ? WHERE id = ?');
    $stmt->execute([$status, $refundedAt, $refundedBy, $orderId]);

    if ($stmt->rowCount() === 0) {
        jsonResponse(['status' => 'error', 'message' => 'Order tidak ditemukan'], 404);
    }

    jsonResponse(['status' => 'success', 'order_id' => $orderId, 'order_status' => $status]);
} catch (Exception $e) {
    jsonResponse(['status' => 'error', 'message' => $e->getMessage()], 500);
}