<?php
require_once(__DIR__ . '/../../session.php');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        echo json_encode(['status' => 'error', 'message' => "Invalid CSRF Token!"]);
        exit();
    }

    $action = $_POST['action'] ?? '';
    $trxId = $_POST['trxid'] ?? '';

    // Cek transaksi
    $checkTransaction = "SELECT user_id, Amount FROM transaction WHERE trxid = :trxId AND type = 'deposit'";
    $stmt = $db->prepare($checkTransaction);
    $stmt->bindParam(':trxId', $trxId);
    $stmt->execute();
    $check = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($check) {
        $amount = (int)$check['Amount'];
        $user_id = (int)$check['user_id'];

        // Ambil eksternal player ID
        $stmt = $db->prepare("SELECT extplayer FROM user WHERE id = :user_id LIMIT 1");
        $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        $extplayer = $user['extplayer'];

        if ($action === 'approve') {
                $updateStatus = "UPDATE transaction SET status = 1, is_read = 0, updated_at = NOW() WHERE trxid = :trxId AND type = 'deposit'";
                $stmt = $db->prepare($updateStatus);
                $stmt->bindParam(':trxId', $trxId);
                $stmt->execute();

                $updateBalance = "UPDATE balance SET total_balance = total_balance + :amount, updated_at = NOW() WHERE user_id = :user_id";
                $stmt = $db->prepare($updateBalance);
                $stmt->bindParam(':amount', $amount, PDO::PARAM_INT);
                $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
                $stmt->execute();

                echo json_encode(['status' => 'success', 'message' => "Transaksi berhasil disetujui."]);

        } elseif ($action === 'reject') {
            $updateStatus = "UPDATE transaction SET status = 2, is_read = 0, updated_at = NOW() WHERE trxid = :trxId AND type = 'deposit'";
            $stmt = $db->prepare($updateStatus);
            $stmt->bindParam(':trxId', $trxId);
            $stmt->execute();

            echo json_encode(['status' => 'success', 'message' => "Transaksi berhasil ditolak."]);
        } else {
            echo json_encode(['status' => 'error', 'message' => "Aksi tidak valid!"]);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => "Transaksi tidak ditemukan!"]);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => "Metode permintaan tidak valid!"]);
}
