<?php

namespace App\Modules\HR\Shifts\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\HR\Employees\Models\Employee;
use App\Modules\HR\Shifts\Repositories\ShiftRepository;
use App\Modules\HR\Shifts\Requests\StoreEmployeeShiftAssignmentRequest;
use App\Modules\HR\Shifts\Services\EmployeeShiftAssignmentService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class EmployeeShiftAssignmentPageController extends Controller
{
    public function __construct(
        private readonly EmployeeShiftAssignmentService $assignments,
        private readonly ShiftRepository $shifts,
    ) {}

    public function create(): View
    {
        $tenant = $this->tenant();

        return view('pages.hr.shifts.assign', [
            'employees' => Employee::query()
                ->where('tenant_id', $tenant->id)
                ->where('is_active', true)
                ->orderBy('full_name')
                ->get(['id', 'full_name']),
            'shifts' => $this->shifts->activeForTenant((int) $tenant->id),
        ]);
    }

    public function store(StoreEmployeeShiftAssignmentRequest $request): RedirectResponse
    {
        $tenant = $this->tenant();
        $v = $request->validated();
        $this->assignments->assign(
            (int) $tenant->id,
            (int) $v['employee_id'],
            (int) $v['shift_id'],
            (int) $request->user()->id,
        );

        return redirect()->route('hr.shifts.assignments.create')->with('status', __('shifts.flash.assigned'));
    }

    private function tenant(): Tenant
    {
        $t = auth()->user()?->tenant;
        abort_if($t === null, 403);

        return $t;
    }
}
