<?php

namespace App\Http\Controllers;

use App\Models\Transaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class TransactionController extends Controller
{
    public function show(Transaction $transaction)
    {
        try {
            // Ensure the user owns this transaction
            $accountIds = auth()->user()->accounts->pluck('id');
            if (!$accountIds->contains($transaction->account_id)) {
                abort(403);
            }

            $transaction->load('account');

            return view('transactions.show', compact('transaction'));
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return back()->with('alert', 'An error occurred.');
        }
    }

    public function index(Request $request)
    {
        try {
            $accountIds = auth()->user()->accounts->pluck('id');
            $query = Transaction::whereIn('account_id', $accountIds);

            if ($request->filled('type')) {
                $query->where('type', $request->type);
            }
            if ($request->filled('status')) {
                $query->where('status', $request->status);
            }
            if ($request->filled('account_id')) {
                $query->where('account_id', $request->account_id);
            }
            if ($request->filled('date_from')) {
                $query->whereDate('created_at', '>=', $request->date_from);
            }
            if ($request->filled('date_to')) {
                $query->whereDate('created_at', '<=', $request->date_to);
            }

            $transactions = $query->latest()->paginate(20)->withQueryString();

            return view('transactions.index', [
                'transactions' => $transactions,
                'accounts' => auth()->user()->accounts,
                'activePage' => 'accounts',
            ]);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return back()->with('alert', 'An error occurred.');
        }
    }

    public function export(Request $request)
    {
        try {
            $accountIds = auth()->user()->accounts->pluck('id');
            $transactions = Transaction::whereIn('account_id', $accountIds)->latest()->get();

            $csv = "Date,Description,Category,Type,Amount,Status,Reference\n";
            foreach ($transactions as $t) {
                $csv .= implode(',', [
                    $t->created_at->format('Y-m-d H:i'),
                    '"' . str_replace('"', '""', $t->description) . '"',
                    $t->category->value,
                    $t->type->value,
                    $t->amount,
                    $t->status->value,
                    $t->reference,
                ]) . "\n";
            }

            return response($csv, 200, [
                'Content-Type' => 'text/csv',
                'Content-Disposition' => 'attachment; filename="transactions.csv"',
            ]);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return back()->with('alert', 'An error occurred.');
        }
    }
}
