<?php
/**
 * MOVEX – Reward Eligibility Check & Claim
 * GET  ?wallet=xxx&action=check    → check current reward status
 * GET  ?wallet=xxx&action=history  → reward history
 * POST ?wallet=xxx&action=claim    → claim pending reward (called after milestone)
 * 
 * ═══════════════════════════════════════
 * REWARD TIERS:
 * Tier 1 → 3 directs in 24h  → $12 one-time + trade profit 5%
 * Tier 2 → 9 directs in 72h  → $20 one-time + trade profit 6%
 * Tier 3 → 27 directs in 7d  → $30 one-time + trade profit 7%
 *
 * PROGRESSION LOGIC:
 * - If user gets 3 directs in day 1 → tier1 achieved, now needs 6 MORE in next window
 * - If they fail 6 → reset: needs 9 directs in 3 days again (tier2 window restarts)
 * - If they get 6 → tier2 achieved, now needs 18 MORE in remaining window
 * - etc.
 * ═══════════════════════════════════════
 */

error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');

require_once '../config/db.php';

$wallet = trim($_GET['wallet'] ?? '');
$action = trim($_GET['action'] ?? 'check');

if (empty($wallet)) {
    echo json_encode(['status' => 'error', 'message' => 'Wallet required']);
    exit;
}

// ── Helper: Get setting value ──
function getSetting($conn, $key, $default = null) {
    $k   = mysqli_real_escape_string($conn, $key);
    $row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT setting_value FROM trade_settings WHERE setting_key='$k' LIMIT 1"));
    return $row ? $row['setting_value'] : $default;
}

// ── Helper: Count confirmed directs of a sponsor ──
function countDirects($conn, $acc_id, $since_datetime = null) {
    $esc = mysqli_real_escape_string($conn, $acc_id);
    $where = "u.referral_id = '$esc'";
    if ($since_datetime) {
        $dt    = mysqli_real_escape_string($conn, $since_datetime);
        $where .= " AND d.created_at >= '$dt'";
    }
    $sql = "SELECT COUNT(DISTINCT u.wallet) AS cnt
            FROM users u
            JOIN deposits d ON u.wallet = d.wallet AND d.status = 'success'
            WHERE $where";
    $row = mysqli_fetch_assoc(mysqli_query($conn, $sql));
    return intval($row['cnt'] ?? 0);
}

// ── Helper: Get user account_id ──
function getAccId($conn, $wallet) {
    $w   = mysqli_real_escape_string($conn, $wallet);
    $row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT account_id FROM users WHERE wallet='$w' LIMIT 1"));
    return $row ? $row['account_id'] : null;
}

// ── Helper: Get user reward tier ──
function getUserRewardData($conn, $wallet) {
    $w = mysqli_real_escape_string($conn, $wallet);
    return mysqli_fetch_assoc(mysqli_query($conn, "
        SELECT reward_tier, reward_tier1_at, reward_tier2_at, reward_tier3_at, trade_profit_rate
        FROM users WHERE wallet='$w' LIMIT 1
    "));
}

// ══════════════════════════════════════════
//  ACTION: CHECK (main eligibility engine)
// ══════════════════════════════════════════
if ($action === 'check') {
    $acc_id = getAccId($conn, $wallet);
    if (!$acc_id) {
        echo json_encode(['status' => 'error', 'message' => 'User not found']);
        exit;
    }

    $userData = getUserRewardData($conn, $wallet);
    $curTier  = intval($userData['reward_tier'] ?? 0);

    // Load reward amounts from settings
    $tier1_amt  = floatval(getSetting($conn, 'tier1_reward_amt', 12));
    $tier2_amt  = floatval(getSetting($conn, 'tier2_reward_amt', 20));
    $tier3_amt  = floatval(getSetting($conn, 'tier3_reward_amt', 30));
    $tier1_pct  = floatval(getSetting($conn, 'tier1_profit_pct', 0.05));
    $tier2_pct  = floatval(getSetting($conn, 'tier2_profit_pct', 0.06));
    $tier3_pct  = floatval(getSetting($conn, 'tier3_profit_pct', 0.07));

    // Total directs ever (with investment)
    $total_directs = countDirects($conn, $acc_id);

    // ── Tier windows ──
    $now    = new DateTime();
    $tier1_window = 24;   // hours
    $tier2_window = 72;   // hours
    $tier3_window = 168;  // hours (7 days)

    // Directs in last 24h / 72h / 168h
    $d24  = countDirects($conn, $acc_id, $now->modify('-24 hours')->format('Y-m-d H:i:s'));
    $now->modify('+24 hours'); // restore
    $d72  = countDirects($conn, $acc_id, $now->modify('-72 hours')->format('Y-m-d H:i:s'));
    $now->modify('+72 hours');
    $d168 = countDirects($conn, $acc_id, $now->modify('-168 hours')->format('Y-m-d H:i:s'));
    $now->modify('+168 hours');

    $pending_reward = null;
    $new_tier       = $curTier;

    // ── Check Tier 3 (highest) first ──
    if ($curTier < 3 && $d168 >= 27) {
        $new_tier = 3;
        $pending_reward = [
            'tier'        => 3,
            'bonus_amt'   => $tier3_amt,
            'new_rate'    => $tier3_pct,
            'directs_hit' => $d168,
            'window'      => '7 days',
            'label'       => '27 Directs in 7 Days'
        ];
    }
    // ── Check Tier 2 ──
    elseif ($curTier < 2 && $d72 >= 9) {
        $new_tier = 2;
        $pending_reward = [
            'tier'        => 2,
            'bonus_amt'   => $tier2_amt,
            'new_rate'    => $tier2_pct,
            'directs_hit' => $d72,
            'window'      => '3 days',
            'label'       => '9 Directs in 3 Days'
        ];
    }
    // ── Check Tier 1 ──
    elseif ($curTier < 1 && $d24 >= 3) {
        $new_tier = 1;
        $pending_reward = [
            'tier'        => 1,
            'bonus_amt'   => $tier1_amt,
            'new_rate'    => $tier1_pct,
            'directs_hit' => $d24,
            'window'      => '24 hours',
            'label'       => '3 Directs in 24 Hours'
        ];
    }

    // Auto-apply if new tier found
    if ($pending_reward && $new_tier > $curTier) {
        $w   = mysqli_real_escape_string($conn, $wallet);
        $nr  = $new_tier;
        $col = "reward_tier{$new_tier}_at";
        $pct = $pending_reward['new_rate'];

        mysqli_query($conn, "
            UPDATE users
            SET reward_tier=$nr, trade_profit_rate=$pct, `$col`=NOW()
            WHERE wallet='$w'
        ");

        // Check if already rewarded for this tier
        $already = mysqli_fetch_assoc(mysqli_query($conn, "
            SELECT id FROM reward_logs WHERE wallet='$w' AND tier=$nr LIMIT 1
        "));

        if (!$already) {
            $amt  = $pending_reward['bonus_amt'];
            $type = "tier{$new_tier}_bonus";
            $cnt  = $pending_reward['directs_hit'];
            $win  = ($new_tier == 1) ? 24 : ($new_tier == 2 ? 72 : 168);

            mysqli_query($conn, "
                INSERT INTO reward_logs (wallet, reward_type, tier, amount, directs_count, window_hours, achieved_at)
                VALUES ('$w', '$type', $new_tier, $amt, $cnt, $win, NOW())
            ");

            // Also add to user balance (via a bonus_logs or wallet_credits table)
            // If you have a wallet_balance column or credits table, update here:
            // mysqli_query($conn, "UPDATE users SET wallet_balance = wallet_balance + $amt WHERE wallet='$w'");
        }

        $curTier  = $new_tier;
        $userData = getUserRewardData($conn, $wallet);
    }

    // ── Build progress towards next tier ──
    $progress = [];
    if ($curTier < 1) {
        $progress = ['next_tier' => 1, 'needed' => 3,  'done' => $d24,  'window' => '24 hours', 'bonus' => $tier1_amt, 'new_rate' => ($tier1_pct*100).'%'];
    } elseif ($curTier < 2) {
        // Need 9 directs in 3 days (if tier1 already done, need 6 more = 9 total in window)
        $progress = ['next_tier' => 2, 'needed' => 9,  'done' => $d72,  'window' => '3 days',   'bonus' => $tier2_amt, 'new_rate' => ($tier2_pct*100).'%'];
    } elseif ($curTier < 3) {
        $progress = ['next_tier' => 3, 'needed' => 27, 'done' => $d168, 'window' => '7 days',   'bonus' => $tier3_amt, 'new_rate' => ($tier3_pct*100).'%'];
    }

    // ── Claimed rewards ──
    $w = mysqli_real_escape_string($conn, $wallet);
    $claimedQ = mysqli_query($conn, "
        SELECT tier, amount, directs_count, window_hours, achieved_at
        FROM reward_logs WHERE wallet='$w' ORDER BY tier ASC
    ");
    $claimed = [];
    while ($r = mysqli_fetch_assoc($claimedQ)) $claimed[] = $r;

    echo json_encode([
        'status'          => 'success',
        'current_tier'    => $curTier,
        'trade_rate'      => floatval($userData['trade_profit_rate'] ?? 0.04),
        'trade_rate_pct'  => round(floatval($userData['trade_profit_rate'] ?? 0.04) * 100, 2),
        'total_directs'   => $total_directs,
        'directs_24h'     => $d24,
        'directs_72h'     => $d72,
        'directs_168h'    => $d168,
        'pending_reward'  => $pending_reward,
        'progress'        => $progress,
        'claimed_rewards' => $claimed,
        'tier_milestones' => [
            ['tier'=>1,'label'=>'3 Directs / 24h', 'bonus'=>$tier1_amt,'rate'=>($tier1_pct*100).'%','achieved'=>in_array(1,array_column($claimed,'tier'))],
            ['tier'=>2,'label'=>'9 Directs / 3 Days','bonus'=>$tier2_amt,'rate'=>($tier2_pct*100).'%','achieved'=>in_array(2,array_column($claimed,'tier'))],
            ['tier'=>3,'label'=>'27 Directs / 7 Days','bonus'=>$tier3_amt,'rate'=>($tier3_pct*100).'%','achieved'=>in_array(3,array_column($claimed,'tier'))],
        ]
    ]);
    exit;
}

// ══════════════════════════════════════════
//  ACTION: HISTORY
// ══════════════════════════════════════════
if ($action === 'history') {
    $w = mysqli_real_escape_string($conn, $wallet);
    $q = mysqli_query($conn, "
        SELECT reward_type, tier, amount, directs_count, window_hours, achieved_at
        FROM reward_logs WHERE wallet='$w' ORDER BY id DESC
    ");
    $logs = [];
    while ($r = mysqli_fetch_assoc($q)) $logs[] = $r;
    echo json_encode(['status' => 'success', 'logs' => $logs, 'count' => count($logs)]);
    exit;
}

echo json_encode(['status' => 'error', 'message' => 'Unknown action']);