<?php

namespace App\Http\Controllers\Admin\Finance;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Finance\PayrollRequest;
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;

class PayrollController extends Controller
{
    public function index(): View
    {
        return view('pages.admin.finance.payroll.index', [
            'pageTitle' => 'Gaji',
            'payrolls' => Payroll::latest()->get(),
        ]);
    }

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

    public function store(PayrollRequest $request): RedirectResponse
    {
        $validatedData = $request->validated();
        Payroll::create(array_merge($validatedData, [
            'user_id' => Auth::id(),
            'employee_id' => $validatedData['employee'],
            'barbershop_id' => Auth::user()->barbershop_id,
        ]));

        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::query()->barbershop()->latest()->get(),
            'payroll' => $payroll,
        ]);
    }

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

        $payroll->update($validatedData);

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

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

    public function delete(Payroll $payroll): RedirectResponse
    {
        $payroll->delete();

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

        return back();
    }

    public function getSalaryEmployee(string $employeeId): JsonResponse
    {
        $baseSalary = User::find($employeeId)->base_salary;
        $latestPayroll = Payroll::where('user_id', $employeeId)->latest()->first();
        $shavingResults = Transaction::where('user_id', $employeeId)
            ->when($latestPayroll, function ($query) use ($latestPayroll) {
                $query->whereBetween('created_at', [$latestPayroll->created_at, now()]);
            })
            ->sum('total');

        return response()->json([
            'status' => true,
            'message' => 'Data retrieved successfully',
            'data' => [
                'baseSalary' => formatToRupiah($baseSalary),
                'shavingResults' => formatToRupiah($shavingResults),
            ],
        ]);
    }
}
