<?php

/**
 * Module d'accueil
 * */

namespace Apps\Forms\Module\Api;

use Core\Controller\Controller;
use Core\View\View;

use Apps\Forms\Entity\FormForm;
use Apps\Forms\Entity\FormQuestion;
use Apps\Forms\Entity\FormResponseUser;


class ApiController extends Controller { 
    
    /***
     * Return list of actis Forms
     */
    public function GetActifs(){
        
        $form = new FormForm($this->Core);
        $forms = $form->Find("Actif=1");
        
        return $form->ToAllArray($forms);
    }
    
    /****
     * Gat form xith Question and Response
     */
    public function GetForm($formId){
        
        $form = new FormForm($this->Core);
        $form->GetById($formId);
        
        return $form->ToCompleteArray();
    }
    
    /****
     * Gat form xith Question and Response
     */
    public function GetFormByCode($code){
        
        $form = new FormForm($this->Core);
        $form = $form->GetByCode($code);
        
        return $form->ToCompleteArray();
    }
    
    /****
     * Save User response
     */
    public function SaveReponseUser($data){
        
        
        foreach($data as $questionId => $response ){
            
            if(is_numeric($questionId)){
                
               $question = new FormQuestion($this->Core);
               $question->GetById($questionId);
               
               switch($question->Type->Value){
                   case "0":
                   case "1":
                       $reponseUser = new FormResponseUser($this->Core);
                       $reponseUser->QuestionId->Value = $questionId;
                       $reponseUser->Value->Value = $response;
                       $reponseUser->Save();
                       break;
                   case "2":
                        $reponses = explode(",", $response);

                        foreach($reponses as $checkResponse)
                        {
                            $reponseUser = new FormResponseUser($this->Core);
                            $reponseUser->QuestionId->Value = $questionId;
                            $reponseUser->ResponseId->Value = $checkResponse;
                            $reponseUser->Save();
                        }

                       break;
                   case "3":
                   case "4":
                       $reponseUser = new FormResponseUser($this->Core);
                       $reponseUser->QuestionId->Value = $questionId;
                       $reponseUser->ResponseId->Value = $response;
                       $reponseUser->Save();
                      
                       break;
              }
            }
        }
    }
    
    
}