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

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

$input = json_decode(file_get_contents('php://input'), true);
$users = $input['users'] ?? [];

if (empty($users)) {
    echo json_encode(['status' => 'error', 'message' => 'No users selected']);
    exit;
}

$today   = date('Y-m-d');
$results = [];
$success_count = 0;
$fail_count    = 0;

foreach ($users as $userData) {
    $wallet          = mysqli_real_escape_string($conn, $userData['wallet']);
    $account_id      = mysqli_real_escape_string($conn, $userData['account_id'] ?? '');
    $penalty_amount  = floatval($userData['penalty_amount']);
    $trade_rate      = floatval($userData['trade_rate']);
    $penalty_rate    = floatval($userData['penalty_rate']);
    $current_balance = floatval($userData['current_balance']);
    $name            = mysqli_real_escape_string($conn, $userData['name']);
    
    if ($penalty_amount <= 0) continue;
    
    $neg_penalty = -abs($penalty_amount);
    
    // trade_logs ke exact columns: wallet, account_id, position, amount, pnl_amount, day_type, rate
    $insert = mysqli_query($conn, "
        INSERT INTO trade_logs 
        (wallet, account_id, position, amount, pnl_amount, day_type, rate, created_at)
        VALUES 
        ('$wallet', '$account_id', 'PENALTY', '$current_balance', '$neg_penalty', 'penalty', '$penalty_rate', NOW())
    ");
    
    if ($insert) {
        $balance_after = max(0, $current_balance + $neg_penalty);
        
        // penalty_logs mein bhi save karo
        mysqli_query($conn, "
            INSERT INTO penalty_logs 
            (wallet, user_name, original_rate, penalty_rate, penalty_amount, 
             balance_before, balance_after, applied_by, trade_date)
            VALUES 
            ('$wallet', '$name', '$trade_rate', '$penalty_rate', '$penalty_amount', 
             '$current_balance', '$balance_after', 'admin', '$today')
        ");
        
        $results[] = [
            'wallet'         => $userData['wallet'],
            'name'           => $name,
            'status'         => 'success',
            'penalty_amount' => $penalty_amount,
            'balance_before' => $current_balance,
            'balance_after'  => $balance_after,
        ];
        $success_count++;
    } else {
        $results[] = [
            'wallet' => $userData['wallet'],
            'name'   => $name,
            'status' => 'failed',
            'error'  => mysqli_error($conn)
        ];
        $fail_count++;
    }
}

echo json_encode([
    'status'        => 'success',
    'success_count' => $success_count,
    'fail_count'    => $fail_count,
    'results'       => $results
]);
?>