<?php

namespace Modules\Payroll\Services;

use App\Models\ActivityLogModel;
use App\Models\PayrollSettingsModel;

class PayrollSettingsService
{
    protected PayrollSettingsModel $settings;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->settings = new PayrollSettingsModel();
        $this->activity = new ActivityLogModel();
    }

    public function get(): array
    {
        return $this->settings->getSettings();
    }

    public function update(array $input, ?int $actingUserId): array
    {
        $row   = $this->settings->getSettings();
        $data  = $this->mapInput($input);

        $this->settings->update((int) $row['id'], $data);
        $this->activity->log(
            'payroll_settings',
            'updated',
            $actingUserId,
            'Updated payroll settings (Bahrain statutory rates)',
            (string) $row['id']
        );

        return ['success' => true];
    }

    protected function mapInput(array $input): array
    {
        return [
            'sio_cap_amount'             => (float) ($input['sio_cap_amount'] ?? 4000),
            'sio_bahraini_employer_rate' => (float) ($input['sio_bahraini_employer_rate'] ?? 18),
            'sio_bahraini_employee_rate' => (float) ($input['sio_bahraini_employee_rate'] ?? 8),
            'sio_expat_employer_rate'    => (float) ($input['sio_expat_employer_rate'] ?? 3),
            'sio_expat_employee_rate'    => (float) ($input['sio_expat_employee_rate'] ?? 1),
            'eosb_rate_first_3_years'    => (float) ($input['eosb_rate_first_3_years'] ?? 4.2),
            'eosb_rate_after_3_years'    => (float) ($input['eosb_rate_after_3_years'] ?? 8.4),
            'eosb_effective_date'        => $input['eosb_effective_date'] ?? '2024-03-01',
            'working_days_per_month'     => (int) ($input['working_days_per_month'] ?? 26),
            'daily_work_hours'           => (float) ($input['daily_work_hours'] ?? 8),
            'overtime_day_multiplier'    => (float) ($input['overtime_day_multiplier'] ?? 1.25),
            'overtime_night_multiplier'  => (float) ($input['overtime_night_multiplier'] ?? 1.50),
            'payment_day'                => (int) ($input['payment_day'] ?? 25),
            'wps_employer_id'            => trim((string) ($input['wps_employer_id'] ?? '')) ?: null,
        ];
    }
}
