<?php

namespace App\Services\Admin\Finance;

use App\Enums\PayrollPeriodStatus;
use App\Enums\PayrollStatus;
use App\Models\Payroll;
use App\Models\PayrollPeriod;
use App\Services\Concerns\HandlesCashTransactions;
use App\Services\NotificationService;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

class PayrollPeriodService
{
    use HandlesCashTransactions;

    public function getAll(array $filters = []): Collection
    {
        return PayrollPeriod::select('id', 'year', 'month', 'status', 'closed_at', 'created_at')
            ->withCount('payrolls')
            ->withSum('payrolls', 'total_amount')
            ->withSum('payrolls', 'bonus_amount')
            ->withSum('payrolls', 'deduction_amount')
            ->withCount(['payrolls as paid_count' => function ($q) {
                $q->paid();
            }])
            ->withCount(['payrolls as cancelled_count' => function ($q) {
                $q->cancelled();
            }])
            ->latest('year')
            ->latest('month')
            ->get();
    }

    public function paginated(int $perPage = 25, string $search = '', string $sort = 'created_at', string $direction = 'desc', array $filters = []): LengthAwarePaginator
    {
        return PayrollPeriod::query()
            ->select('id', 'year', 'month', 'status', 'closed_at', 'created_at')
            ->withCount('payrolls')
            ->withSum('payrolls', 'total_amount')
            ->withSum('payrolls', 'bonus_amount')
            ->withSum('payrolls', 'deduction_amount')
            ->withCount(['payrolls as paid_count' => function ($q) {
                $q->paid();
            }])
            ->withCount(['payrolls as cancelled_count' => function ($q) {
                $q->cancelled();
            }])
            ->when($search, fn ($q) => $q->where('year', 'like', "%{$search}%"))
            ->orderBy($sort, $direction)
            ->paginate($perPage);
    }

    public function getDetail(PayrollPeriod $period): PayrollPeriod
    {
        return $period->load([
            'payrolls' => function ($query) {
                $query->with(['employee.user.userProfile', 'payrollAdjustments'])
                    ->orderBy('id');
            },
        ]);
    }

    public function close(PayrollPeriod $period): PayrollPeriod
    {
        if ($period->status === PayrollPeriodStatus::CLOSED) {
            throw ValidationException::withMessages([
                'period' => 'Periode sudah ditutup.',
            ]);
        }

        $hasUnpaid = $period->payrolls()
            ->where('status', PayrollStatus::UNPAID)
            ->exists();

        if ($hasUnpaid) {
            throw ValidationException::withMessages([
                'period' => 'Masih ada gaji yang belum dibayar.',
            ]);
        }

        $period->update([
            'status' => PayrollPeriodStatus::CLOSED,
            'closed_by_id' => auth()->id(),
            'closed_at' => now(),
        ]);

        return $period;
    }

    public function reopen(PayrollPeriod $period): PayrollPeriod
    {
        if ($period->status === PayrollPeriodStatus::OPEN) {
            throw ValidationException::withMessages([
                'period' => 'Periode sudah terbuka.',
            ]);
        }

        $period->update([
            'status' => PayrollPeriodStatus::OPEN,
            'closed_by_id' => null,
            'closed_at' => null,
        ]);

        return $period;
    }

    public function pay(Payroll $payroll): Payroll
    {
        if ($payroll->status === PayrollStatus::PAID) {
            throw ValidationException::withMessages([
                'payroll' => 'Gaji sudah dibayar.',
            ]);
        }

        if ($payroll->status === PayrollStatus::CANCELLED) {
            throw ValidationException::withMessages([
                'payroll' => 'Gaji sudah dibatalkan.',
            ]);
        }

        $payroll = DB::transaction(function () use ($payroll) {
            $cashTransaction = $this->creditCash(
                amount: $payroll->total_amount,
                description: 'Pembayaran gaji karyawan',
            );

            $payroll->update([
                'status' => PayrollStatus::PAID,
                'cash_transaction_id' => $cashTransaction->id,
                'paid_by_id' => auth()->id(),
                'paid_at' => now(),
            ]);

            return $payroll;
        });

        $employeeUser = $payroll->employee->user ?? null;

        NotificationService::notify(
            roles: ['Owner', 'Developer', 'Direktur', 'Admin Toko'],
            title: 'Gaji Dibayar',
            body: "Gaji karyawan {$payroll->employee->name} sebesar {$payroll->formatted_amount} telah dibayar".' oleh '.auth()->user()->full_name.'.',
            url: route('admin.finance.payroll-periods.index'),
            additionalUser: $employeeUser,
        );

        return $payroll;
    }

    public function cancel(Payroll $payroll): Payroll
    {
        if ($payroll->status === PayrollStatus::PAID) {
            throw ValidationException::withMessages([
                'payroll' => 'Gaji yang sudah dibayar tidak dapat dibatalkan.',
            ]);
        }

        if ($payroll->status === PayrollStatus::CANCELLED) {
            throw ValidationException::withMessages([
                'payroll' => 'Gaji sudah dibatalkan.',
            ]);
        }

        $payroll->update([
            'status' => PayrollStatus::CANCELLED,
        ]);

        $employeeUser = $payroll->employee->user ?? null;

        NotificationService::notify(
            roles: ['Owner', 'Developer', 'Direktur', 'Admin Toko'],
            title: 'Gaji Dibatalkan',
            body: "Gaji karyawan {$payroll->employee->name} sebesar {$payroll->formatted_amount} telah dibatalkan".' oleh '.auth()->user()->full_name.'.',
            url: route('admin.finance.payroll-periods.index'),
            additionalUser: $employeeUser,
        );

        return $payroll;
    }
}
