<?php

class CASS_View_Type_Edit
{

  public static function execute()
  {
    global $wpdb;

    $type = new Type;

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

    //Default values tramsitted
    $IDType=0;

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

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

    //Edit mode
    if ($stateForm == "edit" && $IDType > 0) {
      $type->loadFromId(intval($IDType));
    }

    //Validation form 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 {
        $type->setName(SantizeGlobal($_POST["name"]));
      }

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

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


    <div class="wrap">

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

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