<?php
$access=new yamlReadwriter();

$access->loadYaml(getTemplate("structure_access.yaml")); // charger la structure complète
$access->setType("access"); // important
$access->setSnippetFolder(APP."form_parts/");
$id_access="";

if(isset($_SESSION['id'])){
    $id_access=$_SESSION['id'];
}
if(isset($_POST['source'])){
    $id_access=$_POST['source'];
}
$access->loadContentFromYaml(CONFIG."access/".$id_access);

switch($_POST['action']){
    case "loadform":
        $temp_mdp=$access->get('mdp');
        $access->set('mdp',"");
        $access->addHidden("action","submitform");
        $access->addHidden("callback","yc_filldestination");
        $access->addHidden("endaction","yc_closeViewer");

        $menu_edit= array();
        include(APP."snippets/menu-viewer.php");
        if(!$id_access){
            $access->form_title="Créer un accès";
            $access->form_submit="Créer";
        } else {
            $access->form_title="Modifier un accès";
            $access->form_submit="Modifier";
            $access->form_delete=false;
        }

        echo "<div class='generic-viewercontent'>";
        $access->writeForm();
        echo "</div>"; 

        break;

    case "submitform":
        $access->setDestinationFolder(CONFIG."access/");
        $name=trim($_POST['nom']);
        $login=trim($_POST['login']);
        $mdp=trim($_POST['mdp']);
        $mdp2=trim($_POST['mdp_verif']);

        if(!$name || !$login ){
            echo "Information manquante! ";
            die();
        }
        if(strcmp($mdp, $mdp2) !== 0){
            echo "Les mots de passe ne sont pas identiques ! ";
            die();
        }

        // creer un hash si le nom n'existe pas
        if(!$access->filename){
            if(!trim($mdp) || !trim($mdp2)){
                echo "Le mot de passe et sa vérification ne peuvent pas être vides ! ";
                die();
            }
            $access->filename=date("YmdHis")."_".uniqid().".yaml";
        }

        $access->set("nom",$name);
        $access->set("login",$login);

        if(trim($_POST['mdp'])){
            $access->set("mdp",md5($mdp));
        }

        $access->writeyaml();
        break;
}
?>