<?php

namespace App\Controllers;

use App\Models\EncuestaModel;
use App\Models\PreguntaModel;
use App\Models\RespuestaModel;
use App\Models\SurveyUserModel;
use App\Models\UserModel;
use phpDocumentor\Reflection\DocBlock\Tags\TagWithType;

class Encuesta extends BaseController
{
    public function encuesta($id)
    {
        if (!$encuesta = model(EncuestaModel::class)->find($id)) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }
        $data = [
            'id' => $encuesta['id'],
            'title' => $encuesta['title'],
            'preguntas' => model(PreguntaModel::class)->getPreguntas($id),
        ];
        return view('Encuesta/template', $data);
    }

    public function submit($id)
    {
        $respuestaModel = model(RespuestaModel::class);
        $userId = user_id();

        $data = $this->request->getPost();
        $respuestas = [];

        foreach ($data as $questionId => $answer) {
            if (is_array($answer)) {
                foreach ($answer as $a) {
                    $respuesta = [
                        'survey_id' => $id,
                        'user_id' => $userId,
                        'answer' => $a,
                        'question_id' => $questionId,
                    ];
                    array_push($respuestas, $respuesta);
                }
            } else {
                $respuesta = [
                    'survey_id' => $id,
                    'user_id' => $userId,
                    'answer' => $answer,
                    'question_id' => $questionId,
                ];

                array_push($respuestas, $respuesta);
            }
            // $answer = implode(chr(13), $answer);


        };

        if (!$respuestaModel->insertBatch($respuestas)) {
            return redirect()->back()
                ->with('msg', array(
                    'type' => 'danger',
                    'body' => 'No se pudo guardar la encuesta. Inténtalo nuevamente.'
                ));
        }

        // Registrar que usuario respondió encuesta
        $surveyUserModel = model(SurveyUserModel::class);
        $surveyUserModel->save([
            'survey_id' => $id,
            'user_id' => $userId,
        ]);

        return redirect()->route('home')->with('msg', array(
            'type' => 'success',
            'body' => 'Encuesta guardada correctamente'
        ));
    }


    public function userAnswered()
    {
        $surveyUserModel = model(SurveyUserModel::class);

        $encuestaId = 23;
        $userId = user_id();

        echo $surveyUserModel->alreadyAnswered($encuestaId, $userId);
    }
}