<?php

namespace App\Http\Controllers;

use App\Models\Account;
use App\Models\Transfer;
use App\Http\Requests\StoreTransferRequest;
use Illuminate\Http\Request;

class TransferController extends Controller
{
    /**
     * Display a listing of transfers.
     */
    public function index(Request $request)
    {
        $user = $request->user();

        $query = Transfer::where('user_id', $user->id)
            ->with(['fromAccount', 'toAccount']);

        // Apply filters
        if ($request->filled('account_id')) {
            $query->where(function ($q) use ($request) {
                $q->where('from_account_id', $request->account_id)
                  ->orWhere('to_account_id', $request->account_id);
            });
        }

        if ($request->filled('date_from')) {
            $query->where('date', '>=', $request->date_from);
        }

        if ($request->filled('date_to')) {
            $query->where('date', '<=', $request->date_to);
        }

        $transfers = $query->orderBy('date', 'desc')
            ->orderBy('created_at', 'desc')
            ->paginate(25)
            ->withQueryString();

        $accounts = $user->activeAccounts()->get();

        return view('transfers.index', compact('transfers', 'accounts'));
    }

    /**
     * Show the form for creating a new transfer.
     */
    public function create(Request $request)
    {
        $accounts = $request->user()
            ->activeAccounts()
            ->with('currency')
            ->get();

        return view('transfers.create', compact('accounts'));
    }

    /**
     * Store a newly created transfer.
     */
    public function store(StoreTransferRequest $request)
    {
        $data = $request->validated();
        $data['user_id'] = $request->user()->id;

        // Set default time if not provided
        if (empty($data['time'])) {
            $data['time'] = now()->format('H:i:s');
        } elseif (strlen($data['time']) === 5) {
            $data['time'] = $data['time'] . ':00';
        }

        // If to_amount not provided, use same as amount (same currency)
        if (!isset($data['to_amount'])) {
            $data['to_amount'] = $data['amount'];
        }

        // Calculate exchange rate if different currencies
        $fromAccount = Account::find($data['from_account_id']);
        $toAccount = Account::find($data['to_account_id']);

        if ($fromAccount->currency_id !== $toAccount->currency_id && $data['amount'] > 0) {
            $data['exchange_rate'] = $data['to_amount'] / $data['amount'];
        }

        Transfer::create($data);

        return redirect()->route('transfers.index')
            ->with('success', 'Transfer created successfully.');
    }

    /**
     * Display the specified transfer.
     */
    public function show(Transfer $transfer)
    {
        // Authorization handled by route model binding in AppServiceProvider
        $transfer->load(['fromAccount.currency', 'toAccount.currency']);

        return view('transfers.show', compact('transfer'));
    }

    /**
     * Remove the specified transfer.
     */
    public function destroy(Transfer $transfer)
    {
        // Authorization handled by route model binding in AppServiceProvider
        $transfer->delete();

        return redirect()->route('transfers.index')
            ->with('success', 'Transfer deleted successfully.');
    }

    /**
     * Get exchange rate for currency pair (AJAX).
     */
    public function getExchangeRate(Request $request)
    {
        $fromAccountId = $request->get('from_account_id');
        $toAccountId = $request->get('to_account_id');

        $fromAccount = Account::with('currency')->find($fromAccountId);
        $toAccount = Account::with('currency')->find($toAccountId);

        if (!$fromAccount || !$toAccount) {
            return response()->json(['error' => 'Invalid accounts'], 400);
        }

        // For now, return 1 as default exchange rate
        // In the future, this could fetch from an API
        $rate = 1;
        $sameCurrency = $fromAccount->currency_id === $toAccount->currency_id;

        return response()->json([
            'rate' => $rate,
            'same_currency' => $sameCurrency,
            'from_currency' => $fromAccount->currency,
            'to_currency' => $toAccount->currency,
        ]);
    }
}
