<?php

namespace App\Http\Controllers\Admin\Finance;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Finance\PayrollRequest;
use App\Models\Barbershop;
use App\Models\Debt;
use App\Models\Payroll;
use App\Models\Transaction;
use App\Models\User;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class PayrollController extends Controller
{
    public function index(): View
    {
        return view('pages.admin.finance.payroll.index', [
            'pageTitle' => 'Gaji',
            'payrolls' => Payroll::with(['employee', 'employee.biography'])
                ->barbershop()
                ->when(in_array(auth()->user()->role_id, [4, 5]), function ($query) {
                    return $query->where('user_id', auth()->id())
                        ->orWhere('employee_id', auth()->id());
                })
                ->latest()
                ->get(),
        ]);
    }

    public function create(): View
    {
        return view('pages.admin.finance.payroll.create', [
            'pageTitle' => 'Tambah Gaji',
            'employees' => User::with('biography')->barbershop()->latest()->get(),
        ]);
    }

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

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

            $totalDebt = Debt::where('user_id', $validatedData['employee'])
                ->where('is_paid', '0')
                ->sum('amount');

            $barbershop = Barbershop::findOrFail($barbershopId);

            if ($validatedData['cut'] > $totalDebt) {
                $barbershop->increment('cash', $totalDebt);
            } elseif ($validatedData['cut'] <= $totalDebt) {
                $barbershop->increment('cash', $validatedData['cut']);
            }

            Debt::where('user_id', $validatedData['employee'])
                ->where('is_paid', '0')
                ->update(['is_paid' => '1']);
        });

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

        return redirect('dashboard/finance/payrolls');
    }

    public function edit(Payroll $payroll): View
    {
        return view('pages.admin.finance.payroll.edit', [
            'pageTitle' => 'Edit Gaji',
            'employees' => User::with('biography')->barbershop()->latest()->get(),
            'payroll' => $payroll,
        ]);
    }

    public function update(PayrollRequest $request, Payroll $payroll): RedirectResponse
    {
        $validatedData = $request->validated();
        $barbershopId = Auth::user()->barbershop_id;

        DB::transaction(function () use ($validatedData, $payroll, $barbershopId) {
            $oldCut = $payroll->cut;
            $newCut = $validatedData['cut'];
            $cutDifference = $newCut - $oldCut;

            $totalDebt = Debt::where('user_id', $payroll->employee)
                ->where('is_paid', '0')
                ->sum('amount');

            $payroll->update($validatedData);

            if ($cutDifference > 0) {
                $barbershop = Barbershop::findOrFail($barbershopId);

                if ($newCut > $totalDebt) {
                    $barbershop->increment('cash', $totalDebt);
                } elseif ($newCut <= $totalDebt) {
                    $barbershop->increment('cash', $newCut);
                }
            }
        });

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

        return redirect('dashboard/finance/payrolls');
    }

    public function delete(Payroll $payroll): RedirectResponse
    {
        $barbershopId = Auth::user()->barbershop_id;

        DB::transaction(function () use ($payroll, $barbershopId) {
            $cut = $payroll->cut;

            $totalDebt = Debt::where('user_id', $payroll->employee_id)
                ->where('is_paid', '0')
                ->sum('amount');

            $payroll->delete();

            $barbershop = Barbershop::findOrFail($barbershopId);

            if ($cut > $totalDebt) {
                $barbershop->increment('cash', $totalDebt);
            } elseif ($cut <= $totalDebt) {
                $barbershop->increment('cash', $cut);
            }
        });

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

        return redirect('dashboard/finance/payrolls');
    }

    public function getSalaryEmployee(string $employeeId): JsonResponse
    {
        $employee = User::find($employeeId);
        $latestPayroll = Payroll::where('employee_id', $employeeId)->latest()->first();

        $shavingResults = Transaction::query()
            ->when($employee->role_id === 4, function ($query) use ($employee) {
                return $query->where('barbershop_id', $employee->barbershop_id);
            })
            ->when($employee->role_id === 5, function ($query) use ($employeeId) {
                return $query->where('user_id', $employeeId)
                    ->where('is_paid', '0');
            })
            ->when($latestPayroll, function ($query) use ($latestPayroll, $employee) {
                $query->whereBetween('created_at', [$latestPayroll->created_at, now()]);
                if ($employee->role_id === 4 && $latestPayroll->created_at->isToday()) {
                    $query->where('is_paid', '0');
                }
            })
            ->sum('total');
        $debt = Debt::where('user_id', $employeeId)->where('is_paid', '0')->sum('amount');

        return response()->json([
            'status' => true,
            'message' => 'Data retrieved successfully',
            'data' => [
                'baseSalary' => formatToRupiah($employee->base_salary),
                'shavingResults' => in_array($employee->role_id, [4, 5]) ? formatToRupiah($shavingResults) : 'Rp0',
                'debt' => formatToRupiah($debt),
            ],
        ]);
    }
}
