<?php
/**
 * MOVEX – get-trade-rate.php
 * Returns the correct trade profit/loss rate for THIS user TODAY
 * 
 * Used by dashboard.js before activating a trade
 * GET ?wallet=xxx
 * 
 * Rate priority:
 * 1. Weekend → closed (no trade)
 * 2. Admin set day_type=closed → closed
 * 3. Admin set day_type=loss → loss
 * 4. User reward tier → tier3=7%, tier2=6%, tier1=5%
 * 5. Investment >= $500 → 7% (flat per your spec)
 * 6. Default base → 4%
 */

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

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

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

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;
}

// 1. Weekend check
$dayNum = intval(date('N')); // 1=Mon .. 7=Sun
if ($dayNum >= 6) {
    echo json_encode([
        'status'      => 'success',
        'can_trade'   => false,
        'day_type'    => 'closed',
        'reason'      => 'Weekend — Market closed (Sat & Sun)',
        'profit_pct'  => 0,
        'loss_pct'    => 0,
    ]);
    exit;
}

// 2. Admin daily config
$today  = date('Y-m-d');
$cfg    = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM trade_config WHERE config_date='$today' LIMIT 1"));
$base   = floatval(getSetting($conn, 'base_profit_pct', 0.04));

if (!$cfg) {
    // Auto-create default
    mysqli_query($conn, "
        INSERT IGNORE INTO trade_config (config_date, day_type, profit_pct, loss_pct, note, set_by_admin)
        VALUES ('$today', 'profit', $base, 0, 'Auto-default', 0)
    ");
    $cfg = ['day_type'=>'profit','profit_pct'=>$base,'loss_pct'=>0,'note'=>'Default'];
}

if ($cfg['day_type'] === 'closed') {
    echo json_encode([
        'status'     => 'success',
        'can_trade'  => false,
        'day_type'   => 'closed',
        'reason'     => $cfg['note'] ?: 'Market closed today',
        'profit_pct' => 0,
        'loss_pct'   => 0,
    ]);
    exit;
}

// 3. User data
$w    = mysqli_real_escape_string($conn, $wallet);
$user = mysqli_fetch_assoc(mysqli_query($conn, "
    SELECT reward_tier, trade_profit_rate FROM users WHERE wallet='$w' LIMIT 1
"));
if (!$user) {
    echo json_encode(['status'=>'error','message'=>'User not found']);
    exit;
}

$reward_tier = intval($user['reward_tier'] ?? 0);

// 4. Investment amount
$total_inv = floatval(mysqli_fetch_assoc(mysqli_query($conn, "
    SELECT COALESCE(SUM(amount),0) AS amt FROM deposits WHERE wallet='$w' AND status='success'
"))['amt']);

// 5. Determine profit rate
$high_inv_pct = floatval(getSetting($conn, 'high_inv_pct', 0.07));
$tier3_pct    = floatval(getSetting($conn, 'tier3_profit_pct', 0.07));
$tier2_pct    = floatval(getSetting($conn, 'tier2_profit_pct', 0.06));
$tier1_pct    = floatval(getSetting($conn, 'tier1_profit_pct', 0.05));

if ($cfg['day_type'] === 'loss') {
    // Loss day — admin set
    $profit_pct = 0;
    $loss_pct   = floatval($cfg['loss_pct']);
    $day_type   = 'loss';
} else {
    // Profit day — find user's rate
    if ($reward_tier >= 3) {
        $profit_pct = $tier3_pct;
        $rate_label = 'Tier 3 Reward (27 Directs)';
    } elseif ($reward_tier >= 2) {
        $profit_pct = $tier2_pct;
        $rate_label = 'Tier 2 Reward (9 Directs)';
    } elseif ($reward_tier >= 1) {
        $profit_pct = $tier1_pct;
        $rate_label = 'Tier 1 Reward (3 Directs)';
    } elseif ($total_inv >= 500) {
        // $500+ investment → 7%
        $profit_pct = $high_inv_pct;
        $rate_label = 'High Investment ($500+)';
    } else {
        $profit_pct = $base;
        $rate_label = 'Standard Rate';
    }
    $loss_pct = 0;
    $day_type = 'profit';
}

// 6. Response
$today_weekday = date('l'); // Monday, Tuesday…
// Week schedule: 3 profit days, 2 loss days (Mon-Fri)
// This is admin-controlled, we just return today's

echo json_encode([
    'status'      => 'success',
    'can_trade'   => true,
    'day_type'    => $day_type,
    'day_name'    => $today_weekday,
    'profit_pct'  => round($profit_pct, 4),
    'profit_pct_display' => round($profit_pct * 100, 2) . '%',
    'loss_pct'    => round($loss_pct, 4),
    'rate_label'  => $rate_label ?? 'Standard Rate',
    'reward_tier' => $reward_tier,
    'investment'  => $total_inv,
    'note'        => $cfg['note'] ?? '',
]);