<?php

namespace App\Http\Controllers\Admin\Finance;

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

class CashController extends Controller
{
    use UploadAttachment;

    public function index(): View
    {
        return view('pages.admin.finance.cashes', [
            'pageTitle' => 'Kas',
            'cashes' => Cash::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(CashRequest $request): RedirectResponse
    {
        $validatedData = $request->validated();
        $barbershopId = Auth::user()->barbershop_id;
        $barbershop = Barbershop::findOrFail($barbershopId);

        DB::transaction(function () use ($validatedData, $barbershop) {
            Cash::create(array_merge($validatedData, [
                'user_id' => Auth::id(),
                'barbershop_id' => Auth::user()->barbershop_id,
            ]));
            $barbershop->increment('cash', $validatedData['amount']);
        });

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

        return back();
    }

    public function update(CashRequest $request, Cash $cash): RedirectResponse
    {
        $validatedData = $request->validated();
        $barbershop = Barbershop::findOrFail($cash->barbershop_id);

        DB::transaction(function () use ($validatedData, $cash, $barbershop) {
            $barbershop->decrement('cash', $cash->amount);

            $cash->update($validatedData);

            $barbershop->increment('cash', $validatedData['amount']);
        });

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

        return back();
    }

    public function delete(Cash $cash): RedirectResponse
    {
        $barbershop = Barbershop::findOrFail($cash->barbershop_id);
        DB::transaction(function () use ($cash, $barbershop) {
            $barbershop->decrement('cash', $cash->amount);
            $cash->delete();
        });

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

        return back();
    }
}
