<?php

namespace Modules\Attendance\Services;

use App\Models\ActivityLogModel;
use App\Models\EmployeeShiftAssignmentModel;

class ShiftAssignmentService
{
    protected EmployeeShiftAssignmentModel $assignments;
    protected ActivityLogModel $activity;

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

    public function assign(array $input, ?int $actingUserId): array
    {
        $employeeId = (int) ($input['employee_id'] ?? 0);
        $shiftId    = (int) ($input['shift_id'] ?? 0);
        $from       = trim($input['effective_from'] ?? '');

        if ($employeeId <= 0 || $shiftId <= 0 || $from === '') {
            return ['success' => false, 'errors' => ['form' => 'Employee, shift, and effective date are required.']];
        }

        $data = [
            'employee_id'    => $employeeId,
            'shift_id'       => $shiftId,
            'effective_from' => $from,
            'effective_to'   => ! empty($input['effective_to']) ? $input['effective_to'] : null,
            'created_by'     => $actingUserId,
            'updated_by'     => $actingUserId,
        ];

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

        $id = $this->assignments->getInsertID();
        $this->activity->log('attendance_shifts', 'assigned', $actingUserId, "Assigned shift #{$shiftId} to employee #{$employeeId}", (string) $id);

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