<?php
header('Content-Type: application/json');
include 'config.php';

session_start();

$VALID_USERNAME = 'SKM eSPORTS';
$VALID_PASSWORD = '2580';

$admin_authenticated = false;
if (isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true) {
    $admin_authenticated = true;
}
if (!$admin_authenticated) {
    $admin_username = $_POST['admin_username'] ?? '';
    $admin_password = $_POST['admin_password'] ?? '';
    if ($admin_username === $VALID_USERNAME && $admin_password === $VALID_PASSWORD) {
        $admin_authenticated = true;
        $_SESSION['admin_logged_in'] = true;
        $_SESSION['admin_username'] = $admin_username;
    }
}
if (!$admin_authenticated) {
    http_response_code(403);
    echo json_encode(["status" => "error", "message" => "Access Denied. Please login."]);
    exit;
}

$type = $_POST['type'] ?? '';

$owner_res = $conn->query("SELECT username FROM admin LIMIT 1");
$owner_username = ($owner_res && $owner_res->num_rows > 0) ? $owner_res->fetch_assoc()['username'] : '';

if ($type === 'get_all') {
    $moderatorType = $_POST['moderator_type'] ?? '';
    $page = max(1, (int)($_POST['page'] ?? 1));
    $per_page = max(1, (int)($_POST['per_page'] ?? 20));
    $offset = ($page - 1) * $per_page;

    $where = "";
    if ($moderatorType === 'owner') {
        $where = " WHERE moderator_username = '$owner_username'";
    } elseif ($moderatorType === 'moderator') {
        $where = " WHERE moderator_username != '$owner_username'";
    }

    $countQuery = "SELECT COUNT(*) as total FROM refund_logs" . $where;
    $countResult = $conn->query($countQuery);
    $total = $countResult->fetch_assoc()['total'] ?? 0;
    $last_page = ceil($total / $per_page);

    $sql = "SELECT * FROM refund_logs" . $where . " ORDER BY refunded_at DESC LIMIT $offset, $per_page";
    $result = $conn->query($sql);
    $data = [];
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }

    echo json_encode([
        "status" => "success",
        "data" => $data,
        "total" => (int)$total,
        "current_page" => $page,
        "per_page" => $per_page,
        "last_page" => $last_page
    ]);
    exit;
}

// পুরোনো টাইপ সাপোর্ট (ঐচ্ছিক)
if ($type === 'owner') {
    $stmt = $conn->prepare("SELECT * FROM refund_logs WHERE moderator_username = ? ORDER BY refunded_at DESC");
    $stmt->bind_param("s", $owner_username);
    $stmt->execute();
    $logs = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    echo json_encode(count($logs) > 0 ? $logs : []);
    exit;
}
if ($type === 'moderator') {
    $stmt = $conn->prepare("SELECT * FROM refund_logs WHERE moderator_username != ? ORDER BY refunded_at DESC");
    $stmt->bind_param("s", $owner_username);
    $stmt->execute();
    $logs = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    echo json_encode(count($logs) > 0 ? $logs : []);
    exit;
}

echo json_encode(["status" => "error", "message" => "Invalid type"]);
$conn->close();
?>