<?php

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

    $stateForm = $_POST["stateForm"];

    $race = new Race;
    $material = new Material;
    $race_material = new Race_Material;

    //Default values tramsitted
    $IDRace = 0;

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

    $race->loadFromId($IDRace);
    $resultsMaterial = $material->selectAll();

    if ($stateForm == "update") {

      //Delete all race_material
      $race_material->deleteAllRaceMaterialFromRace($IDRace);

      //Insert
      for ($g = 0; $g < count($resultsMaterial); $g++) {
        if (isset($_POST[$resultsMaterial[$g]->IDMaterial]) && intval($_POST[$resultsMaterial[$g]->IDMaterial]) > 0) {
          $race_material->setIDMaterial(intval($_POST[$resultsMaterial[$g]->IDMaterial]));
          $race_material->setIDRace($IDRace);
          $race_material->create();
        }
      }
    
      //Redirection
      redirectJS(admin_url() . "admin.php?page=cass-admin-race-list");

    }

    //In all case
    $resultsRaceMaterial = $race_material->selectAllRaceMaterialFromRace($IDRace);

    ?>
    <div class="wrap">

      <?php

      echo "<h2>Matériel pour la course " . $race->getName() . "</h2>";


      ?>
      <form action="" method="post">
        <input type="hidden" id="IDRace" name="IDRace" value=<?php echo $IDRace ?>>
        <input type="hidden" id="stateForm" name="stateForm" value="update">

        <br />
        <?php

        for ($i = 0; $i < count($resultsMaterial); $i++) {
          $checked = '';
          for ($j = 0; $j < count($resultsRaceMaterial); $j++) {
            if ($resultsRaceMaterial[$j]->IDMaterial == $resultsMaterial[$i]->IDMaterial) {
              $checked = 'checked';
            }
          }

          echo "
                    <input type='checkbox' id='" . $resultsMaterial[$i]->IDMaterial . "' name='" . $resultsMaterial[$i]->IDMaterial . "' value='" . $resultsMaterial[$i]->IDMaterial . "' " . $checked . "/>
                    <label for='" . $resultsMaterial[$i]->IDMaterial . "'>" . ReadGlobal($resultsMaterial[$i]->name) . "</label><br>
                ";
        }
        ?>

        <?php
        submit_button('Sauvegarder', 'primary');
        ?>
      </form>
    </div>
    <?php
  }
}