<?php

namespace App\Http\Controllers\Admin\Finance;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Finance\DebtRequest;
use App\Models\Barbershop;
use App\Models\Debt;
use App\Models\Transaction;
use App\Models\User;
use App\Traits\UploadAttachment;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class DebtController extends Controller
{
    use UploadAttachment;

    public function index(): View
    {
        return view('pages.admin.finance.debts', [
            'pageTitle' => 'Kasbon',
            'debts' => Debt::with(['user', 'user.biography'])
                ->when(in_array(auth()->user()->role_id, [4, 5]), function ($query) {
                    return $query->where('user_id', auth()->id());
                })
                ->latest()
                ->get(),
            'employees' => User::with('biography')->barbershop()->latest()->get(),
        ]);
    }

    public function store(DebtRequest $request): RedirectResponse
    {
        $validatedData = $request->validated();
        $barbershopId = Auth::user()->barbershop_id;
        $barbershop = Barbershop::findOrFail($barbershopId);
        $user = User::findOrFail($validatedData['employee']);

        if ($user->role_id === 4) {
            $transaction = Transaction::where('barbershop_id', $barbershopId)->where('is_paid', '0')->sum('total');
        } else {
            $transaction = Transaction::where('user_id', $user->id)->where('is_paid', '0')->sum('total');
        }

        $maxDebt = $user->base_salary + (0.5 * $transaction);

        if ($barbershop->cash < $validatedData['amount']) {
            notify()->error('Kas tidak cukup untuk melakukan transaksi ini', 'Gagal');

            return back()->withInput();
        }

        if ($validatedData['amount'] > $maxDebt) {
            notify()->error('Jumlah utang tidak boleh lebih dari gaji pokok + 50% dari transaksi. Maksimal utang: Rp '.number_format($maxDebt, 2), 'Gagal');

            return back()->withInput();
        }

        DB::transaction(function () use ($validatedData, $barbershop) {
            Debt::create([
                'user_id' => $validatedData['employee'],
                'amount' => $validatedData['amount'],
            ]);
            $barbershop->decrement('cash', $validatedData['amount']);
        });

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

        return back();
    }

    public function update(DebtRequest $request, Debt $debt): RedirectResponse
    {
        $validatedData = $request->validated();
        $barbershopId = Auth::user()->barbershop_id;
        $barbershop = Barbershop::findOrFail($barbershopId);
        $user = User::findOrFail($debt->user_id);

        if ($user->role_id == 4) {
            $transaction = Transaction::where('barbershop_id', $barbershopId)->where('is_paid', '0')->first();
        } else {
            $transaction = Transaction::where('user_id', $user->id)->where('is_paid', '0')->first();
        }

        $transactionAmount = $transaction ? $transaction->total : 0;
        $maxDebt = $user->base_salary + (0.5 * $transactionAmount);

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

        if ($amountDifference > 0 && $barbershop->cash < $amountDifference) {
            notify()->error('Kas tidak cukup untuk menambah jumlah utang', 'Gagal');

            return back()->withInput();
        }

        if ($validatedData['amount'] > $maxDebt) {
            notify()->error('Jumlah utang tidak boleh lebih dari gaji pokok + 50% dari transaksi. Maksimal utang: Rp '.number_format($maxDebt, 2), 'Gagal');

            return back()->withInput();
        }

        DB::transaction(function () use ($validatedData, $debt, $barbershop, $amountDifference) {
            $debt->update([
                'amount' => $validatedData['amount'],
            ]);

            if ($amountDifference !== 0) {
                $barbershop->decrement('cash', $amountDifference);
            }
        });

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

        return back();
    }

    public function delete(Debt $debt): RedirectResponse
    {
        $barbershopId = Auth::user()->barbershop_id;
        $barbershop = Barbershop::findOrFail($barbershopId);

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

            $debt->delete();
        });

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

        return back();
    }
}
