<?php

namespace App\Http\Controllers\Accounting;

use App\Http\Controllers\Controller;
use App\Models\FinancialTransaction;
use App\Models\FinancialTreasury;
use App\Models\FinancialCategory;
use App\Models\Currency;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ExpenseController extends Controller
{
    public function index(Request $request)
    {
        $query = FinancialTransaction::with(['treasury', 'category', 'user'])
            ->where('type', 'out') // Expenses are money out
            ->whereNull('model_type'); // General expenses aren't linked to Bills or Invoices

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

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

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

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

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

        $categories = FinancialCategory::where('type', 'expense')->get();
        $treasuries = FinancialTreasury::where('is_active', true)->get();

        // Stats
        $stats = [
            'total_amount' => (float) $query->sum('amount'),
            'count' => $query->count(),
        ];

        return view('accounting.expenses.index', compact('expenses', 'categories', 'treasuries', 'stats'));
    }

    public function create()
    {
        $categories = FinancialCategory::where('type', 'expense')->get();
        $treasuries = FinancialTreasury::where('is_active', true)->get();
        $baseCurrency = Currency::getBase();

        return view('accounting.expenses.create', compact('categories', 'treasuries', 'baseCurrency'));
    }

    use \App\Traits\HasLockCheck;

    public function store(Request $request)
    {
        $validated = $request->validate([
            'category_id' => 'required|exists:financial_categories,id',
            'treasury_id' => 'required|exists:financial_treasuries,id',
            'amount' => 'required|numeric|min:0.01',
            'date' => 'required|date',
            'description' => 'required|string|max:500',
            'ref_no' => 'nullable|string|max:100',
        ]);

        if ($this->isDateLocked($validated['date'])) {
            return back()->with('error', 'The selected date is locked for accounting.')->withInput();
        }

        try {
            DB::transaction(function () use ($validated) {
                $treasury = FinancialTreasury::findOrFail($validated['treasury_id']);

                if ($treasury->balance < $validated['amount']) {
                    throw new \Exception('Insufficient funds in the selected treasury.');
                }

                // Create Transaction
                FinancialTransaction::create([
                    'treasury_id' => $validated['treasury_id'],
                    'category_id' => $validated['category_id'],
                    'currency_id' => $treasury->currency_id ?? Currency::getBase()->id,
                    'amount' => $validated['amount'],
                    'type' => 'out', // Expense
                    'date' => $validated['date'],
                    'description' => $validated['description'],
                    'ref_no' => $validated['ref_no'],
                    'user_id' => auth()->id(),
                ]);

                // Update Treasury Balance
                $treasury->decrement('balance', $validated['amount']);
            });

            return redirect()->route('accounting.expenses.index')->with('success', 'Expense recorded successfully.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage())->withInput();
        }
    }

    public function destroy(FinancialTransaction $transaction)
    {
        // For general expenses, unlinked from models
        try {
            DB::transaction(function () use ($transaction) {
                // Revert Treasury Balance
                $treasury = $transaction->treasury;
                if ($treasury) {
                    $treasury->increment('balance', $transaction->amount);
                }
                $transaction->delete();
            });

            return back()->with('success', 'Expense deleted and balance reverted.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }
}
