<?php

namespace App\Http\Controllers;

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

class ExpenseController extends Controller
{
    public function index(Request $request)
    {
        $query = Expense::with(['category', 'creator']);

        if ($request->filled('category_id')) {
            $query->where('expense_category_id', $request->category_id);
        }

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

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

        if ($request->filled('search')) {
            $query->where('description', 'like', '%' . $request->search . '%');
        }

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

        $this->ensureBahanBakuCategoryExists();

        $categories = ExpenseCategory::active()->orderBy('name')->get();

        $totalExpense = (clone $query)->sum('amount');

        return view('pages.expenses.index', [
            'title' => 'Data Pengeluaran',
            'expenses' => $expenses,
            'categories' => $categories,
            'totalExpense' => $totalExpense,
        ]);
    }

    public function create()
    {
        $this->ensureBahanBakuCategoryExists();

        $categories = ExpenseCategory::active()->orderBy('name')->get();

        return view('pages.expenses.form', [
            'title' => 'Tambah Pengeluaran',
            'expense' => new Expense(),
            'categories' => $categories,
        ]);
    }

    public function store(Request $request)
    {
        $request->merge([
            'amount' => str_replace('.', '', $request->amount ?? '0'),
        ]);

        $validated = $request->validate([
            'expense_category_id' => 'required|exists:expense_categories,id',
            'amount' => 'required|numeric|min:1',
            'expense_date' => 'required|date',
            'description' => 'nullable|string|max:500',
        ]);

        $validated['created_by'] = Auth::id();

        DB::transaction(function () use ($validated) {
            Expense::create($validated);
        });

        return redirect()->route('expenses.index')
            ->with('success', 'Pengeluaran berhasil ditambahkan.');
    }

    public function edit(Expense $expense)
    {
        $this->ensureBahanBakuCategoryExists();

        $categories = ExpenseCategory::active()->orderBy('name')->get();

        return view('pages.expenses.form', [
            'title' => 'Edit Pengeluaran',
            'expense' => $expense,
            'categories' => $categories,
        ]);
    }

    public function update(Request $request, Expense $expense)
    {
        $request->merge([
            'amount' => str_replace('.', '', $request->amount ?? '0'),
        ]);

        $validated = $request->validate([
            'expense_category_id' => 'required|exists:expense_categories,id',
            'amount' => 'required|numeric|min:1',
            'expense_date' => 'required|date',
            'description' => 'nullable|string|max:500',
        ]);

        DB::transaction(function () use ($expense, $validated) {
            $expense->update($validated);
        });

        return redirect()->route('expenses.index')
            ->with('success', 'Pengeluaran berhasil diperbarui.');
    }

    public function destroy(Expense $expense)
    {
        DB::transaction(function () use ($expense) {
            $expense->delete();
        });

        return redirect()->route('expenses.index')
            ->with('success', 'Pengeluaran berhasil dihapus.');
    }

    private function ensureBahanBakuCategoryExists(): ExpenseCategory
    {
        return ExpenseCategory::firstOrCreate(
            ['name' => 'Bahan Baku'],
            ['is_active' => true]
        );
    }
}
