<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Http\Requests\SubmitEmployeeRegistrationRequest;
use App\Models\AuditLog;
use App\Models\Company;
use App\Services\AuditService;
use App\Services\EmployeeRegistrationService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;

class EmployeeRegistrationController extends Controller
{
    public function __construct(
        private readonly EmployeeRegistrationService $registrationService,
        private readonly AuditService $auditService,
    ) {}

    /**
     * Get list of active companies for employee to select from.
     */
    public function getCompanies(): JsonResponse
    {
        try {
            $companies = Company::where('status', 'active')
                ->orderBy('name', 'asc')
                ->get(['id', 'name', 'email']);

            return response()->json([
                'success' => true,
                'data' => $companies->map(fn ($company) => [
                    'id' => $company->id,
                    'name' => $company->name,
                    'email' => $company->email,
                ]),
            ]);
        } catch (\Exception $e) {
            Log::error('Error fetching companies for employee registration: ' . $e->getMessage(), [
                'exception' => $e,
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while fetching companies.',
                'error' => config('app.debug') ? $e->getMessage() : 'Internal server error',
            ], 500);
        }
    }

    /**
     * Submit a new employee registration form (public endpoint, no auth required).
     */
    public function submit(SubmitEmployeeRegistrationRequest $request): JsonResponse
    {
        try {
            $validated = $request->validated();

            // Resolve company from the registration token
            $company = Company::where('registration_token', $validated['token'])->firstOrFail();
            $validated['company_id'] = $company->id;

            $registration = $this->registrationService->submitPublicRegistrationForm($validated);

            $this->auditService->success(
                AuditLog::ACTION_EMPLOYEE_REGISTRATION_SUBMITTED,
                AuditLog::ACTOR_PUBLIC,
                null, null,
                'EmployeeRegistration', $registration->id,
                ['name' => $registration->first_name . ' ' . $registration->last_name, 'email' => $registration->email_address, 'company_id' => $registration->company_id],
                $request->ip(),
            );

            return response()->json([
                'success' => true,
                'message' => 'Employee registration received successfully. You will receive an email confirmation shortly.',
                'data' => [
                    'registration_id' => $registration->id,
                    'first_name' => $registration->first_name,
                    'last_name' => $registration->last_name,
                    'email_address' => $registration->email_address,
                    'company_id' => $registration->company_id,
                    'status' => $registration->status,
                    'submitted_at' => $registration->created_at->toIso8601String(),
                ],
            ], 201);
        } catch (\Exception $e) {
            Log::error('Error submitting employee registration form: ' . $e->getMessage(), [
                'exception' => $e,
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while submitting your employee registration. Please try again.',
                'error' => config('app.debug') ? $e->getMessage() : 'Internal server error',
            ], 500);
        }
    }
}
