<?php

namespace App\Services\Admin\Finance\Payroll;

use App\Concerns\HasRoleChecks;
use App\Enums\CashTransactionType;
use App\Enums\PayrollPeriodStatus;
use App\Enums\PayrollStatus;
use App\Enums\Role;
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\Facades\DB;
use Illuminate\Validation\ValidationException;

class PayrollPeriodService
{
    use HandlesCashTransactions, HasRoleChecks;

    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'])
            ->when(! self::hasAnyRole([Role::DEVELOPER, Role::OWNER, Role::DIREKTUR, Role::ADMIN_TOKO]), function ($query) {
                $query->withCount(['payrolls as payrolls_count' => fn ($q) => $q->whereHas('employee', fn ($eq) => $eq->where('user_id', auth()->id()))])
                    ->withSum(['payrolls as payrolls_sum_total_amount' => fn ($q) => $q->whereHas('employee', fn ($eq) => $eq->where('user_id', auth()->id()))], 'total_amount')
                    ->withSum(['payrolls as payrolls_sum_bonus_amount' => fn ($q) => $q->whereHas('employee', fn ($eq) => $eq->where('user_id', auth()->id()))], 'bonus_amount')
                    ->withSum(['payrolls as payrolls_sum_deduction_amount' => fn ($q) => $q->whereHas('employee', fn ($eq) => $eq->where('user_id', auth()->id()))], 'deduction_amount')
                    ->withCount(['payrolls as paid_count' => fn ($q) => $q->paid()->whereHas('employee', fn ($eq) => $eq->where('user_id', auth()->id()))])
                    ->withCount(['payrolls as cancelled_count' => fn ($q) => $q->cancelled()->whereHas('employee', fn ($eq) => $eq->where('user_id', auth()->id()))]);
            })
            ->when(self::hasAnyRole([Role::DEVELOPER, Role::OWNER, Role::DIREKTUR, Role::ADMIN_TOKO]), function ($query) {
                $query->withCount('payrolls')
                    ->withSum('payrolls', 'total_amount')
                    ->withSum('payrolls', 'bonus_amount')
                    ->withSum('payrolls', 'deduction_amount')
                    ->withCount(['payrolls as paid_count' => fn ($q) => $q->paid()])
                    ->withCount(['payrolls as cancelled_count' => fn ($q) => $q->cancelled()]);
            })
            ->when($search, fn ($q) => $q->where('year', 'like', "%{$search}%"))
            ->orderBy($sort, $direction)
            ->paginate($perPage);
    }

    public function getCurrentOrCreate(): PayrollPeriod
    {
        $now = now();
        $cuttingDay = 5;

        if ($now->day < $cuttingDay) {
            $year = $now->year;
            $month = $now->month;
        } else {
            $year = $now->year;
            $month = $now->month + 1;
            if ($month > 12) {
                $month = 1;
                $year++;
            }
        }

        return PayrollPeriod::firstOrCreate(
            ['year' => $year, 'month' => $month],
            ['status' => PayrollPeriodStatus::OPEN]
        );
    }

    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->debitCash(
                amount: $payroll->total_amount,
                description: 'Pembayaran gaji karyawan',
                type: CashTransactionType::EXPENSE,
            );

            $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: [Role::OWNER, Role::DEVELOPER, Role::DIREKTUR, Role::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: [Role::OWNER, Role::DEVELOPER, Role::DIREKTUR, Role::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;
    }
}
