<?php
include "conn.php";

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // Make MySQLi throw exceptions.

        try {
            // Try Connect to the DB with new MySqli object - Params {hostname, userid, password, dbname}
            $mysqli = new mysqli($host, $user, $pass, $base);


              $filtro = " WHERE linea='".$_GET["linea"]."' AND genero='".$_GET["gen"]."'";


              $titulo = "Metas por categoría";
              
              $subtitulo = $_GET["linea"]." - ".$_GET["gen"];
              //$descripcion = "Después de modificar las metas se debe reprocesar";


            // Select all records from the db. Keep inside try block incase there an issue with sql query
            $query = "SELECT tienda,almacen,meta
            FROM metas
            ".$filtro."
            ORDER BY tienda,genero,linea,almacen DESC";

            //echo $query;
            $tabla='    <table align="center" border="1" id="sampleTbl" cellpadding="10">
            <thead>
                <tr>
                    <th>Tienda</th>
                    <th>Zona</th>
                    <th>Meta</th>
                </tr>
            </thead>
            <tbody>';
            
            if ($result = $mysqli->query($query)) {

                /* fetch associative array */
                while ($row = $result->fetch_assoc()) {

                    $tabla = $tabla . '<tr>
                    <td style="padding:10px">'.$row["tienda"].'</td>
                    <td>'.$row["almacen"].'</td>
                    <td contenteditable="true">'.$row["meta"].'</td>
                  </tr>';
                }
                $tabla = $tabla . '</tbody></table>';

                $result->free();

            }
        } catch (mysqli_sql_exception $e) { // Failed to connect? Lets see the exception details..
            echo "MySQLi Error Code: " . $e->getCode() . "<br />";
            echo "Exception Msg: " . $e->getMessage();
            exit; // exit and close connection.
        }

        $mysqli->close(); // finally, close the connection
        
 ?>  
 
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="Start your development with a Dashboard for Bootstrap 4.">
  <meta name="author" content="Creative Tim">
  <title><?php echo $marca;?></title>

  <!-- Fonts -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700">
  <!-- Icons -->
  <link rel="stylesheet" href="../../assets/vendor/nucleo/css/nucleo.css" type="text/css">
  <link rel="stylesheet" href="../../assets/vendor/@fortawesome/fontawesome-free/css/all.min.css" type="text/css">
  <!-- Page plugins -->
  <link rel="stylesheet" href="../../assets/vendor/datatables.net-bs4/css/dataTables.bootstrap4.min.css">
  <link rel="stylesheet" href="../../assets/vendor/datatables.net-buttons-bs4/css/buttons.bootstrap4.min.css">
  <link rel="stylesheet" href="../../assets/vendor/datatables.net-select-bs4/css/select.bootstrap4.min.css">
  <!-- Argon CSS -->
  <link rel="stylesheet" href="../../assets/css/argon.css?v=1.1.0" type="text/css">


  <script src="tabla/ajax.jquery.min.js"></script>
  <script src="tabla/jquery.json-2.4.min.js"></script>

</head>

<body>

  <!-- menu lateral -->
  <?php include "menu.php"?>
  
  <!-- Main content -->
  <div class="main-content" id="panel">
    <!-- Topnav -->
    
    <!-- Header -->
    <!-- Header -->
    <div class="header bg-primary pb-6">
      <div class="container-fluid">
        <div class="header-body">
        <div class="row align-items-center py-4">

<div class="col-lg-6 col-7">
  <h6 class="h2 text-white d-inline-block mb-0"><?php echo $titulo;?></h6>
</div>

  <!-- Sidenav toggler -->
  <?php include "toggler.php"?>


</div>
        </div>
      </div>
    </div>
    <!-- Page content -->
    <div class="container-fluid mt--6">
      <!-- Table -->
      <div class="row">
        <div class="col">
          <div class="card">
            <!-- Card header -->
            <div class="card-header">
              <h3 class="mb-0"><?php echo $subtitulo;?></h3>
              <p class="text-sm mb-0">
              <?php echo $descripcion;?>
              </p>
            </div>

            <div class="card-header bg-transparent border-0">
                <a href="mapa_det_cat.php?gen=<?php echo $_GET["gen"]?>&tienda=<?php echo $_GET["linea"]?>" class="btn btn-sm btn-neutral">Mapa</a>
            </div>

            <div class="table-responsive py-4">
            
            <?php echo $tabla;?>
            <br><br>
    <!--input type="button" value="1. Read Table Values" name="read" onClick="readTblValues()"/>
    <input type="button" value="2. Store values in JS Array" name="store" onClick="storeAndShowTableValues()"/>    
    <input type="button" value="3. Convert JS Array to json" name="convert" onClick="convertArrayToJSON()"/>
    <input type="button" value="4. Send json array to Server" name="send" onClick="sendTblDataToServer()"/-->
    <div align=center><input type="button" value="Guardar" name="send" onClick="sendTblDataToServer()"/>
      </div>

    <br><br>
    
    <div id="tbTableValues"></div>
    <div id="tbTableValuesArray"></div>
    <div id="tbConvertToJSON"></div>
    
    <div align=center id="tbServerResponse">...</div>


    <script>
/*
 * Robert Scavilla
 * https://github.com/rscavilla/store-html-table-values-in-a-javascript-array
 */
        function readTblValues()
        {
            var TableData = '';

            $('#tbTableValues').val('');    // clear textbox
            $('#sampleTbl tr').each(function (row, tr) {
                TableData = TableData
                        + $(tr).find('td:eq(0)').text() + ' '  // Task No.
                        + $(tr).find('td:eq(1)').text() + ' '  // Date
                        + $(tr).find('td:eq(2)').text() + ' '  // Description
                        + '\n';
            });
            $('#tbTableValues').html(TableData);
        }

        function storeAndShowTableValues()
        {
            var TableData;
            TableData = storeTblValues();
            $('#tbTableValuesArray').html('<br>JS Array: <br>' + print_r(TableData));
        }
        function storeTblValues()
        {
            var TableData = new Array();

            $('#sampleTbl tr').each(function (row, tr) {
                TableData[row] = {
                    "tienda": $(tr).find('td:eq(0)').text()
                    , "almacen": $(tr).find('td:eq(1)').text()
                    , "meta": $(tr).find('td:eq(2)').text()
                }

            });
            //TableData.shift();  // first row will be empty - so remove
            TableData[0]= {
                    "tienda": <?php echo '"'.$_GET["gen"].'"'; ?>
                    , "almacen": <?php echo '"'.$_GET["linea"].'"'; ?>
                    , "meta": ""
                }

            return TableData;
        }

        function convertArrayToJSON()
        {
          var TableData;
            TableData = $.toJSON(storeTblValues());
            alert(TableData);
            $('#tbConvertToJSON').html('<br>JSON array: <br>' + TableData.replace(/},/g, "},<br>"));

        }
        function sendTblDataToServer()
        {
            var TableData;
            TableData = $.toJSON(storeTblValues());
            $('#tbSendTblDataToServer').val('JSON array to send to server: <br<br>' + TableData.replace(/},/g, "},<br>"));

            $.ajax({
                type: "POST",
                url: "meta_guarda.php",
                data: "pTableData=" + TableData,    // post TableData to server script

                success: function (msg) {
                    // return value stored in msg variable 
                    $('#tbServerResponse').html( msg );
                }
            });
        }


        function print_r(arr, level) {
            var dumped_text = "";
            if (!level)
                level = 0;

            //The padding given at the beginning of the line.
            var level_padding = "";
            for (var j = 0; j < level + 1; j++)
                level_padding += "    ";

            if (typeof (arr) === 'object') { //Array/Hashes/Objects 
                for (var item in arr) {
                    var value = arr[item];

                    if (typeof (value) === 'object') { //If it is an array,
                        dumped_text += level_padding + "'" + item + "' \n";
                        dumped_text += print_r(value, level + 1);
                    } else {
                        dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
                    }
                }
            } else { //Stings/Chars/Numbers etc.
                dumped_text = "===>" + arr + "<===(" + typeof (arr) + ")";
            }
            return dumped_text;
        }
    </script>
            </div>
          </div>
          
        </div>
      </div>
       <!-- Footer -->
       <footer class="footer pt-0">
         <div class="row align-items-center justify-content-lg-between">
           <div class="col-lg-6">
             <div class="copyright text-center text-lg-left text-muted">
               &copy; <?php echo $anio;?> <a href="#" class="font-weight-bold ml-1" ><?php echo $marca;?></a>
             </div>
           </div>

         </div>
       </footer>
    </div>
  </div>
  <!-- Argon Scripts -->
  <!-- Core -->

  <script src="../../assets/vendor/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
  <script src="../../assets/vendor/js-cookie/js.cookie.js"></script>
  <script src="../../assets/vendor/jquery.scrollbar/jquery.scrollbar.min.js"></script>
  <script src="../../assets/vendor/jquery-scroll-lock/dist/jquery-scrollLock.min.js"></script>
  <!-- Optional JS -->
  <script src="../../assets/vendor/datatables.net/js/jquery.dataTables.min.js"></script>
  <script src="../../assets/vendor/datatables.net-bs4/js/dataTables.bootstrap4.min.js"></script>
  <script src="../../assets/vendor/datatables.net-buttons/js/dataTables.buttons.min.js"></script>
  <script src="../../assets/vendor/datatables.net-buttons-bs4/js/buttons.bootstrap4.min.js"></script>
  <script src="../../assets/vendor/datatables.net-buttons/js/buttons.html5.min.js"></script>
  <script src="../../assets/vendor/datatables.net-buttons/js/buttons.flash.min.js"></script>
  <script src="../../assets/vendor/datatables.net-buttons/js/buttons.print.min.js"></script>
  <script src="../../assets/vendor/datatables.net-select/js/dataTables.select.min.js"></script>
  <!-- Argon JS -->
  <script src="../../assets/js/argon.js?v=1.1.0"></script>

</body>

</html>