<?php

    /**
     * Smart Report Maker
     * Version 9.0.0
     * Author : Webuccino
     * All copyrights are preserved to Webuccino
     * URL : http://mysqlreports.com/
     */
    defined('DIRECTACESS') or die("Error 301: Access denied!");
    require_once "request.php";

    $_SESSION[Session_wizard_key]["page_key"] = "step_2";
    require_once 'activePages.php';
    $saved_connections   = $srm_dashboard->get_all_connection_names();
    $selected_connection = isset($_SESSION[Session_report_Settings_key]["connection_name"]) ? $_SESSION[Session_report_Settings_key]["connection_name"] : "";
    /*$host_name = (isset ( $_SESSION[Session_report_Settings_key]["host"] )) ? $_SESSION[Session_report_Settings_key]["host"] : "localhost";
    $user_name = (isset ( $_SESSION[Session_report_Settings_key]["user"] )) ? $_SESSION[Session_report_Settings_key]["user"] : "";
    $password = (isset ( $_SESSION[Session_report_Settings_key]["pass"] )) ? $_SESSION[Session_report_Settings_key]["pass"] :  "";
    $database_name = (isset ( $_SESSION[Session_report_Settings_key]["db"] )) ? $_SESSION[Session_report_Settings_key]["db"] :"";
     */

    $data_source = (isset($_SESSION[Session_report_Settings_key]["datasource"])) ? $_SESSION[Session_report_Settings_key]["datasource"] : 'table';
    require_once "services/functions.php"
?>
<div style="min-height: 350px;" class="container col-xs-12">
  <!-- style="border: 1px solid black;" -->
  <form id="myForm" name="myForm" action="<?php echo ($_SERVER['PHP_SELF']); ?>" role="form" method="post"
    onsubmit="return false;">

    <input type='hidden' id='csrfToken' name='csrfToken' value='<?php echo $request_token_value; ?>' />

    <div class="row">
      <div class="col-xs-10"></div>
      <div class="col-xs-2"></div>
    </div>
    <!-- .row (title) -->

    <div class="row">
      <div class="col-xs-1"></div>
      <div id="error-container" class="col-xs-10">
        <!-- .alert -->
      </div>
      <div class="col-xs-1"></div>
    </div>
    <!-- .row (error) -->
    <div class="row">
      <div class="col-xs-1"></div>

      <div class="form-group col-xs-10">

        <label for="host_name">Connection Name:</label>
        <div class="left-inner-addon">
          <i class="glyphicon glyphicon-tasks"></i>
          <?php

              if (!$_SESSION[Session_wizard_key]["edit_mode"]) {
                  echo ' <select
							name="connection_name" class="form-control font-size-lg"
							id="connection_name">';

                  foreach ($saved_connections as $connection_id => $connection_name) {

                      if ($selected_connection == $connection_name) {
                          echo "<option value='" . $connection_name . "' selected >" . $connection_name . "</option>";
                      } else {
                          echo "<option value='" . $connection_name . "'  >" . $connection_name . "</option>";
                      }

                  }

                  if ($_SESSION[Session_security_key]["srm_access_role"] === "admin") {
                      echo "<option value='add-new-connection'>+ Add new connection</option>";
                  }

              } else {
                  echo '<label style="padding-left: 40px;"
							name="connection_name" class="form-control font-size-lg"
							id="connection_name">' . $_SESSION[Session_report_Settings_key]["connection_name"] . '</label>';
              }

          ?>


          </select>
        </div>
      </div>
      <div class="help-container col-xs-1">
        <a href="" onClick="return false;" id="hostHelp"> <img src="includes/images/help.png" width="15" height="15"
            border="0">
        </a>
      </div>
    </div>

    <div class="row">
      <div class="col-xs-4"></div>
      <div class="col-xs-4">
        <?php

            if (!$_SESSION[Session_wizard_key]["edit_mode"]) {
            ?>
        <button style="margin: 10px;" name="btn_connect" class="btn btn-sunny btn-block" id="btn_connect">

          <?php

                  if (!is_connected()) {
                      echo '<span  class="icon glyphicon glyphicon-link"></span><span
						class="separator"></span> Connect';
                  } else {
                      echo "Disconnect";
                  }

              ?>

        </button>
        <?php
            }
        ?>
      </div>

    </div>
    <!-- .row (connect btn) -->

    <div id="form-two" <?php

                           if (!isset($_SESSION[Session_wizard_key]["validate_key"]) || (isset($_SESSION[Session_wizard_key]["validate_key"]) && $_SESSION[Session_wizard_key]["validate_key"] !== md5("srm_f92024_report_settings_valid_1010"))) {
                               echo "style='display: none;'";
                       }
                       ?>>



      <div style="min-height: 200px;" class="row">
        <div class="col-xs-1"></div>
        <div class="form-group col-xs-10">
          <label for="cmb_data_source">Data Source</label>
          <div class="left-inner-addon">
            <i class="glyphicon glyphicon-dashboard"></i> <select name="data_source" class="form-control font-size-lg"
              id="cmb_data_source">
              <option value="table" <?php
                                        if ($data_source === 'table') {
                                            echo 'selected';
                                    }
                                    ?>>Table</option>
              <option value="sql" <?php
                                      if ($data_source === 'sql') {
                                          echo 'selected';
                                  }
                                  ?>>SQL Query</option>
            </select>
          </div>
        </div>
        <div class="help-container col-xs-1">
          <a href="" id="dsHelp" onClick="return false;"> <img src="includes/images/help.png" width="15" height="15"
              border="0">
          </a>
        </div>
      </div>
      <!-- .row (select data source) -->

      <?php
      if ($_SESSION[Session_wizard_key]["edit_mode"]) {?>
      <div class="alert alert-info">
        <div class="row">
          <div class="col-xs-1" style="margin-right: -17px;margin-top: 5px;">
            <i class="fa fa-info-circle fa-fw"></i>
          </div>
          <div class="col-xs-11">

            <span style="font-size: smaller;">If you make changes to saved options at any point, remember to click
              'Next' on that step to ensure your changes are saved</span>
          </div>
        </div>
      </div>
      <?php }
      ?>
      <div class="row">
        <div class="col-xs-4">
          <!-- back button -->
        </div>
        <div class="col-xs-4"></div>
        <div class="col-xs-4">

          <button name="btn_cont" id="btn_cont" class="btn btn-sunny btn-block">
            <span class="icon glyphicon glyphicon-forward"></span><span class="separator"></span> Next
          </button>
        </div>

      </div>
      <!-- .row (navigation buttons) -->
    </div>

  </form>
</div>
<!-- .container (end of this page) -->

<!-- to complete index tags -->
</div>

</div>
</div>
</div>
<!-- end index tags -->
<script>
/* step_2.php
 * myForm
 * host_name
 * user_name
 * password
 * database_name
 * cmb_data_source
 */
$(document).ready(function() {

  <?php

      if (is_connected()) {
          echo "var connection_status = 'connected';";
      } else {
          echo "var connection_status = 'disconnected';";
      }

  ?>
  $(document).on('change', "#connection_name", function(event) {
    if (window.parent) {
      if ($(this).val() == "add-new-connection")
        window.parent.location.href = window.parent.$("#add-connection-url").data("url");
    }

  });


  if (connection_status == 'connected') {
    $("#connection_name").attr("disabled", true);
  }
  $("#page-header").empty();
  $("#page-header").append(
    '<div id="img-container"><img src="includes/images/mysql-icon.png" width="70" height="70"/></div>');
  $("#page-header").append(
    '<div id="text-container"><h4>Connect to MySQL</h4>Please enter MySQL database parameters</div>');


  $("#btn_connect").mousedown(function(e) {
    e.preventDefault();

    //case disconnect

    if (connection_status == "connected") {
      // console.log(connection_status);
      $.ajax({
        type: "POST",
        data: "stay=1",
        url: "services/disconnect.php"
      }).done(function() {
        connection_status = "disconnected";
        location.replace("../wizard/?id=0");

      });

      return true;

    }

    var connection = $("#connection_name").find(":selected").val();
    //consol.log($("#connection_name").find(":selected").text())
    var token = "<?php echo $request_token_value; ?>";
    $.ajax({
      url: "services/step_2.php",
      type: "post",
      data: "connection=" + connection + "&token=" + token,

      success: function(data) {


        data = jQuery.parseJSON(data);

        $("#error-container").empty();
        if (data.result === "success") {
          connection_status = "connected";
          alertify.success("Connected Successfully");
          $("#connection_name").attr('disabled', true);
          $("#form-two").show("slow");
          //lood templates
          //***********************************
          if (data.templates) {

            if (data.templates.constructor === Array && data.templates.length > 0) {
              var counter = 0;
              $.each(data.templates, function(key, value) {

                if (typeof value.name != "undefined" && typeof value.title != "undefined") {
                  if (counter == 0) {
                    $("#template_name").empty().append(
                      '<option selected="selected" value="no">Select a template </option>');
                    $("#load_template").text("Load Selected Template");
                  }


                  $("#template_name")
                    .append($("<option></option>")
                      .attr("value", value.name.replace(/[&\/\\#,+();$~%.'":*?<>{}]/g, ''))
                      .text(value.title.replace(/[&\/\\#,+();$~%.'":*?<>{}]/g, '')));
                  counter++;

                }
              });
            }

          }
          //**********************************
          $("#btn_connect").text("Disconnect");

        } else {

          if (data.result != "error" || !data.errorMessage) {
            $("#error-container").append("<div class='alert alert-danger'>No response from server</div>");
          } else {

            var error_message = data.errorMessage;
            $("#error-container").append("<div class='alert alert-danger'>" + error_message + "</div>");
            $("#form-two").hide("slow");
          }
        }
      },
      error: function() {
        $("#error-container").append(
          "<div class='alert alert-danger'>Error contacting the server!</div>");
      }
    });
  });


  function refresh() {
    return function() {
      location.replace("../wizard/?id=0");
    }
  }



  $("#btn_cont").mousedown(function(e) {
    e.preventDefault();
    var token = $("#csrfToken").val();


    var dataSource = $("#cmb_data_source").val();
    $.ajax({
      url: "services/step_2.php",
      type: "post",
      data: "token=" + token + "&dataSource=" + dataSource,
      success: function(data) {

        data = jQuery.parseJSON(data);
        $("#error-container").empty();
        if (data.result === "success") {
          nextToPage("1");
          SwitchStatusDone();
        } else if (typeof data.errorMessage != "undefined" && data.result == "error") {
          alertify.error("Error:" + data.errorMessage);
          //SwitchStatusError();
        }
      },
      error: function() {
        alertify.error("Error contacting the server");
        return;

      }
    });
  });
});
</script>
<!--
	</body>
</html>
-->