<?php

namespace App\Http\Controllers\Admin;

use App\Models\BusinessExpense;
use Illuminate\Http\Request;
use Brian2694\Toastr\Facades\Toastr;
use App\Http\Controllers\Controller;

class BusinessExpenseController extends Controller
{
    public function index(Request $request)
    {
        $expenses = BusinessExpense::query()
            ->when($request->search, function ($query) use ($request) {
                $key = trim($request->search);
                $query->where(function ($subQuery) use ($key) {
                    $subQuery->where('reference', 'like', "%{$key}%")
                        ->orWhere('note', 'like', "%{$key}%")
                        ->orWhere('category', 'like', "%{$key}%");
                });
            })
            ->when($request->category && $request->category !== 'all', function ($query) use ($request) {
                $query->where('category', $request->category);
            })
            ->when($request->filled('from') && $request->filled('to'), function ($query) use ($request) {
                $query->whereBetween('expense_date', [$request->from, $request->to]);
            })
            ->latest('expense_date')
            ->latest('id')
            ->paginate(config('default_pagination'))
            ->withQueryString();

        $categories = BusinessExpense::categoryOptions();

        return view('admin-views.business-expense.index', compact('expenses', 'categories'));
    }

    public function create()
    {
        $categories = BusinessExpense::categoryOptions();

        return view('admin-views.business-expense.create', compact('categories'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'expense_date' => 'required|date',
            'category' => 'required|string|in:' . implode(',', array_keys(BusinessExpense::categoryOptions())),
            'amount' => 'required|numeric|min:0.01',
            'reference' => 'nullable|string|max:191',
            'note' => 'nullable|string',
        ]);

        BusinessExpense::create([
            'expense_date' => $request->expense_date,
            'category' => $request->category,
            'amount' => $request->amount,
            'reference' => $request->reference,
            'note' => $request->note,
            'created_by_admin_id' => auth('admin')->id(),
        ]);

        Toastr::success(translate('Business expense added successfully.'));
        return redirect()->route('admin.business-expense.index');
    }
}
