<?php

namespace Modules\Payroll\Repositories;

use Modules\Payroll\DTO\PayrollCyclesFilter;
use Modules\Payroll\Enums\PayrollCyclesStatusEnum;
use Modules\Payroll\Models\PayrollCycle;

class PayrollCycleRepository
{
    public function all(PayrollCyclesFilter $filter, array $columns = ['*'])
    {
        return PayrollCycle::query()
            ->search($filter->search)
            ->filterByStatus($filter->status)
            ->dateRange($filter->from_date, $filter->to_date)
            ->orderBy('name')
            ->select($columns)
            ->paginate($filter->perPage ?? 15);
    }

    public function find($id)
    {
        return PayrollCycle::findOrFail($id);
    }

    public function create(array $data)
    {
        return PayrollCycle::create([
            'name'       => $data['name'],
            'month'      => $data['month'],
            'year'       => $data['year'],
            'from_date'  => $data['from_date'],
            'to_date'    => $data['to_date'],
            'salary_date' => $data['salary_date'],
            'remarks'    => $data['remarks'] ?? null,
            'status'     => $data['status'] ?? PayrollCyclesStatusEnum::DRAFT,
        ]);
    }

    public function update(PayrollCycle $payrollCycle, array $data)
    {
        $payrollCycle->update([
            'name'       => $data['name'],
            'month'      => $data['month'],
            'year'       => $data['year'],
            'from_date'  => $data['from_date'],
            'to_date'    => $data['to_date'],
            'salary_date' => $data['salary_date'],
            'remarks'    => $data['remarks'] ?? null,
            'status'     => $data['status'] ?? PayrollCyclesStatusEnum::DRAFT,
        ]);

        return $payrollCycle;
    }


    public function updateStatus(PayrollCycle $payrollCycle, array $status)
    {
        $payrollCycle->update([
            'status' => $status['status'] ?? PayrollCyclesStatusEnum::DRAFT,
        ]);

        return $payrollCycle;
    }
}
