<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Transaction;
use App\Models\User;
use Livewire\WithPagination;

class AdminTransactions extends Component
{
    use WithPagination;

    public $showCreateModal = false;
    public $users = [];
    public $newTransaction = [
        'user_id' => '',
        'type' => 'deposit',
        'amount' => '',
        'description' => '',
        'to_address' => '',
    ];

    protected $paginationTheme = 'bootstrap';

    public function mount()
    {
        $this->loadUsers();
    }

    public function loadUsers()
    {
        if (auth()->user()->hasRole('admin')) {
            $this->users = User::orderBy('name')->get();
        } else {
            $this->users = auth()->user()->managedUsers;
        }
    }

    public function confirmTransaction($transactionId)
    {
        $transaction = Transaction::find($transactionId);

        if ($transaction && ($transaction->type == 'deposit' || $transaction->type == 'withdraw') && !$transaction->confirmed) {
            $transaction->update(['confirmed' => true]);
            session()->flash('success', 'Transaction #' . $transaction->id . ' confirmed successfully.');
        } else {
            session()->flash('error', 'Transaction cannot be confirmed or is not a deposit.');
        }
    }

    public function declineTransaction($transactionId)
    {
        $transaction = Transaction::find($transactionId);

        if ($transaction && ($transaction->type == 'deposit' || $transaction->type == 'withdraw') && !$transaction->confirmed) {
            $transaction->delete();
            session()->flash('success', 'Transaction #' . $transactionId . ' declined and deleted successfully.');
        } else {
            session()->flash('error', 'Transaction cannot be declined or is already confirmed.');
        }
    }

    public function openCreateModal()
    {
        $this->resetValidation();
        $this->reset('newTransaction');
        $this->newTransaction['type'] = 'deposit';
        $this->showCreateModal = true;
    }

    public function closeModal()
    {
        $this->showCreateModal = false;
    }

    public function createTransaction()
    {
        $this->validate([
            'newTransaction.user_id' => 'required|exists:users,id',
            'newTransaction.type' => 'required|in:deposit,withdraw',
            'newTransaction.amount' => 'required|numeric|min:0.00000001',
            'newTransaction.description' => 'nullable|string|max:255',
            'newTransaction.to_address' => $this->newTransaction['type'] === 'withdraw' ? 'required|string|max:255' : 'nullable|string|max:255',
        ]);
        $managedUsers = auth()->user()->managedUsers;
        if(auth()->user()->hasRole('manager') && !$managedUsers->contains($this->newTransaction['user_id'])) {
            session()->flash('error', 'You are not authorized to create transactions for this user.');
            return;
        }

        Transaction::create([
            'user_id' => $this->newTransaction['user_id'],
            'type' => $this->newTransaction['type'],
            'amount' => $this->newTransaction['amount'],
            'description' => $this->newTransaction['description'],
            'to_address' => $this->newTransaction['type'] === 'withdraw' ? $this->newTransaction['to_address'] : null,
            'confirmed' => true,
        ]);

        session()->flash('success', 'Transaction created successfully.');
        $this->showCreateModal = false;
    }

    public function render()
    {
        if (auth()->user()->hasRole('admin')) {
            $transactions = Transaction::with('user')
                ->whereIn('type', ['deposit', 'withdraw'])
                ->orderBy('created_at', 'desc')
                ->paginate(10);
        } else {
            $managedUsers = auth()->user()->managedUsers;
            $transactions = Transaction::with('user')
                ->whereIn('type', ['deposit', 'withdraw'])
                ->whereIn('user_id', $managedUsers->pluck('id'))
                ->orderBy('created_at', 'desc')
                ->paginate(10);
        }

        return view('livewire.admin-transactions', [
            'transactions' => $transactions,
        ]);
    }
}