<?php

namespace App\Http\Controllers;

use App\Models\Survey;
use App\Services\Member\SurveyService;
use Illuminate\Http\Request;
use Inertia\Inertia;

// ══════════════════════════════════════════════════════════════════
//  PublicSurveyController
//
//  Handles the public survey link — no authentication required.
//  Anyone with the token URL can view and submit the survey.
//
//  Routes live outside the auth middleware group.
//  Demographic fields (name, title, company, gender, age) are
//  collected here since we do not know who the respondent is.
// ══════════════════════════════════════════════════════════════════

class PublicSurveyController extends Controller
{
    public function __construct(private SurveyService $service) {}

    // ── Show public survey ─────────────────────────────────────
    public function show(string $token): \Inertia\Response
    {
        $survey = Survey::where('link_token', $token)->firstOrFail();

        if ($survey->status === 'closed' || ($survey->closes_at && $survey->closes_at->isPast())) {
            return Inertia::render('Public/SurveyClosed', [
                'survey' => [
                    'title_en' => $survey->title_en,
                    'title_ar' => $survey->title_ar,
                ],
            ]);
        }

        return Inertia::render('Public/SurveyPublic', [
            'token'  => $token,
            'survey' => $this->service->show($survey),
        ]);
    }

    // ── Submit public response ─────────────────────────────────
    public function respond(Request $request, string $token): \Inertia\Response
    {
        $survey = Survey::where('link_token', $token)->firstOrFail();

        abort_if($survey->status !== 'active', 404);
        abort_if($survey->closes_at && $survey->closes_at->isPast(), 404);

        $request->validate([
            'answers'            => ['required', 'array'],
            'respondent_name'    => ['nullable', 'string', 'max:100'],
            'respondent_title'   => ['nullable', 'string', 'max:100'],
            'respondent_company' => ['nullable', 'string', 'max:100'],
            'respondent_gender'  => ['nullable', 'in:male,female,prefer_not_to_say'],
            'respondent_age'     => ['nullable', 'integer', 'min:15', 'max:90'],
        ]);

        $this->service->respond(
            $survey,
            $request->validated(),
            null,   // no user_id — public respondent
            $request->ip()
        );

        return Inertia::render('Public/SurveyThankYou', [
            'survey' => [
                'title_en' => $survey->title_en,
                'title_ar' => $survey->title_ar,
            ],
        ]);
    }
}
