<?php

class CASS_View_Race_Edit
{

  public static function execute()
  {
    global $wpdb;


    $race = new Race;




    //Default state of form
    $stateForm = "create";
    $race->setSubscriptionEnable(true);
    $race->setSubscriptionStart("0001-01-01T00:00:00");
    $race->setSubscriptionEnd("0001-01-01T00:00:00");

    //Default values tramsitted
    $IDRace = 0;

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


    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"]);
    }
    //Edit mode
    if ($stateForm == "edit" && $IDRace > 0) {
      $race->loadFromId($IDRace);
    } else {
      //Create mode
      $race->setStart(date("Y-m-d H:i:s"));
      $race->setEnd(date("Y-m-d H:i:s"));
    }

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

      //Obligatory fields
      if ($_POST["name"] == "") {
        // echo "<p>* le nom est obligatoire</p>";
        $dataValidationSuccess = false;
      } else {
        $race->setName(SantizeGlobal($_POST["name"]));
      }

      if (intval($_POST["state"]) == 0) {
        // echo "<p>* l'état est obligatoire</p>";
        $dataValidationSuccess = false;
      } else {
        $race->setState(intval($_POST["state"]));
      }

      if (intval($_POST["IDWPUser_RL"]) == 0) {
        // echo "<p>* le chef de course est obligatoire</p>";
        $dataValidationSuccess = false;
      } else {
        $race->setIDWPUser_RL(intval($_POST["IDWPUser_RL"]));
      }

      if (intval($_POST["IDSeason"]) == 0) {
        // echo "<p>* le choix de saison est obligatoire</p>";
        $dataValidationSuccess = false;
      } else {
        $race->setIDSeason(intval($_POST["IDSeason"]));
      }

      if ($_POST["placeName"] == "") {
        // echo "<p>* le nom du lieu est obligatoire</p>";
        $dataValidationSuccess = false;
      } else {
        $race->setPlaceName(SantizeGlobal($_POST["placeName"]));
      }

      if ($_POST["placeLocality"] == "") {
        // echo "<p>* la localité est obligatoire</p>";
        $dataValidationSuccess = false;
      } else {
        $race->setPlaceLocality(SantizeGlobal($_POST["placeLocality"]));
      }

      if ($_POST["start"] == "") {
        // echo "<p>* le début est obligatoire</p>";
        $dataValidationSuccess = false;
      } else {
        $race->setStart($_POST["start"]);
      }

      if ($_POST["end"] == "") {
        // echo "<p>* la fin est obligatoire</p>";
        $dataValidationSuccess = false;
      } else {
        $race->setEnd($_POST["end"]);
      }

      if (intval($_POST["level"]) == 0) {
        // echo "<p>* le niveau est obligatoire</p>";
        $dataValidationSuccess = false;
      } else {
        $race->setIDLevel(intval($_POST["level"]));
      }

      if ($_POST["meetingPlaceName"] == "") {
        // echo "<p>* le lieu de rencontre est obligatoire</p>";
        $dataValidationSuccess = false;
      } else {
        $race->setMeetingPlaceName(SantizeGlobal($_POST["meetingPlaceName"]));
      }

      if (intval($_POST["participantMax"]) > 0) {
        if (intval($_POST["participantMin"]) > intval($_POST["participantMax"])) {
          echo "<p>* Le nombre de participants minimum doit être inférieur au nombre de participants maximum</p>";
          $dataValidationSuccess = false;
        }
      }

      if (strtotime($_POST["start"]) > strtotime($_POST["end"])) {
        echo "<p>* La date de début de course doit être inférieur à la date de fin.</p>";
        $dataValidationSuccess = false;
      }


      if (strtotime($_POST["subscriptionStart"]) > strtotime($_POST["subscriptionEnd"])) {
        echo "<p>* La date de début des inscriptions doit être inférieur à la date de fin des inscriptions</p>";
        $dataValidationSuccess = false;
      }

      if (strtotime($_POST["subscriptionStart"]) > strtotime($_POST["start"])) {
        echo "<p>* La date de début des inscriptions doit être inférieur à la date de début de la course</p>";
        $dataValidationSuccess = false;
      }

      if (strtotime($_POST["subscriptionEnd"]) > strtotime($_POST["start"])) {
        echo "<p>* La date de fin des inscriptions doit être inférieur à la date de début de la course</p>";
        $dataValidationSuccess = false;
      }

      if (intval($_POST["IDType"]) == 0) {
        // echo "<p>* le type de course est obligatoire</p>";
        $dataValidationSuccess = false;
      } else {
        $race->setIDType(intval($_POST["IDType"]));
      }

      if (intval($_POST["IDGroup"]) == 0) {
        $dataValidationSuccess = false;
      } else {
        $race->setIDGroup(intval($_POST["IDGroup"]));
      }

      //Non obligatory fields
      $race->setSubscriptionEnable($_POST["subscriptionEnable"] === "on" ? 1 : 0);
      $race->setPlaceLatitude(doubleval($_POST["placeLatitude"]));
      $race->setPlaceLongitude(doubleval($_POST["placeLongitude"]));
      $race->setMeetingPlaceLongitude(doubleval($_POST["meetingPlaceLongitude"]));
      $race->setMeetingPlaceLatitude(doubleval($_POST["meetingPlaceLatitude"]));
      $race->setDescriptionPublic($_POST["descriptionPublic"]);
      $race->setDescriptionMemberSubscribed($_POST["descriptionMemberSubscribed"]);
      $race->setFormType(intval($_POST["formType"]));
      $race->setComment(SantizeGlobal($_POST["comment"]));
      $race->setParticipantMax(intval($_POST["participantMax"]));
      $race->setIDWPUser_Deputy(intval($_POST["IDWPUser_Deputy"]));
      $race->setParticipantMin(intval($_POST["participantMin"]));
      $race->setParticipantMin(intval($_POST["participantMin"]));
      $race->setParticipantMin(intval($_POST["participantMin"]));
      $race->setSubscriptionStart($_POST["subscriptionStart"]);
      $race->setSubscriptionEnd($_POST["subscriptionEnd"]);

      if ($dataValidationSuccess) {
        switch ($stateForm) {
          case 'create':
            $race->setDtCreation(date("Y-m-d H:i:s"));
            $race->setDtEdition(date("Y-m-d H:i:s"));
            $race->create();
            break;

          case 'edit':
            $race->setIDRace($IDRace);
            $race->setDtEdition(date("Y-m-d H:i:s"));
            $race->update();
            break;
        }

        //Send mail
        if ($_POST["cbNotificationMail"] == "on") {
          $mailContentRaceStateChangeObject = SantizeGlobal($_POST["mailContentRaceStateChangeObject"]);
          $mailContentRaceStateChange = SantizeGlobal($_POST["mailContentRaceStateChange"]);
          $state = "";
          switch (intval($race->getState())) {
            case 1:
              $state = "brouillon";
              break;
            case 2:
              $state = "ouverte";
              break;
            case 3:
              $state = "confirmée";
              break;
            case 4:
              $state = "terminée";
              break;
            case 5:
              $state = "annulée";
              break;
          }

          global $wpdb;
          $sql = "SELECT IDWPUser FROM cass_race_user WHERE IDRace = %d AND state <= 2;";
          $rows = $wpdb->get_results($wpdb->prepare($sql, $IDRace));

          for ($i = 0; $i < count($rows); $i++) {
            //Send mail to all members
            $race = new Race();
            $race->loadFromId($IDRace);

            $member_info = get_userdata($rows[$i]->IDWPUser);
            $member_mail = $member_info->user_email;
            $member_first_name = $member_info->first_name;
            $member_last_name = $member_info->last_name;
            $member_no = $member_info->cassMemberNo;

            $rl_info = get_userdata($race->getIDWPUser_RL());
            $rl_mail = $rl_info->user_email;
            $rl_first_name = $rl_info->first_name;
            $rl_last_name = $rl_info->last_name;
            //Send mail
            $mailer = new Mailer("", $member_mail, Mailer::getTemplate("mailContentRaceStateChangeObject"), Mailer::getTemplate("mailContentRaceStateChange"), $member_first_name, $member_last_name, $member_no, $race->getName(), $state);
            $mailer->setMailObject($mailContentRaceStateChangeObject);
            $mailer->setMailMessage($mailContentRaceStateChange);
            $mailer->replaceParametterValue();
            $mailer->sendMail();
          }

        }

        //Redirection
        redirectJS(admin_url() . "admin.php?page=cass-admin-race-list");
      } else {
        echo "<h3>Veuillez vérifier les données.</h3>";
      }

    }

    ?>


    <div class="wrap">

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

      ?>
      <form action="" method="post">
        <input type="hidden" id="action" name="action" value=<?php echo $stateForm ?>>
        <input type="hidden" id="IDRace" name="IDRace" value=<?php echo $IDRace ?>>
        <br />
        <div class="form-element">
          <label class="form-element">Nom*</label>
          <input class="cass" type="text" name="name" value="<?php echo ReadGlobal($race->getName()) ?>" required>
        </div>
        <br />
        <div class="form-element">
          <label class="form-element">Etat*</label>
          <select name="state" id="state" required onchange="stateChangeNotification()">
            <option value="">Sélectionner un état</option>;
            <?php
            $selDrafted = "";
            $selOpened = "";
            $selConfirmed = "";
            $selDone = "";
            $selCancelled = "";

            switch (intval($race->getState())) {
              case 1:
                $selDrafted = "selected";
                break;
              case 2:
                $selOpened = "selected";
                break;
              case 3:
                $selConfirmed = "selected";
                break;
              case 4:
                $selDone = "selected";
                break;
              case 5:
                $selCancelled = "selected";
                break;
            }

            echo "<option value='1' " . $selDrafted . ">Brouillon</option>";
            echo "<option value='2' " . $selOpened . ">Ouverte</option>";
            echo "<option value='3' " . $selConfirmed . ">Confirmée</option>";
            echo "<option value='4' " . $selDone . ">Effectuée</option>";
            echo "<option value='5' " . $selCancelled . ">Annulée</option>";



            ?>
          </select>
          <script>
            function stateChangeNotification() {
              //show stateChangeNotification
              document.getElementById("stateChangeNotification").removeAttribute("hidden");
            }
          </script>
        </div>

        <div hidden class="form-element" id='stateChangeNotification'>
          <br />
          <label class="form-element">Notification</label>
          <span class="cass" style='color:red;'>Vous pouvez notifier le changement du status en activant la notifiation par
            mail (fond du formulaire)</span>
        </div>
        <br />
        <div class="form-element">
          <label class="form-element">Chef de course*</label>
          <select id="IDWPUser_RL" name="IDWPUser_RL" value="<?php echo $race->getIDWPUser_RL() ?>" required>
            <option value="">Sélectionner un chef de course</option>";
            <?php
            $args = array(
              'role' => 'CASS_RL',
              'orderby' => 'user_nicename',
              'order' => 'ASC'
            );
            $users = get_users($args);
            foreach ($users as $user) {
              $selected = "";
              if ($user->id == $race->getIDWPUser_RL()) {

                $selected = "selected";
              }
              echo "<option value=" . $user->id . " " . $selected . " >" . $user->display_name . "</option>";

            }

            ?>
          </select>
        </div>
        <br />
        <div class="form-element">
          <label class="form-element">Adjoint</label>
          <select id="IDWPUser_Deputy" name="IDWPUser_Deputy" value="<?php echo intval($race->getIDWPUser_Deputy()) ?>">
            <option value=0 selected>Sélectionner un adjoint</option>";
            <?php
            $args = array(
              'role' => 'CASS_MEMBER',
              'orderby' => 'user_nicename',
              'order' => 'ASC'
            );
            $users = get_users($args);
            foreach ($users as $user) {
              $selected = "";
              if ($user->id == $race->getIDWPUser_Deputy()) {

                $selected = "selected";
              }
              echo "<option value=" . $user->id . " " . $selected . " >" . $user->display_name . "</option>";

            }
            ?>
          </select>
        </div>
        <br />
        <div class="form-element">
          <label class="form-element">Saison*</label>
          <select name="IDSeason" id="IDSeason" required>
            <?php
            $season = new Season();
            // Obtenez l'ID de la saison en cours
            $currentSeasonID = $season->getCurrentSeason();

            // Select all seasons
            $sql = "SELECT IDSeason,name FROM cass_season ORDER BY name ASC;";
            $rows = $wpdb->get_results($sql);

            foreach ($rows as $season) {
              $selected = "";

              if (intval($race->getIDSeason()) == intval($season->IDSeason)) {
                $selected = "selected";
              } elseif (intval($season->IDSeason) == intval($currentSeasonID)) {
                $selected = "selected"; // Sélectionne la saison en cours par défaut
              }

              echo "<option value='" . $season->IDSeason . "' " . $selected . ">" . $season->name . "</option>";
            }
            ?>
          </select>
        </div>
        <br />
        <div class="form-element">
          <label class="form-element">Nom du lieu*</label>
          <input class="cass" type="text" name="placeName" value="<?php echo ReadGlobal($race->getPlaceName()) ?>" required>
        </div>
        <br />
        <div class="form-element">
          <label class="form-element">Localité*</label>
          <input required class="cass" type="text" name="placeLocality"
            value="<?php echo ReadGlobal($race->getPlaceLocality()) ?>" required>
        </div>
        <br />
        <div class="form-element">
          <label class="form-element">Latitude</label>
          <input class="cass" type="text" name="placeLatitude" value="<?php echo $race->getPlaceLatitude() ?>">
        </div>
        <br />
        <div class="form-element">
          <label class="form-element">Longitude</label>
          <input class="cass" type="text" name="placeLongitude" value="<?php echo $race->getPlaceLongitude() ?>">
        </div>
        <br />
        <div class="form-element">
          <label class="form-element">Inscription activée</label>
          <input type="checkbox" id="subscriptionEnable" name="subscriptionEnable" <?php if ($race->getSubscriptionEnable() == 1) {
            echo "checked";
          } ?>>
        </div>
        <br />

        <!--
        <div class="form-element">
          <label class="form-element">Choisir date inscriptions</label>
          <input type="checkbox" id="inscriptionsDate" />
        </div>
        !--> 
        <br />

        <div id="inscriptionFields">
          <div class="form-element">
            <label class="form-element">Début des inscriptions</label>
            <input class="cass" type="datetime-local" name="subscriptionStart"
              value="<?php echo date('Y-m-d\TH:i', strtotime($race->getSubscriptionStart())) ?>">

          </div>
          <br />
          <div class="form-element">
            <label class="form-element">Fin des inscriptions</label>
            <input class="cass" type="datetime-local" name="subscriptionEnd"
              value="<?php echo date('Y-m-d\TH:i', strtotime($race->getSubscriptionEnd())) ?>">
          </div>

        </div>

        <br />
        <div class="form-element">
          <label class="form-element">Début*</label>
          <input class="cass" type="datetime-local" name="start" required
            value="<?php echo date('Y-m-d\TH:i', strtotime($race->getStart())) ?>">
        </div>
        <br />
        <div class="form-element">
          <label class="form-element">Fin*</label>
          <input class="cass" type="datetime-local" name="end" required
            value="<?php echo date('Y-m-d\TH:i', strtotime($race->getEnd())) ?>">
        </div>
        <br />
        <div class="form-element">
          <label class="form-element">Niveau*</label>
          <select name="level" id="level" required>
            <option value="">Sélectionner un niveau</option>";
            <?php
            //Select all group
            $rows = Level::selectAll();
            foreach ($rows as $level) {
              $selected = "";

              if (intval($level->IDLevel) == intval($race->getIDLevel())) {
                $selected = "selected";
              }
              echo "<option value=" . $level->IDLevel . " " . $selected . ">" . $level->name . "</option>";
            }
            ?>
          </select>
        </div>


        <br />
        <div class="form-element">
          <label class="form-element">Lieu de rencontre*</label>
          <input class="cass" type="text" name="meetingPlaceName"
            value="<?php echo ReadGlobal($race->getMeetingPlaceName()) ?>" required>
        </div>
        <br />
        <div class="form-element">
          <label class="form-element">Latitude</label>
          <input class="cass" type="text" name="meetingPlaceLatitude"
            value="<?php echo $race->getMeetingPlaceLatitude() ?>">
        </div>
        <br />
        <div class="form-element">
          <label class="form-element">Longitude</label>
          <input class="cass" type="text" name="meetingPlaceLongitude"
            value="<?php echo $race->getMeetingPlaceLongitude() ?>">
        </div>
        <br />
        <div class="form-element">
          <label class="form-element">Participants min</label>
          <input class="cass" type="text" name="participantMin" value="<?php echo $race->getParticipantMin() ?>">
        </div>
        <br />
        <div class="form-element">
          <label class="form-element">Participants max*</label>
          <input class="cass" type="text" name="participantMax" value="<?php echo $race->getParticipantMax() ?>" required>
        </div>
        <br />



        <div class="form-element">
          <label class="form-element">Description</label>
          <textarea id="descriptionPublic" name="descriptionPublic" rows="12"
            cols="50"><?php echo ReadGlobal($race->getDescriptionPublic()) ?></textarea>
        </div>
        <br />
        <div class="form-element">
          <label class="form-element">Description membres</label>
          <textarea id="descriptionMemberSubscribed" name="descriptionMemberSubscribed" rows="12"
            cols="50"><?php echo ReadGlobal($race->getDescriptionMemberSubscribed()) ?></textarea>
        </div>
        <br />
        <div class="form-element">
          <label class="form-element">Type de formulaire</label>
          <input class="cass" type="text" name="formType" value="<?php echo $race->getFormType() ?>">
        </div>
        <br />
        <div class="form-element">
          <label class="form-element">Type de course*</label>
          <select name="IDType" id="IDType" required>
            <option value="">Sélectionner un type de course</option>";
            <?php
            //Select all type
            $sql = "SELECT IDType,name FROM cass_type ORDER BY name ASC;";
            $rows = $wpdb->get_results($sql);
            foreach ($rows as $type) {
              $selected = "";

              if (intval($race->getIDType()) == intval($type->IDType)) {
                $selected = "selected";
              }


              echo "<option value=" . $type->IDType . " " . $selected . ">" . $type->name . "</option>";
            }
            ?>
          </select>
        </div>
        <br />
        <div class="form-element">
          <label class="form-element">Type de groupe*</label>
          <select name="IDGroup" id="IDGroup" required>
            <option value="">Sélectionner un groupe</option>";
            <?php
            //Select all group
            $sql = "SELECT IDGroup,name FROM cass_group ORDER BY name ASC;";
            $rows = $wpdb->get_results($sql);
            foreach ($rows as $group) {
              $selected = "";

              if (intval($race->getIDGroup()) == intval($group->IDGroup)) {
                $selected = "selected";
              }


              echo "<option value=" . $group->IDGroup . " " . $selected . ">" . $group->name . "</option>";
            }
            ?>
          </select>
        </div>
        <br />
        <div class="form-element">
          <label class="form-element">Commentaire</label>
          <textarea id="comment" name="comment" rows="12" cols="50"><?php echo ReadGlobal($race->getComment()) ?></textarea>
        </div>
        <br />

        <?php
        $setting = Setting::getInstance();
        ?>
        <h4>Mail de notification</h4>
        <input onchange="showNotificationMail()" type="checkbox" id="cbNotificationMail" name="cbNotificationMail">Notifier
        le changement d'état</checkbox>

        <div id='notificationMail' hidden>

          <br />
          <br />
          <div class="form-element">
            <label class="form-element">Objet du mail aux membres</label>
            <textarea id="mailContentRaceStateChangeObject" name="mailContentRaceStateChangeObject" rows="2"
              cols="50"><?php echo ReadGlobal($setting->getMailContentRaceStateChangeObject()) ?></textarea>
          </div>
          <div class="form-element">
            <label class="form-element">Contenu du mail aux membres</label>
            <textarea id="mailContentRaceStateChange" name="mailContentRaceStateChange" rows="12"
              cols="50"><?php echo ReadGlobal($setting->getMailContentRaceStateChange()) ?></textarea>
          </div>
        </div>
        <br />

        <script>
          function showNotificationMail() {
            var checkBox = document.getElementById("cbNotificationMail");
            var notificationMail = document.getElementById("notificationMail");
            if (checkBox.checked == true) {
              notificationMail.removeAttribute("hidden");
            } else {
              notificationMail.setAttribute("hidden", true);
            }
          }
        </script>

        <?php
        if ($stateForm == "create") {
          submit_button('Créer la course', 'primary');
        } else if ($stateForm == "edit") {
          submit_button('Sauvegarder', 'primary');
        }

        ?>
      </form>
    </div>

    <script>initializeTinyMCE("#descriptionPublic, #descriptionMemberSubscribed");</script>

    <!--
    <script>
      document.getElementById('inscriptionsDate').addEventListener('change', function () {
        const inscriptionFields = document.getElementById('inscriptionFields');
        if (this.checked) {
          inscriptionFields.classList.remove('hidden');
        } else {
          inscriptionFields.classList.add('hidden');
        }
      });
    </script>
      -->

    <style>
      .form-element {
        display: flex;
        /* Disposition en ligne */
      }
    </style>

    <?php

  }
}