<?php

namespace Main\Controllers\CustomForm;

use Main\Core\Controller;
use Main\Services\SeoService;

class CustomFormController extends Controller
{
		protected string $route_type = 'form';
	
    public function show($slug)
    {
        $form = db()->prepare("SELECT * FROM CustomForms WHERE slug = ? AND isEnabled = ?");
		    $form->execute(array($slug, 1));
		    $form = $form->fetch();

        if (!$form) abort_404();
	    
		    SeoService::set('forms.show', [
			    'form_title' => $form['title'],
		    ]);

        $questions = db()->prepare("SELECT * FROM CustomFormQuestions WHERE formId = ? AND isEnabled = ? ORDER BY id ASC");
        $questions->execute(array($form["id"], 1));
		    $form["questions"] = $questions->fetchAll();

        return $this->view('custom-forms.show', compact('form'));
    }

    public function submit($id)
    {
        validate([
            "field-*" => "required"
        ]);
	    
		    $form = db()->prepare("SELECT * FROM CustomForms WHERE id = ? AND isEnabled = ?");
		    $form->execute(array($id, 1));
		    $form = $form->fetch();

        if (!$form) abort_404();

        $questionsForChecking = db()->prepare("SELECT * FROM CustomFormQuestions WHERE formId = ? AND isEnabled = ? ORDER BY id ASC");
        $questionsForChecking->execute(array($form["id"], 1));
        $questionsForChecking = $questionsForChecking->fetchAll();

        $insertForm = db()->prepare("INSERT INTO Forms (accountID, formID, creationDate) VALUES (?, ?, ?)");
        $insertForm->execute(array(auth()->user()->id(), $form["id"], datetime()));
        $formID = db()->lastInsertId();

        foreach ($questionsForChecking as $questionsForChecking) {
            if ($questionsForChecking["type"] == 4) {
                foreach ($_POST["field-" . $questionsForChecking["id"]] as $key => $value) {
                    $field = sanitize($_POST["field-" . $questionsForChecking["id"]][$key]);
                    $insertAnswer = db()->prepare("INSERT INTO FormAnswers (applicationId, questionId, answer) VALUES (?, ?, ?)");
                    $insertAnswer->execute(array($formID, $questionsForChecking["id"], $field));
                }
            } else {
                $field = sanitize(input("field-" . $questionsForChecking["id"]));
                $insertAnswer = db()->prepare("INSERT INTO FormAnswers (applicationId, questionId, answer) VALUES (?, ?, ?)");
                $insertAnswer->execute(array($formID, $questionsForChecking["id"], $field));
            }
        }

        return back()->flash("success", t__('The form has been successfully answered!'));
    }
}