<?php

namespace App\Http\Controllers;

use App\Models\ExpenseCategory;
use App\Models\ExpensesModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class ExpensesController extends Controller
{
    public function index()
    {
        $expenses = ExpensesModel::where('branch_id', session('branch_id'))->orderBy('id', 'desc')->get();

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

    public function add()
    {
        $expense_category = ExpenseCategory::get();

        return view('expenses.add', compact('expense_category'));

    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'expense_category_id' => 'required',
            'expense_name' => 'required',
            'expense_amount' => 'required|numeric',
            'expense_date' => 'required|date',
            'attachment' => 'nullable|file',
        ]);
        DB::beginTransaction();

        try {
            $categoryID = '';
            if ($request->expense_category_id) {
                $category = ExpenseCategory::find($request->expense_category_id);
                if (!empty($category)) {
                    $categoryID = $category->id;
                } else {
                    $cat = ExpenseCategory::create([
                        'category_name' => $request->expense_category_id
                    ]);
                    $categoryID = $cat->id;
                }
            }

            $attachmentPath = null;
            if ($request->hasFile('attachment')) {
                $attachmentPath = storeFile($request->file('attachment'), 'expense');
            }

            ExpensesModel::create([
                'expense_category_id' => $categoryID,
                'expense_name' => $validated['expense_name'],
                'expense_amount' => $validated['expense_amount'],
                'expense_date' => $validated['expense_date'],
                'expense_attachment' => $attachmentPath,
                'branch_id' => session('branch_id'),
                'created_by' => Auth::user()->id,
            ]);

            DB::commit();

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

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Failed to store expense: ' . $e->getMessage());
            return redirect()->route('expense-index')
                ->with('error', 'Failed to add expense. Please try again.');
        }
    }

    public function edit($id)
    {
        $expense = ExpensesModel::findOrFail($id);
        $expense_category = ExpenseCategory::get();

        return view('expenses.edit', compact('expense', 'expense_category'));
    }

    public function update(Request $request)
    {
        DB::beginTransaction();

        try {
            $validated = $request->validate([
                'id' => 'required',
                'expense_category_id' => 'required',
                'expense_name' => 'required',
                'expense_amount' => 'required|numeric',
                'expense_date' => 'required|date',
                'attachment' => 'nullable|file',
            ]);

            $expense = ExpensesModel::findOrFail($validated['id']);

            if ($request->hasFile('attachment')) {
                $attachmentPath = storeFile($request->file('attachment'), 'expense');

                if ($expense->expense_attachment && Storage::disk('s3')->exists($expense->expense_attachment)) {
                    Storage::disk('s3')->delete($expense->expense_attachment);
                }

            } else {
                $attachmentPath = $expense->expense_attachment;
            }

            $expense->update([
                'expense_category_id' => $validated['expense_category_id'],
                'expense_name' => $validated['expense_name'],
                'expense_amount' => $validated['expense_amount'],
                'expense_date' => $validated['expense_date'],
                'expense_attachment' => $attachmentPath,
                'updated_by' => Auth::user()->id,
            ]);

            DB::commit();

            return redirect()->route('expense-index')
                ->with('success', 'Expense updated successfully');

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Failed to update expense: ' . $e->getMessage());
            return redirect()->route('expense-index')
                ->with('error', 'Failed to update expense. Please try again.');
        }
    }

    public function delete($id)
    {
        DB::beginTransaction();

        try {
            $expense = ExpensesModel::findOrFail($id);

            if ($expense->expense_attachment && Storage::disk('s3')->exists($expense->expense_attachment)) {
                Storage::disk('s3')->delete($expense->expense_attachment);
            }

            $expense->delete();

            DB::commit();

            return redirect()->route('expense-index')
                ->with('success', 'Expense deleted successfully');

        } catch (\Exception $e) {
            DB::rollBack();

            \Log::error("Failed to delete expense: " . $e->getMessage());

            return redirect()->route('expense-index')
                ->with('error', 'Failed to delete expense. Please try again.');
        }
    }
}