<?php

namespace App\Http\Controllers\Admin\Crm;

use App\Http\Controllers\Controller;
use App\Models\Crm\QuestionnaireAnswer;
use App\Models\Crm\QuestionnaireTemplate;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class QuestionnaireController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = QuestionnaireTemplate::query();
        $query->when($request->title, fn($q, $v) => $q->where('title', 'like', "%{$v}%"));
        $query->when($request->type, fn($q, $v) => $q->where('type', $v));
        $query->when($request->has('status'), fn($q) => $q->where('status', $request->status));

        return $this->paginate($query->latest()->paginate($request->input('per_page', 15)));
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'title' => 'required|string|max:100',
            'description' => 'nullable|string',
            'questions' => 'nullable|array',
            'type' => 'nullable|integer|in:1,2,3,4',
            'status' => 'sometimes|integer|in:0,1',
        ]);
        return $this->success(QuestionnaireTemplate::create($validated));
    }

    public function show(QuestionnaireTemplate $questionnaire): JsonResponse
    {
        return $this->success($questionnaire->load('answers.customer'));
    }

    public function update(Request $request, QuestionnaireTemplate $questionnaire): JsonResponse
    {
        $validated = $request->validate([
            'title' => 'sometimes|string|max:100',
            'description' => 'nullable|string',
            'questions' => 'nullable|array',
            'type' => 'nullable|integer|in:1,2,3,4',
            'status' => 'sometimes|integer|in:0,1',
        ]);
        $questionnaire->update($validated);
        return $this->success($questionnaire);
    }

    public function destroy(QuestionnaireTemplate $questionnaire): JsonResponse
    {
        $questionnaire->delete();
        return $this->success(null);
    }

    public function submitAnswer(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'questionnaire_template_id' => 'required|exists:questionnaire_templates,id',
            'customer_id' => 'required|exists:customers,id',
            'answers' => 'nullable|array',
            'score' => 'nullable|numeric|min:0|max:100',
        ]);
        $validated['status'] = 1;

        return $this->success(QuestionnaireAnswer::create($validated));
    }

    public function answers(Request $request): JsonResponse
    {
        $query = QuestionnaireAnswer::query()->with(['template', 'customer']);
        $query->when($request->questionnaire_template_id, fn($q, $v) => $q->where('questionnaire_template_id', $v));
        $query->when($request->customer_id, fn($q, $v) => $q->where('customer_id', $v));

        return $this->paginate($query->latest()->paginate($request->input('per_page', 15)));
    }
}
