<?php
require_once 'config.php';

ini_set('display_errors', 0);
error_reporting(0);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die("Invalid Request Method");
}

$username = trim($_POST['username'] ?? '');
$type     = trim($_POST['type'] ?? '');
$token    = trim($_POST['token'] ?? '');

if ($username === '' || $type === '') {
    die("Invalid Type");
}

/**
 * Dev ZabbarX
 */
function bindParams(mysqli_stmt $stmt, string $types, array &$params): void
{
    $bindNames = [$types];
    foreach ($params as $key => $value) {
        $bindNames[] = &$params[$key];
    }
    call_user_func_array([$stmt, 'bind_param'], $bindNames);
}

/**
 * Help ZabbarX
 */
function fetchOne(mysqli $conn, string $sql, string $types, array $params): ?array
{
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        return null;
    }

    bindParams($stmt, $types, $params);
    $stmt->execute();

    $result = $stmt->get_result();
    $row = $result ? $result->fetch_assoc() : null;

    $stmt->close();
    return $row ?: null;
}

/**
 * Helper: ZabbarX
 */
function fetchAll(mysqli $conn, string $sql, string $types, array $params): array
{
    $data = [];

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        return $data;
    }

    bindParams($stmt, $types, $params);
    $stmt->execute();

    $result = $stmt->get_result();
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
    }

    $stmt->close();
    return $data;
}

/*
|--------------------------------------------------------------------------
| First: @found_null ©
|--------------------------------------------------------------------------
*/
$user = fetchOne(
    $conn,
    "SELECT id, email, fcm_key, uid, token
     FROM users
     WHERE username = ? AND token = ?
     LIMIT 1",
    "ss",
    [$username, $token]
);

if (!$user) {
    $user = fetchOne(
        $conn,
        "SELECT id, email, fcm_key, uid, token
         FROM users
         WHERE username = ?
         LIMIT 1",
        "s",
        [$username]
    );
}

if (!$user) {
    die("No Data Found");
}

$user_id    = $user['id'];
$user_email = $user['email'];
$user_fcm   = $user['fcm_key'];
$user_uid   = $user['uid'];
$user_token = $user['token'];

$historyData = [];

switch ($type) {
    case 'addmoney':
        $rows = fetchAll(
            $conn,
            "SELECT id, username, email, method, number, amount, trxid, status, date, time
             FROM addmoney
             WHERE username = ?
             ORDER BY id DESC",
            "s",
            [$username]
        );

        foreach ($rows as $row) {
            $row['fcm'] = $user_fcm;
            $historyData[] = $row;
        }
        break;

    case 'withdraw':
        $rows = fetchAll(
            $conn,
            "SELECT id, username, email, method, number, amount, trxid, status, date, time
             FROM withdraw
             WHERE username = ?
             ORDER BY id DESC",
            "s",
            [$username]
        );

        foreach ($rows as $row) {
            $row['fcm'] = $user_fcm;
            $historyData[] = $row;
        }
        break;

    case 'product':
    case 'joinentry':
        $rows = fetchAll(
            $conn,
            "SELECT id, name, type, email, match_id, total_kill, winning, fcm_key, mode, team_color, team_name, is_leader
             FROM joiners
             WHERE email = ?
             ORDER BY id DESC",
            "s",
            [$user_email]
        );

        foreach ($rows as $row) {
            $row['match_title'] = "Match ID: #" . $row['match_id'] . " (" . $row['type'] . ")";
            $row['amount'] = ($row['winning'] > 0) ? $row['winning'] : "0";
            $row['status'] = "Completed";
            $row['date'] = "Joined Match";
            $historyData[] = $row;
        }
        break;

    case 'gift':
        $rows = fetchAll(
            $conn,
            "SELECT id, sender_uid, receiver_uid, amount, fee, total, type, status, created_at
             FROM gift_requests
             WHERE sender_uid = ?
             ORDER BY id DESC",
            "s",
            [$user_uid]
        );

        foreach ($rows as $row) {
            $row['gift_name'] = "Gift Sent to UID";
            $historyData[] = $row;
        }
        break;

    case 'topup':
        $rows = fetchAll(
            $conn,
            "SELECT id, product_id, user_token, username, email, product_title, discount_price, topup_uid, order_date, status
             FROM topup_orders
             WHERE user_token = ?
             ORDER BY id DESC",
            "s",
            [$user_token]
        );

        foreach ($rows as $row) {
            $row['amount'] = $row['discount_price'];
            $row['date'] = $row['order_date'];
            $historyData[] = $row;
        }
        break;

    case 'products':
        /*
         #The Pro 🤥 @found_null
         */
        $rows = fetchAll(
            $conn,
            "SELECT id, order_id, user_id, product_id, product_title, product_image, amount, address, extra_json, status, created_at
             FROM product_orders
             WHERE user_id = ? OR user_id = ? OR user_id = ?
             ORDER BY id DESC",
            "sss",
            [$user_id, $user_uid, $user_token]
        );

        foreach ($rows as $row) {
            $row['date'] = $row['created_at'];
            $historyData[] = $row;
        }
        break;

    default:
        die("Invalid Type");
}

if (!empty($historyData)) {
    echo json_encode($historyData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} else {
    echo "No Data Found";
}

$conn->close();
?>