<?php

namespace Modules\Attendance\Services;

use App\Models\ActivityLogModel;
use App\Models\AttendanceShiftModel;

class AttendanceShiftService
{
    protected AttendanceShiftModel $shifts;
    protected ActivityLogModel $activity;

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

    public function create(array $input, ?int $actingUserId): array
    {
        $code = strtoupper(trim($input['code'] ?? ''));
        if ($this->shifts->isCodeTaken($code)) {
            return ['success' => false, 'errors' => ['code' => 'That shift code is already in use.']];
        }

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

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

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

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

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

        $code = strtoupper(trim($input['code'] ?? ''));
        if ($this->shifts->isCodeTaken($code, $id)) {
            return ['success' => false, 'errors' => ['code' => 'That shift code is already in use.']];
        }

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

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

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

        return ['success' => true];
    }

    public function activate(int $id, ?int $actingUserId): void
    {
        $this->shifts->update($id, ['status' => 'active', 'updated_by' => $actingUserId]);
        $this->activity->log('attendance_shifts', 'activated', $actingUserId, "Activated shift #{$id}", (string) $id);
    }

    public function deactivate(int $id, ?int $actingUserId): void
    {
        $this->shifts->update($id, ['status' => 'inactive', 'updated_by' => $actingUserId]);
        $this->activity->log('attendance_shifts', 'deactivated', $actingUserId, "Deactivated shift #{$id}", (string) $id);
    }

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

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

        return ['success' => true];
    }

    protected function mapInput(array $input, ?int $actingUserId): array
    {
        return [
            'name'                     => trim($input['name']),
            'start_time'               => $input['start_time'],
            'end_time'                 => $input['end_time'],
            'grace_period_minutes'     => (int) ($input['grace_period_minutes'] ?? 15),
            'early_exit_grace_minutes' => (int) ($input['early_exit_grace_minutes'] ?? 0),
            'overtime_after_minutes'   => (int) ($input['overtime_after_minutes'] ?? 30),
            'break_minutes'            => (int) ($input['break_minutes'] ?? 60),
            'auto_punch'               => ! empty($input['auto_punch']) ? 1 : 0,
            'description'              => $input['description'] ?: null,
            'status'                   => $input['status'] ?? 'active',
        ];
    }
}
