<?php

namespace Modules\HR\Services;

use Illuminate\Support\Facades\DB;
use Modules\HR\DTO\HrSettingFilter;
use Modules\HR\Models\WeekendPolicy;
use Modules\HR\Repositories\WeekendPolicyRepository;

class WeekendPolicyService
{
    protected $weekendPolicyRepo;

    public function __construct(WeekendPolicyRepository $weekendPolicyRepo)
    {
        $this->weekendPolicyRepo = $weekendPolicyRepo;
    }

    public function list(HrSettingFilter $filter)
    {
        $columns = ['id', 'name', 'weekend_days', 'is_default', 'status'];
        return $this->weekendPolicyRepo->all($filter, $columns);
    }

    public function lookup(HrSettingFilter $filter)
    {
        $columns = ['id', 'name', 'status'];
        return $this->weekendPolicyRepo->all($filter, $columns);
    }

    public function show($id)
    {
        return $this->weekendPolicyRepo->find($id);
    }

    public function store(array $data)
    {
        return DB::transaction(function () use ($data) {
            if ($data['is_default']) {
                WeekendPolicy::where('is_default', true)->update(['is_default' => false]);
            }
            return $this->weekendPolicyRepo->create($data);
        });
    }

    public function update(WeekendPolicy $weekendPolicy, array $data)
    {
        return DB::transaction(function () use ($weekendPolicy, $data) {
            if ($data['is_default']) {
                WeekendPolicy::where('is_default', true)->update(['is_default' => false]);
            }
            return $this->weekendPolicyRepo->update($weekendPolicy, $data);
        });
    }

    public function updateStatus(WeekendPolicy $weekendPolicy, array $status)
    {
        return DB::transaction(function () use ($weekendPolicy, $status) {
            return $this->weekendPolicyRepo->updateStatus($weekendPolicy, $status);
        });
    }
}
