<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Trade;
use Illuminate\Http\Request;

class AdminTradeController extends Controller
{
    public function index(Request $request)
    {
        $query = Trade::with('user');

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('asset')) {
            $query->where('asset_symbol', 'like', '%' . $request->asset . '%');
        }
        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        $trades = $query->latest()->paginate(25)->withQueryString();

        return view('admin.trades.index', compact('trades'));
    }

    public function cancel($uuid)
    {
        $trade = Trade::where('uuid', $uuid)
            ->whereIn('status', ['active', 'pending'])
            ->firstOrFail();

        $user = $trade->user;

        $field = ($trade->account_type ?? 'demo') . '_balance';
        $user->increment($field, $trade->amount);

        $trade->update(['status' => 'cancelled', 'closed_at' => now()]);

        return back()->with('success', 'Trade cancelled and amount refunded.');
    }
}
