<?php

namespace App\Http\Controllers;

use App\Models\Expense;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ExpenseController extends Controller
{
    public function index()
    {
        $user = Auth::user();

        if ($user->isFreePlan()) {
            return redirect()->route('subscription.index')
                ->with('error', 'Expense tracking is available on the Pro plan and above.');
        }

        $expenses = $user->expenses()->latest('date')->paginate(20);
        return view('expenses.index', compact('expenses'));
    }

    public function create()
    {
        if (Auth::user()->isFreePlan()) {
            return redirect()->route('settings.subscription')
                ->with('error', 'Upgrade to Pro to track expenses.');
        }
        return view('expenses.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'date'        => ['required', 'date'],
            'category'    => ['required', 'string'],
            'amount'      => ['required', 'numeric', 'min:0'],
            'description' => ['nullable', 'string', 'max:500'],
            'receipt'     => ['nullable', 'file', 'mimes:jpeg,png,jpg,pdf', 'max:2048'],
        ]);

        if ($request->hasFile('receipt')) {
            $data['receipt_path'] = $request->file('receipt')->store('receipts', 'public');
        }

        Auth::user()->expenses()->create($data);

        return redirect()->route('expenses.index')
            ->with('success', 'Expense added successfully.');
    }

    public function edit(Expense $expense)
    {
        abort_if($expense->user_id !== Auth::id(), 403);
        return view('expenses.edit', compact('expense'));
    }

    public function update(Request $request, Expense $expense)
    {
        abort_if($expense->user_id !== Auth::id(), 403);

        $data = $request->validate([
            'date'        => ['required', 'date'],
            'category'    => ['required', 'string'],
            'amount'      => ['required', 'numeric', 'min:0'],
            'description' => ['nullable', 'string', 'max:500'],
        ]);

        $expense->update($data);

        return redirect()->route('expenses.index')
            ->with('success', 'Expense updated.');
    }

    public function destroy(Expense $expense)
    {
        abort_if($expense->user_id !== Auth::id(), 403);
        $expense->delete();
        return back()->with('success', 'Expense deleted.');
    }

    public function summary()
    {
        $user     = Auth::user();
        $expenses = $user->expenses()
            ->selectRaw('category, SUM(amount) as total')
            ->groupBy('category')
            ->get();

        return view('expenses.summary', compact('expenses'));
    }
}