<?php

namespace App\Http\Controllers;

use App\Models\Transaction;
use App\Models\Account;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PendingTransactionController extends Controller
{
    public function index(Request $request)
    {
        $filters = $request->only(['search', 'agent_id', 'date_from', 'date_to']);

        $query = Transaction::with(['currency', 'account.currency', 'paymentCurrency', 'agent'])
            ->where('is_pending', true);

        if ($request->filled('search')) {
            $search = $request->input('search');
            $query->where(function($q) use ($search) {
                $q->where('description', 'like', "%{$search}%")
                  ->orWhere('type', 'like', "%{$search}%")
                  ->orWhereHas('agent', function($sq) use ($search) {
                      $sq->where('name', 'like', "%{$search}%");
                  })
                  ->orWhereHas('currency', function($sq) use ($search) {
                      $sq->where('code', 'like', "%{$search}%");
                  })
                  ->orWhereHas('account', function($sq) use ($search) {
                      $sq->where('name', 'like', "%{$search}%");
                  });
            });
        }

        if ($request->filled('agent_id')) {
            $query->where('agent_id', $request->input('agent_id'));
        }

        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->input('date_from'));
        }

        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->input('date_to'));
        }

        $transactions = $query->latest()->get();
        $agents = \App\Models\Agent::orderBy('name')->get();

        return view('transactions.pending', compact('transactions', 'agents', 'filters'));
    }

    public function markReceived(Transaction $transaction)
    {
        if (!$transaction->is_pending) {
            return back()->with('error', 'Transaction is already received.');
        }

        DB::transaction(function () use ($transaction) {
            // Find the receiving account
            if ($transaction->type === Transaction::TYPE_BUY) {
                // For BUY: The target account (account_id) receives quantity + handling_fee
                $targetAccount = Account::lockForUpdate()->findOrFail($transaction->account_id);
                $targetAccount->update([
                    'balance' => (float) $targetAccount->balance + (float) $transaction->quantity + (float) $transaction->handling_fee,
                ]);
            } elseif ($transaction->type === Transaction::TYPE_SELL) {
                // For SELL: The payment account (payment_account_id) receives payment_amount + handling_fee
                $targetAccount = Account::lockForUpdate()->findOrFail($transaction->payment_account_id);
                $targetAccount->update([
                    'balance' => (float) $targetAccount->balance + (float) $transaction->payment_amount + (float) $transaction->handling_fee,
                ]);
            }

            // Mark as completed
            $transaction->update([
                'is_pending' => false,
            ]);

            // Recalculate profits for this currency
            $transaction->currency->recalculateProfits();
        });

        return redirect()
            ->route('transactions.pending.index')
            ->with('success', 'Transaction marked as received successfully.');
    }
}
