<?php
/**
 * commission_api.php
 * ✅ কোনো Existing File (Callback.php, Deposit-Approval)
 * স্পর্শ করা হয়নি — Downline-দের Real Deposit/Betting-Data
 * থেকে, On-Demand Commission Calculate + Claim করা হয়
 *
 * action=summary → মোট কত Commission Available (Claim না করা)
 * action=claim   → Available Commission, Balance-এ যোগ করা
 * action=history → আগের সব Commission-Payout দেখা
 */
error_reporting(E_ALL);
ini_set('display_errors', 0);
header('Content-Type: application/json; charset=utf-8');
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    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])) {
        echo json_encode(['code' => 1, 'msg' => "Fatal-Error: " . $error['message']]);
    }
});

include __DIR__ . "/deepanshu/conn.php";
include __DIR__ . "/deepanshu/functions2.php";

define('DEPOSIT_COMMISSION_RATE', 2.0);
define('BETTING_COMMISSION_RATE', 0.0); // ✅ ঠিক করা হলো — Betting-Commission সম্পূর্ণ বন্ধ, শুধু Deposit-Commission থাকবে

$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'];
$action = $_GET['action'] ?? '';

$tableCheck = $conn->query("SHOW TABLES LIKE 'commission_payouts'");
if (!$tableCheck || $tableCheck->num_rows === 0) {
    echo json_encode(['code' => 1, 'msg' => 'Database-এ "commission_payouts" Table পাওয়া যায়নি — commission_schema.sql Run করতে হবে']);
    exit;
}

$ownCodeQuery = $conn->prepare("SELECT owncode FROM shonu_subjects WHERE id = ?");
$ownCodeQuery->bind_param("s", $userId);
$ownCodeQuery->execute();
$ownCodeResult = $ownCodeQuery->get_result();
$ownCodeRow = $ownCodeResult->fetch_assoc();
$ownCode = $ownCodeRow['owncode'] ?? '';

$downlineIds = [];
if ($ownCode !== '') {
    // ✅ ঠিক করা হলো — আগে ভুলবশত "code1" Column ব্যবহার হচ্ছিল,
    // কিন্তু আসল, Working Referral-System "code" Column ব্যবহার করে
    $downlineQuery = $conn->prepare("SELECT id FROM shonu_subjects WHERE code = ?");
    $downlineQuery->bind_param("s", $ownCode);
    $downlineQuery->execute();
    $downlineResult = $downlineQuery->get_result();
    while ($row = $downlineResult->fetch_assoc()) {
        $downlineIds[] = $row['id'];
    }
}

function calculateAvailableCommission($conn, $userId, $downlineIds, $depositRate, $bettingRate) {
    if (empty($downlineIds)) {
        return ['total_deposit_amount' => 0, 'total_betting_amount' => 0, 'total_deposit_commission' => 0, 'total_betting_commission' => 0, 'total_earned_overall' => 0, 'total_already_paid' => 0, 'available_to_claim' => 0, 'downline_count' => 0];
    }

    $placeholders = implode(',', array_fill(0, count($downlineIds), '?'));
    $types = str_repeat('s', count($downlineIds));

    $depositStmt = $conn->prepare("SELECT SUM(motta) as total FROM thevani WHERE balakedara IN ($placeholders) AND sthiti = 1");
    $depositStmt->bind_param($types, ...$downlineIds);
    $depositStmt->execute();
    $totalDeposit = (float)($depositStmt->get_result()->fetch_assoc()['total'] ?? 0);

    $betStmt = $conn->prepare("SELECT SUM(bet_amount) as total FROM game_bet_logs WHERE user_id IN ($placeholders)");
    $betStmt->bind_param($types, ...$downlineIds);
    $betStmt->execute();
    $totalBet = (float)($betStmt->get_result()->fetch_assoc()['total'] ?? 0);

    $paidStmt = $conn->prepare("SELECT SUM(commission_amount) as total FROM commission_payouts WHERE referrer_id = ?");
    $paidStmt->bind_param("s", $userId);
    $paidStmt->execute();
    $totalAlreadyPaid = (float)($paidStmt->get_result()->fetch_assoc()['total'] ?? 0);

    $totalEarnedDeposit = round($totalDeposit * ($depositRate / 100), 2);
    $totalEarnedBetting = round($totalBet * ($bettingRate / 100), 2);
    $totalEarnedOverall = $totalEarnedDeposit + $totalEarnedBetting;

    $availableToClaim = max(0, round($totalEarnedOverall - $totalAlreadyPaid, 2));

    return [
        'total_deposit_amount' => round($totalDeposit, 2),
        'total_betting_amount' => round($totalBet, 2),
        'total_deposit_commission' => $totalEarnedDeposit,
        'total_betting_commission' => $totalEarnedBetting,
        'total_earned_overall' => round($totalEarnedOverall, 2),
        'total_already_paid' => round($totalAlreadyPaid, 2),
        'available_to_claim' => $availableToClaim,
        'downline_count' => count($downlineIds)
    ];
}

if ($action === 'summary') {
    $summary = calculateAvailableCommission($conn, $userId, $downlineIds, DEPOSIT_COMMISSION_RATE, BETTING_COMMISSION_RATE);
    $summary['code'] = 0;
    $summary['deposit_rate'] = DEPOSIT_COMMISSION_RATE;
    $summary['betting_rate'] = BETTING_COMMISSION_RATE;
    echo json_encode($summary);
    exit;
}

if ($action === 'claim') {
    $summary = calculateAvailableCommission($conn, $userId, $downlineIds, DEPOSIT_COMMISSION_RATE, BETTING_COMMISSION_RATE);
    $claimAmount = $summary['available_to_claim'];

    if ($claimAmount <= 0) {
        echo json_encode(['code' => 1, 'msg' => 'এখন Claim করার মতো কোনো Commission নেই']);
        exit;
    }

    $conn->begin_transaction();
    try {
        $updateStmt = $conn->prepare("UPDATE shonu_kaichila SET motta = motta + ? WHERE balakedara = ?");
        $updateStmt->bind_param("ds", $claimAmount, $userId);
        $updateStmt->execute();

        $recordStmt = $conn->prepare("INSERT INTO commission_payouts (referrer_id, downline_id, source_type, source_amount, commission_amount, commission_rate) VALUES (?, 'summary', 'combined', ?, ?, 0)");
        $recordStmt->bind_param("sdd", $userId, $claimAmount, $claimAmount);
        $recordStmt->execute();

        $conn->commit();
        echo json_encode(['code' => 0, 'msg' => "সফল! ৳$claimAmount তোমার Balance-এ যোগ হয়েছে", 'claimed_amount' => $claimAmount]);
    } catch (Throwable $e) {
        $conn->rollback();
        echo json_encode(['code' => 1, 'msg' => 'একটা সমস্যা হয়েছে, আবার চেষ্টা করো']);
    }
    exit;
}

if ($action === 'history') {
    $historyStmt = $conn->prepare("SELECT commission_amount, source_type, paid_at FROM commission_payouts WHERE referrer_id = ? ORDER BY paid_at DESC LIMIT 100");
    $historyStmt->bind_param("s", $userId);
    $historyStmt->execute();
    $historyResult = $historyStmt->get_result();

    $history = [];
    while ($row = $historyResult->fetch_assoc()) {
        $history[] = $row;
    }
    echo json_encode(['code' => 0, 'history' => $history]);
    exit;
}

echo json_encode(['code' => 1, 'msg' => 'Invalid Action']);
