<?php
/**
 * rebate_history_api.php
 * User-এর আগের সব Rebate-Claim-History দেখায়
 */
error_reporting(E_ALL);
ini_set('display_errors', 0);
ob_start();
header('Content-Type: application/json; charset=utf-8');
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    ob_end_clean();
    echo json_encode(['code' => 1, 'msg' => "PHP-Error: $errstr (Line: $errline)"]);
    exit;
});
register_shutdown_function(function() {
    $error = error_get_last();
    if ($error !== null && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        if (ob_get_level() > 0) ob_end_clean();
        echo json_encode(['code' => 1, 'msg' => "Fatal-Error: " . $error['message']]);
    } else {
        if (ob_get_level() > 0) ob_end_flush();
    }
});

include __DIR__ . "/deepanshu/conn.php";
include __DIR__ . "/deepanshu/functions2.php";
if (isset($conn)) { $conn->set_charset("utf8mb4"); }

$bearer = explode(" ", $_SERVER['HTTP_AUTHORIZATION'] ?? '');
$author = $bearer[1] ?? '';
$is_jwt_valid = is_jwt_valid($author);
$data_auth = json_decode($is_jwt_valid, true);

if (($data_auth['status'] ?? '') !== 'Success') {
    echo json_encode(['code' => 1, 'msg' => 'Login করা নেই']);
    exit;
}

$userId = $data_auth['payload']['id'];

$tableCheck = $conn->query("SHOW TABLES LIKE 'rebate_claims'");
if (!$tableCheck || $tableCheck->num_rows === 0) {
    echo json_encode(['code' => 0, 'history' => []]);
    exit;
}

$stmt = $conn->prepare("SELECT turnover_amount, rebate_amount, claimed_at FROM rebate_claims WHERE user_id = ? ORDER BY claimed_at DESC LIMIT 100");
$stmt->bind_param("s", $userId);
$stmt->execute();
$result = $stmt->get_result();

$history = [];
while ($row = $result->fetch_assoc()) {
    $history[] = $row;
}

echo json_encode(['code' => 0, 'history' => $history]);
