<?php

namespace Modules\Leave\Services;

use App\Models\ActivityLogModel;
use App\Models\HolidayModel;

class HolidayService
{
    protected HolidayModel $holidays;
    protected ActivityLogModel $activity;

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

    public function create(array $input, ?int $actingUserId): array
    {
        $data = $this->mapInput($input, $actingUserId);
        $data['created_by'] = $actingUserId;
        $data['updated_by'] = $actingUserId;

        if (! $this->holidays->insert($data, true)) {
            return ['success' => false, 'errors' => $this->holidays->errors()];
        }

        $id = $this->holidays->getInsertID();
        $this->activity->log('holidays', 'created', $actingUserId, "Created holiday #{$id} ({$data['name']})", (string) $id);

        return ['success' => true, 'id' => $id];
    }

    public function update(int $id, array $input, ?int $actingUserId): array
    {
        $holiday = $this->holidays->find($id);
        if (! $holiday) {
            return ['success' => false, 'errors' => ['id' => 'Holiday not found.']];
        }

        $data = $this->mapInput($input, $actingUserId);
        $data['updated_by'] = $actingUserId;

        if (! $this->holidays->update($id, $data)) {
            return ['success' => false, 'errors' => $this->holidays->errors()];
        }

        $this->activity->log('holidays', 'updated', $actingUserId, "Updated holiday #{$id}", (string) $id);

        return ['success' => true];
    }

    public function delete(int $id, ?int $actingUserId): array
    {
        $holiday = $this->holidays->find($id);
        if (! $holiday) {
            return ['success' => false, 'error' => 'Holiday not found.'];
        }

        $this->holidays->delete($id);
        $this->activity->log('holidays', 'deleted', $actingUserId, "Deleted holiday #{$id}", (string) $id);

        return ['success' => true];
    }

    protected function mapInput(array $input, ?int $actingUserId): array
    {
        return [
            'name'          => trim($input['name']),
            'date'          => $input['date'],
            'is_recurring'  => ! empty($input['is_recurring']) ? 1 : 0,
            'branch_id'     => $input['branch_id'] ?: null,
            'description'   => $input['description'] ?: null,
        ];
    }
}
