<?php

namespace App\Livewire;

use Livewire\Component;
use Livewire\WithPagination;
use App\Models\Order;
use Carbon\Carbon;
use App\Models\Transaction;

class AdminOrders extends Component
{
    use WithPagination;

    public $search = '';
    public $sortField = 'id';
    public $sortDirection = 'desc';
    public $editingOrder = null;
    public $deletingOrder = null;
    public $showEditModal = false;
    public $showDeleteModal = false;
    public $perPage = 10;
    
    // Editable fields
    public $editVolume;
    public $editTakeProfit;
    public $editStopLoss;
    public $editOpenPrice;
    public $editOpenTime;
    public $editClosePrice;
    public $editCloseTime;
    public $editFee;

    protected $queryString = ['search', 'sortField', 'sortDirection'];
    
    // Tell Livewire to use Bootstrap pagination theme
    protected $paginationTheme = 'bootstrap';

    // Reset pagination when search changes
    public function updatingSearch()
    {
        $this->resetPage();
    }

    // Reset pagination when per page changes
    public function updatingPerPage()
    {
        $this->resetPage();
    }

    protected $rules = [
        'editVolume' => 'required|numeric|min:0.1',
        'editTakeProfit' => 'nullable|numeric|min:0',
        'editStopLoss' => 'nullable|numeric|min:0',
        'editOpenPrice' => 'required|numeric|min:0',
        'editOpenTime' => 'required|date',
        'editClosePrice' => 'nullable|numeric|min:0',
        'editCloseTime' => 'nullable|date',
        'editFee' => 'required|numeric|min:0',
    ];

    public function sortBy($field)
    {
        if ($this->sortField === $field) {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortDirection = 'asc';
        }
        $this->sortField = $field;
    }

    public function closeOrder($orderId)
    {
        $order = Order::findOrFail($orderId);
        if (auth()->user()->hasRole('manager')) {
            $managedUsers = auth()->user()->managedUsers;
            if(!$managedUsers->contains($order->user_id)) {
                return;
            }
        }
        
        if ($order->status == 'open') {
            $order->close();
            session()->flash('message', 'Order closed successfully.');
        }
    }

    public function editOrder($orderId)
    {
        $this->editingOrder = Order::findOrFail($orderId);
        if (auth()->user()->hasRole('manager')) {
            $managedUsers = auth()->user()->managedUsers;
            if(!$managedUsers->contains($this->editingOrder->user_id)) {
                $this->editingOrder = null;
            }
        }
        if ($this->editingOrder) {
            $this->editVolume = $this->editingOrder->volume;
            $this->editTakeProfit = $this->editingOrder->take_profit;
            $this->editStopLoss = $this->editingOrder->stop_loss;
            $this->editOpenPrice = $this->editingOrder->open_price;
            $this->editOpenTime = $this->editingOrder->open_time->format('Y-m-d\TH:i');
            $this->editFee = $this->editingOrder->fee;
            

            if ($this->editingOrder->status == 'closed') {
                $this->editClosePrice = $this->editingOrder->close_price;
                $this->editCloseTime = $this->editingOrder->close_time ? $this->editingOrder->close_time->format('Y-m-d\TH:i') : null;
            }
        }

        $this->showEditModal = true;
    }

    public function updateOrder()
    {
        $this->validate();

        if ($this->editingOrder) {
            $updateData = [
                'volume' => $this->editVolume,
                'take_profit' => $this->editTakeProfit,
                'stop_loss' => $this->editStopLoss,
                'open_price' => $this->editOpenPrice,
                'open_time' => Carbon::parse($this->editOpenTime),
                'fee' => $this->editFee,
            ];

            if ($this->editingOrder->status == 'closed') {
                $updateData['close_price'] = $this->editClosePrice;
                if ($this->editCloseTime) {
                    $updateData['close_time'] = Carbon::parse($this->editCloseTime);
                }
            }

            $this->editingOrder->update($updateData);

            if ($this->editingOrder->status == 'closed') {
                $transaction = Transaction::where('order_id', $this->editingOrder->id)->where('type', 'close_position')->first();
                $transaction->amount = $this->editingOrder->calculateProfitLoss();
                $transaction->save();
            }

            session()->flash('message', 'Order updated successfully.');
            $this->closeModal();
        }
    }

    public function closeModal()
    {
        $this->showEditModal = false;
        $this->editingOrder = null;
        $this->reset(['editVolume', 'editTakeProfit', 'editStopLoss', 'editOpenPrice', 
                     'editOpenTime', 'editClosePrice', 'editCloseTime', 'editFee']);
    }

    public function deleteOrder($orderId)
    {
        $order = Order::findOrFail($orderId);
        if (auth()->user()->hasRole('manager')) {
            $managedUsers = auth()->user()->managedUsers;
            if(!$managedUsers->contains($order->user_id)) {
                return;
            }
        }
        $order->delete();
        session()->flash('message', 'Order deleted successfully.');
    }

    public function render()
    {
        if (auth()->user()->hasRole('admin')) {
            $query = Order::query();
        } else {
            $managedUsers = auth()->user()->managedUsers;
            $query = Order::whereIn('user_id', $managedUsers->pluck('id'));
        }
        
        if ($this->search) {
            $query->whereHas('user', function($q) {
                $q->where('name', 'like', '%' . $this->search . '%');
            })->orWhereHas('currency', function($q) {
                $q->where('name', 'like', '%' . $this->search . '%');
            })->orWhere('id', 'like', '%' . $this->search . '%')
              ->orWhere('side', 'like', '%' . $this->search . '%')
              ->orWhere('status', 'like', '%' . $this->search . '%');
        }
        
        $query->orderBy($this->sortField, $this->sortDirection);

        return view('livewire.admin-orders', [
            'orders' => $query->paginate($this->perPage),
        ]);
    }
} 