<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Transaction;
use Illuminate\Http\Request;

class ExpenseController extends Controller
{
    public function index(Request $request)
    {
        $query = Transaction::where('type', 'EXPENSE')
            ->when($request->search, function ($q, $search) {
                $q->where('description', 'like', "%{$search}%")->orWhere('transaction_id', 'like', "%{$search}%");
            })->when($request->category && $request->category !== 'all', function ($q) use ($request) {
                $q->where('category', $request->category);
            });

        $expenses = $query->latest()->paginate(15);

        $stats = [
            'total' => Transaction::where('type', 'EXPENSE')->sum('amount'),
            'this_month' => Transaction::where('type', 'EXPENSE')->whereMonth('created_at', now()->month)->sum('amount'),
            'count' => Transaction::where('type', 'EXPENSE')->count(),
        ];

        return view('admin.expenses.index', compact('expenses', 'stats'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'description' => 'required|string|max:500',
            'amount' => 'required|numeric|min:0.01',
            'category' => 'required|string',
            'payment_method' => 'required|string',
            'date' => 'required|date',
            'notes' => 'nullable|string',
        ]);

        Transaction::create([
            'transaction_id' => 'EXP-'.now()->format('Ymd').'-'.strtoupper(\Illuminate\Support\Str::random(6)),
            'type' => 'EXPENSE',
            'description' => $validated['description'],
            'amount' => $validated['amount'],
            'category' => $validated['category'],
            'payment_method' => $validated['payment_method'],
            'status' => 'COMPLETED',
            'currency' => 'EGP',
            'notes' => $validated['notes'],
            'branch_id' => auth()->user()->branch_id ?? null,
        ]);

        return back()->with('success', 'Expense recorded successfully.');
    }
}
