<?php

namespace Main\Controllers\Application;

use Main\Core\Controller;
use Main\Core\Jobs\JobDispatcher;
use Main\Jobs\SendDiscordWebhook;
use Main\Services\SeoService;

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

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

        $questions = db()->prepare("SELECT * FROM ApplicationFormQuestions WHERE formId = ? AND isEnabled = ? ORDER BY id ASC");
        $questions->execute(array($form["id"], 1));
        $form["questions"] = $questions->fetchAll();
	    
		    $activeApplication = db()->prepare("SELECT id, status FROM Applications WHERE accountId = ? AND formId = ? ORDER BY id DESC LIMIT 1");
		    $activeApplication->execute(array(auth()->user()->id(), $form["id"]));
		    $activeApplication = $activeApplication->fetch();
				$form["isAppliable"] = !$activeApplication || ($activeApplication["status"] == "0" && $form["reappliable"] == "1");
				
        return $this->view('applications.form', compact('form'));
    }

    public function apply($id)
    {
        $form = db()->prepare("SELECT * FROM ApplicationForms WHERE id = ? AND isEnabled = ?");
        $form->execute(array($id, 1));
        $form = $form->fetch();
	    
		    if (!$form) abort_404();
	    
		    $activeApplication = db()->prepare("SELECT id, status FROM Applications WHERE accountId = ? AND formId = ? ORDER BY id DESC LIMIT 1");
		    $activeApplication->execute(array(auth()->user()->id(), $form["id"]));
		    $activeApplication = $activeApplication->fetch();
		    $form["isAppliable"] = !$activeApplication || ($activeApplication["status"] == "0" && $form["reappliable"] == "1");
				if (!$form["isAppliable"]) abort_404();

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

        $insertApplication = db()->prepare("INSERT INTO Applications (accountID, formID, reason, creationDate) VALUES (?, ?, ?, ?)");
        $insertApplication->execute(array(auth()->user()->id(), $id, "", datetime()));
        $applicationID = 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 ApplicationAnswers (applicationId, questionId, answer) VALUES (?, ?, ?)");
                    $insertAnswer->execute(array($applicationID, $questionsForChecking["id"], $field));
                }
            } else {
                $field = sanitize(input("field-" . $questionsForChecking["id"]));
                $insertAnswer = db()->prepare("INSERT INTO ApplicationAnswers (applicationId, questionId, answer) VALUES (?, ?, ?)");
                $insertAnswer->execute(array($applicationID, $questionsForChecking["id"], $field));
            }
        }
	    
	      JobDispatcher::dispatch((new SendDiscordWebhook('application.submitted', [
			    "username" => auth()->user()->displayName(),
			    "form_title" => $form["title"],
			    "dashboard_url" => website_url("/dashboard/applications/$applicationID")
	      ])));

        redirect(url('applications.show', ['id' => $applicationID]));
    }
}