<?php

namespace Controllers;

if ( ! defined( 'ABSPATH' ) ) exit;

use Classes\FormBuilder;
use Classes\DigitalSignage4_Tools2;
use Classes\DigitalSignage4_caller;
use Kernel\API\Manager\DigitalSignage4_Exception;
use Kernel\API\Manager\DigitalSignage4_ForfaitManager;
use Kernel\Translations\Translate;

class DigitalSignage4_ConnexionController extends Controller
{
    public function generatePage()
    {
        $this->displayLoginForm();
    }


    private function displayLoginForm()
    {

        //Création du formulaire de contact
        $form = new FormBuilder("formualireDeConnexion", Translate::getTraduction("Connexion"));

        //Ajout des champs du formulaire
        $form->addChamp(
            $form->generateField()
                 ->setId("userToken")
                 ->setLabel(Translate::getTraduction("Entrer_token_connexion"))
                 ->setName("userToken")
                 ->setType("text")
                 ->setValue("")
        );


        //ajout de l'oubli de mot de passe et de la création de contre
        $form->addExtraLink(Translate::getTraduction("Creer_compte_ds4"), "https://www.acacia-dynamic.com/FR/index.php");

        //Récuperation du submit
        if ($form->isSubmit()) {
            $token = $form->getDatas()['userToken'];

            try {
                DigitalSignage4_ForfaitManager::instance()->clearUserMessages();
                $user = DigitalSignage4_ForfaitManager::instance()->getForfait($token, true);

                if ($user) {
                    $_SESSION['Success'][] = Translate::getTraduction("Connexion_compte_etablie");
                    ( new DigitalSignage4_caller() )->save_data(DigitalSignage4_caller::FORFAIT, $user);
                    $_SESSION['Errors'] = array();
                    DigitalSignage4_Tools2::redirectAdmin("presentation");
                } else {
                    $_SESSION['Errors'] = array_merge(isset($_SESSION['Errors']) ?$_SESSION['Errors']: array(), DigitalSignage4_ForfaitManager::instance()->getUserMessages());
                }
            } catch (DigitalSignage4_Exception $e) {
                $e->echoError();
            }
        }

        //Affichage de la vue de connexion
        $this->assign(array(
            'formConnection' => $form,
            'form_nonce' => wp_nonce_field( 'ds4_form_nonce' ),
        ));

        $this->setWPTemplate("Account/login");
    }
}
