<?php

namespace Modules\Vrc\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Vrc\Entities\VrcSatisfactionSurvey;
use Yajra\DataTables\Facades\DataTables;

class SatisfactionController extends VrcBaseController
{
    public function index()
    {
        $this->guard('vrc.ticket.view');

        if (request()->ajax()) {
            $surveys = VrcSatisfactionSurvey::where('business_id', $this->businessId())
                ->whereNotNull('submitted_at')
                ->select(['id', 'submitted_at', 'score', 'nps', 'would_recommend', 'comments']);

            return DataTables::of($surveys)
                ->editColumn('submitted_at', fn ($s) => $s->submitted_at ? $s->submitted_at->format('Y-m-d H:i') : '—')
                ->editColumn('score', fn ($s) => str_repeat('★', (int) $s->score) . str_repeat('☆', 5 - (int) $s->score))
                ->editColumn('nps', fn ($s) => $s->nps !== null ? $s->nps : '—')
                ->editColumn('comments', fn ($s) => e((string) $s->comments))
                ->rawColumns(['score'])
                ->make(true);
        }

        $base = VrcSatisfactionSurvey::where('business_id', $this->businessId())
            ->whereNotNull('submitted_at');

        $count = (clone $base)->count();
        $avgScore = $count ? round((float) (clone $base)->avg('score'), 2) : 0;

        $npsBase = (clone $base)->whereNotNull('nps');
        $npsCount = (clone $npsBase)->count();
        $nps = 0;
        if ($npsCount) {
            $promoters = (clone $npsBase)->where('nps', '>=', 9)->count();
            $detractors = (clone $npsBase)->where('nps', '<=', 6)->count();
            $nps = round((($promoters - $detractors) / $npsCount) * 100, 1);
        }

        return view('vrc::satisfaction.index', compact('count', 'avgScore', 'nps', 'npsCount'));
    }

    /** PUBLIC survey page — resolved by token only. */
    public function show($token)
    {
        $survey = VrcSatisfactionSurvey::where('token', $token)->firstOrFail();
        return view('vrc::portal.survey', compact('survey'));
    }

    /** PUBLIC survey submission — resolved by token only. */
    public function submit(Request $request, $token)
    {
        $survey = VrcSatisfactionSurvey::where('token', $token)->firstOrFail();

        if ($survey->submitted_at) {
            return redirect()->route('vrc.portal.survey', $token);
        }

        $data = $request->validate([
            'score'           => 'required|integer|min:1|max:5',
            'nps'             => 'nullable|integer|min:0|max:10',
            'comments'        => 'nullable|string',
            'would_recommend' => 'nullable|boolean',
        ]);

        $survey->score = $data['score'];
        $survey->nps = $data['nps'] ?? null;
        $survey->comments = $data['comments'] ?? null;
        $survey->would_recommend = $request->boolean('would_recommend');
        $survey->submitted_at = now();
        $survey->save();

        return redirect()->route('vrc.portal.survey', $token);
    }
}
