<?php

class CASS_View_Group_Edit
{
  public static function execute()
  {
    global $wpdb;

    $group = new Group;

    //Default state of form
    $stateForm = "create";

    //Default values tramsitted
    $IDGroup=0;

    if(isset($_GET["action"]) && $_GET["action"]!="") {
      $stateForm = $_GET["action"];
    } else if(isset($_POST["action"]) && $_POST["action"]!="") {
      $stateForm = $_POST["action"];
    }

    if(isset($_GET["IDGroup"]) && intval($_GET["IDGroup"])!=0) {
      $IDGroup = intval($_GET["IDGroup"]);
    } else if(isset($_POST["IDGroup"]) && intval($_POST["IDGroup"])!=0) {
      $IDGroup = intval($_POST["IDGroup"]);
    }

    //Edit mode
    if ($stateForm == "edit" && $IDGroup > 0) {
      $group->loadFromId($IDGroup);
    }
  
      //Validation form data
      if(isset($_POST["name"]) && isset($_POST["description"])) {
        $dataValidationSuccess = true;

        //Obligatory fields
        if ($_POST["name"]=="") {
          $dataValidationSuccess = false;
        }  else {
          $group->setName(SantizeGlobal($_POST["name"]));
        }

        //Non obligatory fields
        $group->setDescription(SantizeGlobal($_POST["description"]));
      
      if($dataValidationSuccess) { 
        switch ($stateForm) {
          case 'create':   
                $group->create();
                break;

              case 'edit':
                $group->setId($IDGroup);
                $group->update();
                break;
        }
        //Redirection
        redirectJS(admin_url()."admin.php?page=cass-admin-group-list");
      } else {
        echo "<h3>Veuillez vérifier les données.</h3>";
      }
    }
    ?>

    <div class="wrap">

      <?php
      if ($stateForm == "create") {
        echo "<h2>Créer un nouveau groupe</h2>";
      } else if ($stateForm == "edit") {
        echo "<h2>Modifier un groupe</h2>";
      }

      ?>
      <form action="" method="post">
        <input type="hidden" id="action" name="action" value=<?php echo $stateForm ?>>
        <input type="hidden" id="IDGroup" name="IDGroup" value=<?php echo $IDGroup ?>>
        <br />
        <div class="form-element">
        <label class="form-element">Nom*</label>
        <input class="cass" type="text" name="name" value="<?php echo ReadGlobal($group->getName())?>" required>
        </div>
        <br />
        <div class="form-element">
        <label class="form-element">Description</label>
        <input class="cass" type="text" name="description" value="<?php echo ReadGlobal($group->getDescription())?>">
    </div> 
       <br />
        <?php
          if ($stateForm == "create") {
            submit_button('Créer le groupe', 'primary');
          } else if ($stateForm == "edit") {
            submit_button('Sauvegarder', 'primary');
          }
        ?>
      </form>
    </div>
    <?php
  }
}