<?php

namespace App\Http\Controllers\Member;

use App\Http\Controllers\Controller;
use App\Http\Requests\Member\StoreSurveyRequest;
use App\Models\Survey;
use App\Services\Member\SurveyService;
use Illuminate\Http\Request;
use Inertia\Inertia;

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

    // ── Index ──────────────────────────────────────────────────
    public function index(): \Inertia\Response
    {
        $data = $this->service->index(auth()->id());
        return Inertia::render('Member/Surveys/Index', $data);
    }

    // ── Create ─────────────────────────────────────────────────
    public function create(): \Inertia\Response
    {
        $builderData = $this->service->builderData(auth()->id());
        return Inertia::render('Member/Surveys/Create', [
            ...$builderData,
            'survey' => null,
        ]);
    }

    // ── Store ──────────────────────────────────────────────────
    public function store(StoreSurveyRequest $request): \Illuminate\Http\RedirectResponse
    {
        $this->service->store(auth()->id(), $request->validated());
        return redirect()->route('member.surveys.index')
            ->with('success', __('survey.created_success'));
    }

    // ── Edit ───────────────────────────────────────────────────
    public function edit(Survey $survey): \Inertia\Response
    {
        abort_if($survey->created_by !== auth()->id(), 403);
        $builderData = $this->service->builderData(auth()->id());
        return Inertia::render('Member/Surveys/Create', [
            ...$builderData,
            'survey' => $this->service->formatSurveyForEdit($survey),
        ]);
    }

    // ── Update ─────────────────────────────────────────────────
    public function update(StoreSurveyRequest $request, Survey $survey): \Illuminate\Http\RedirectResponse
    {
        abort_if($survey->created_by !== auth()->id(), 403);
        $this->service->update($survey, $request->validated(), auth()->id());
        return redirect()->route('member.surveys.index')
            ->with('success', __('survey.updated_success'));
    }

    // ── Destroy ────────────────────────────────────────────────
    public function destroy(Survey $survey): \Illuminate\Http\RedirectResponse
    {
        abort_if($survey->created_by !== auth()->id(), 403);
        abort_if($survey->response_count > 0, 422, __('survey.cannot_delete_has_responses'));
        $survey->delete();
        return back()->with('success', __('survey.deleted_success'));
    }

    // ── Publish ────────────────────────────────────────────────
    public function publish(Survey $survey): \Illuminate\Http\JsonResponse
    {
        abort_if($survey->created_by !== auth()->id(), 403);
        $token = $this->service->publish($survey);
        return response()->json(['success' => true, 'token' => $token]);
    }

    // ── Toggle status ──────────────────────────────────────────
    public function toggleStatus(Survey $survey): \Illuminate\Http\JsonResponse
    {
        abort_if($survey->created_by !== auth()->id(), 403);
        if ($survey->status === 'active') {
            $this->service->close($survey);
        } else {
            $this->service->reopen($survey);
        }
        return response()->json(['success' => true, 'status' => $survey->fresh()->status]);
    }

    // ── Show — take the survey ─────────────────────────────────
    public function show(Survey $survey): \Inertia\Response
    {
        abort_if($survey->status !== 'active', 404);
        abort_if($survey->created_by === auth()->id(), 403);

        $alreadyResponded = $survey->responses()->where('user_id', auth()->id())->exists();
        if ($alreadyResponded) {
            return Inertia::render('Member/Surveys/ThankYou', [
                'survey'            => ['title_en' => $survey->title_en, 'title_ar' => $survey->title_ar],
                'already_responded' => true,
            ]);
        }

        return Inertia::render('Member/Surveys/Show', [
            'survey' => $this->service->show($survey),
        ]);
    }

    // ── Respond ────────────────────────────────────────────────
   public function respond(Request $request, Survey $survey): \Inertia\Response
{
    abort_if($survey->status !== 'active', 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', 'string', 'in:male,female,prefer_not_to_say'],
        'respondent_age'     => ['nullable', 'integer', 'min:16', 'max:100'],
    ]);
    $this->service->respond($survey, $request->validated(), auth()->id(), $request->ip());
        return Inertia::render('Member/Surveys/ThankYou', [
            'survey' => ['title_en' => $survey->title_en, 'title_ar' => $survey->title_ar],
        ]);
    }

    // ── Results ────────────────────────────────────────────────
    public function results(Survey $survey): \Inertia\Response
    {
        abort_if($survey->created_by !== auth()->id(), 403);
        $data = $this->service->results($survey);
        return Inertia::render('Member/Surveys/Results', $data);
    }

    // ── Delete personal bank item ──────────────────────────────
    public function deleteBankItem(Request $request, int $itemId): \Illuminate\Http\JsonResponse
    {
        $deleted = $this->service->deleteBankItem(auth()->id(), $itemId);
        return response()->json(['success' => $deleted]);
    }
}