<?php

namespace App\Http\Controllers\Admin\Finance;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Finance\ExpenseRequest;
use App\Models\Barbershop;
use App\Models\Expense;
use App\Traits\UploadAttachment;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class ExpenseController extends Controller
{
    use UploadAttachment;

    public function index(): View
    {
        return view('pages.admin.finance.expenses', [
            'pageTitle' => 'Pengeluaran',
            'expenses' => Expense::with(['user', 'user.biography'])
                ->barbershop()
                ->when(auth()->user()->role_id === 4, function ($query) {
                    return $query->where('user_id', auth()->id());
                })
                ->latest()
                ->get(),
        ]);
    }

    public function store(ExpenseRequest $request): RedirectResponse
    {
        $validatedData = $request->validated();
        $barbershopId = Auth::user()->barbershop_id;
        $barbershop = Barbershop::findOrFail($barbershopId);

        if ($validatedData['use_cash'] === '1' && $barbershop->cash < $validatedData['amount']) {
            notify()->error('Saldo kas tidak mencukupi', 'Gagal');

            return back()->withInput();
        }

        DB::transaction(function () use ($validatedData, $barbershop, $barbershopId) {
            $newExpense = Expense::create(array_merge($validatedData, [
                'user_id' => Auth::id(),
                'barbershop_id' => $barbershopId,
            ]));

            if ($validatedData['use_cash'] === '1') {
                $barbershop->decrement('cash', $validatedData['amount']);
            }

            $this->uploadAttachment($validatedData['proof'], 'expenses', Expense::class, $newExpense->id, 'expenses');
        });

        notify()->success('Data berhasil ditambahkan', 'Berhasil');

        return back();
    }

    public function update(ExpenseRequest $request, Expense $expense): RedirectResponse
    {
        $validatedData = $request->validated();
        $barbershop = Barbershop::findOrFail($expense->barbershop_id);

        $amountDifference = $validatedData['amount'] - $expense->amount;

        if ($validatedData['use_cash'] === '1') {
            $requiredCash = $barbershop->cash - ($amountDifference < 0 ? 0 : $amountDifference);
            if ($requiredCash < 0) {
                notify()->error('Saldo kas tidak mencukupi', 'Gagal');

                return back()->withInput();
            }
        }

        DB::transaction(function () use ($validatedData, $expense, $barbershop) {
            if ($expense->use_cash === '1') {
                $barbershop->increment('cash', $expense->amount);
            }

            $expense->update($validatedData);

            if ($validatedData['use_cash'] === '1') {
                $barbershop->decrement('cash', $validatedData['amount']);
            }

            if (isset($validatedData['proof'])) {
                $this->uploadAttachment($validatedData['proof'], 'expenses', Expense::class, $expense->id, 'expenses');
            }
        });

        notify()->success('Data berhasil diperbarui', 'Berhasil');

        return back();
    }

    public function delete(Expense $expense): RedirectResponse
    {
        $barbershop = Barbershop::findOrFail($expense->barbershop_id);

        DB::transaction(function () use ($expense, $barbershop) {
            if ($expense->use_cash === '1') {
                $barbershop->increment('cash', $expense->amount);
            }

            $expense->delete();
        });

        notify()->success('Data berhasil dihapus', 'Berhasil');

        return back();
    }
}
