<?php

namespace App\Modules\HR\EmployeeSelfService\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\HR\EmployeeSelfService\Requests\MeStorePermissionRequestRequest;
use App\Modules\HR\EmployeeSelfService\Services\SelfEmployeeContextService;
use App\Modules\HR\PermissionRequests\DTOs\PermissionRequestSubmitData;
use App\Modules\HR\PermissionRequests\Models\PermissionRequest;
use App\Modules\HR\PermissionRequests\Repositories\PermissionRequestRepository;
use App\Modules\HR\PermissionRequests\Services\PermissionRequestService;
use App\Modules\HR\PermissionRequests\Support\PermissionRequestType;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class MePermissionRequestController extends Controller
{
    use AuthorizesRequests;

    public function __construct(
        private readonly SelfEmployeeContextService $context,
        private readonly PermissionRequestRepository $requests,
        private readonly PermissionRequestService $submit,
    ) {}

    public function index(): View
    {
        $employee = $this->context->employee();
        $tenant = $this->tenant();

        return view('pages.me.permission-requests.index', [
            'paginator' => $this->requests->paginateForEmployee((int) $tenant->id, (int) $employee->id),
        ]);
    }

    public function create(): View
    {
        $this->authorize('create', PermissionRequest::class);
        $types = [];
        foreach (PermissionRequestType::all() as $type) {
            $types[$type] = __('permission_requests.types.'.$type);
        }

        return view('pages.me.permission-requests.create', compact('types'));
    }

    public function store(MeStorePermissionRequestRequest $request): RedirectResponse
    {
        $employee = $this->context->employee();
        $v = $request->validated();
        if ($v['type'] === PermissionRequestType::MANUAL_ATTENDANCE_CORRECTION) {
            return redirect()->route('me.attendance.corrections.create', [
                'date' => $v['request_date'],
            ]);
        }
        $this->submit->submit(
            $this->tenant(),
            PermissionRequestSubmitData::fromValidated([
                'employee_id' => (int) $employee->id,
                'type' => $v['type'],
                'request_date' => $v['request_date'],
                'start_at' => $v['start_at'] ?? null,
                'end_at' => $v['end_at'] ?? null,
                'reason' => $v['reason'] ?? null,
            ]),
            (int) $request->user()->id,
        );

        return redirect()
            ->route('me.permission-requests.index')
            ->with('status', __('permission_requests.flash.submitted'));
    }

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

        return $t;
    }
}
