<?php

class CASS_View_Material_Edit
{

  public static function execute()
  {
    global $wpdb;

    $material = new Material;

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

    //Default values tramsitted
    $IDMaterial = 0;

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

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

    //Edit mode
    if ($stateForm == "edit" && $IDMaterial > 0) {
      $material->loadFromId($IDMaterial);
    }

    //Validating data 
    if (isset($_POST["name"]) && isset($_POST["description"])) {
      $dataValidationSuccess = true;

      //Obligatory fields
      if ($_POST["name"] == "") {
        // echo "<h3>Le nom est obligatoire.</h3>";
        $dataValidationSuccess = false;
      } else {
        $material->setName(SantizeGlobal($_POST["name"]));
      }

      //Non obligatory fields
      $material->setDescription(SantizeGlobal($_POST["description"]));

      if ($dataValidationSuccess) {
        switch ($stateForm) {
          case 'create':
            $material->create();
            break;

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

    ?>

    <div class="wrap">

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

      ?>
      <form action="" method="post">
        <input type="hidden" id="action" name="action" value=<?php echo $stateForm ?>>
        <input type="hidden" id="IDMaterial" name="IDMaterial" value=<?php echo $IDMaterial ?>>
        <br />
        <div class="form-element">
          <label class="form-element">Nom*</label>
          <input class="cass" type="text" name="name" value="<?php echo ReadGlobal($material->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($material->getDescription()) ?>">
        </div>
        <br />
        <?php
        if ($stateForm == "create") {
          submit_button('Créer le matériel', 'primary');
        } else if ($stateForm == "edit") {
          submit_button('Sauvegarder', 'primary');
        }
        ?>
      </form>
    </div>
    <?php
  }
}