<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Order;
use Illuminate\View\View;

class OrderController extends Controller
{
    public function index(Request $request): View
    {
        $query = Order::with(['user', 'aiTradeBot']);

        if ($request->has('status')) {
            $query->where('status', $request->get('status'));
        }

        // Per page - default 10, allow 10, 20, 50, 100
        $perPage = $request->get('per_page', 10);
        if (!in_array($perPage, [10, 20, 50, 100])) {
            $perPage = 10;
        }

        $orders = $query->latest()->paginate($perPage)->withQueryString();

        return view('admin.orders.index', [
            'orders' => $orders,
            'pageTitle' => 'Orders/Trades',
            'title' => 'Order Management'
        ]);
    }

    public function show($id): View
    {
        $order = Order::with(['user', 'aiTradeBot'])->findOrFail($id);

        return view('admin.orders.show', [
            'order' => $order,
            'pageTitle' => 'Order Details',
            'title' => 'Order #' . $order->id
        ]);
    }

    public function adjustProfitLoss(Request $request, $id): \Illuminate\Http\RedirectResponse
    {
        $order = Order::findOrFail($id);

        $validated = $request->validate([
            'admin_adjusted_profit_loss' => 'required|numeric',
            'admin_adjustment_reason' => 'required|string|max:500',
        ]);

        $order->update([
            'admin_adjusted_profit_loss' => $validated['admin_adjusted_profit_loss'],
            'admin_adjustment_reason' => $validated['admin_adjustment_reason'],
            'adjusted_by' => session('admin.user_id'),
            'admin_adjusted_at' => now(),
        ]);

        \App\Models\AuditLog::create([
            'admin_user_id' => session('admin.user_id'),
            'action' => 'order_adjust_profit_loss',
            'model_type' => Order::class,
            'model_id' => $order->id,
            'changes' => json_encode([
                'old_profit_loss' => $order->profit_loss,
                'new_profit_loss' => $validated['admin_adjusted_profit_loss'],
            ]),
            'reason' => $validated['admin_adjustment_reason'],
        ]);

        return redirect()->back()->with('success', 'Profit/Loss adjusted');
    }

    public function adjustTradeTime(Request $request, $id): \Illuminate\Http\RedirectResponse
    {
        $order = Order::findOrFail($id);

        $validated = $request->validate([
            'admin_adjusted_executed_at' => 'required|date',
            'admin_adjustment_reason' => 'required|string|max:500',
        ]);

        $order->update([
            'admin_adjusted_executed_at' => $validated['admin_adjusted_executed_at'],
            'admin_adjustment_reason' => $validated['admin_adjustment_reason'],
            'adjusted_by' => session('admin.user_id'),
            'admin_adjusted_at' => now(),
        ]);

        \App\Models\AuditLog::create([
            'admin_user_id' => session('admin.user_id'),
            'action' => 'order_adjust_trade_time',
            'model_type' => Order::class,
            'model_id' => $order->id,
            'changes' => json_encode([
                'old_executed_at' => $order->executed_at,
                'new_executed_at' => $validated['admin_adjusted_executed_at'],
            ]),
            'reason' => $validated['admin_adjustment_reason'],
        ]);

        return redirect()->back()->with('success', 'Trade time adjusted');
    }
}
