<?php

include_once("../connect.php");
include_once("../functions.php");
include_once("../session.php");
//ini_set("display_errors", 1);
//error_reporting(E_ALL);


?>
<!DOCTYPE html>
 <html lang="en">
   <head>
     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
	 <meta name="viewport" content="width=device-width, initial-scale=1">

     <title><?= $config['CompanyName'] ?></title>

     <!-- Bootstrap -->
     <link href="../css/bootstrap.min.css" rel="stylesheet">
     <link rel="stylesheet" href="../css/bootstrap-combobox.css" />

     <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
     <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
     <!--[if lt IE 9]>
       <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
       <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
       <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
           <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
           <!-- Include all compiled plugins (below), or include individual files as needed -->
           <script src="../js/bootstrap.min.js"></script>
       	 <script src="../js/bootstrap-combobox.js"></script>
         <script src="../js/functions.js"></script>
         <script src="../js/excellentexport.js"></script>
           <script type="text/javascript">
             $(document).ready(function(){
              // $('.combobox').combobox();

       //        $('.grpline').css("width", "100px");

             });
           </script>
     <![endif]-->
	<link rel="stylesheet" href="../css/styles.css"/>
	<style>
  .itemText2 {
    position: absolute;
    top: 3.5in;
  }
		.tooltip-inner {
			white-space:pre-wrap;
		}
		    @media print {
      a[href]:after {
        content: "" !important;
      }
    }
    @media print {
      hr.page-break {page-break-after: always;}
    }
    tfoot {
      font-weight: bold;
    }
	</style>
</head>
<body>
  <?php
    include("navbar.php");
    //$customer = new Customer($_REQUEST['an']);
  ?>
   <!-- Stack the columns on mobile by making one full-width and the other half-width -->
	<div class="container hidden-print" style="height: 80px;"></div>
  <div class="container " style="margin-top: -20px;">
  <div class="page-header hidden-print">
      <center>
			     <h2 class=""><?= $config['CompanyName'] ?></h2>
			     <h3 class="center">Print Catalog</h3>
           
		  </center>
    </div>
		<div class="pull-right">

			<a class="btn btn-primary hidden-print" onclick="window.print();" href="#">Print</a>
		</div>
    <div class="hidden-print">
    
    <div style="" class="form-inline">
    <label for="filterLine">Line</label>
    <select class="form-control" id="filterLine" name="filterLine">
      <option value="%">All</option>
      <?php
        $query ="SELECT DISTINCT(Line), `Name` FROM INVENTORY LEFT JOIN `LINE` ON(`Line` = `Code`) ORDER BY `Line` ";
        $result = mysqli_query($con, $query);
        while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
      ?>
        <option value="<?= $row['Line'] ?>"><?= $row['Line'] . " - " . $row['Name'] ?></option>
      <?php
        }
      ?>
    </select>
    <label for="filterGroup">Group</label>
    <select class="form-control" id="filterGroup" name="filterGroup">
      <option value="%">All</option>
      <?php
        $query ="SELECT DISTINCT(`Group`), `Name` FROM INVENTORY LEFT JOIN `GROUP` ON(`Group` = `Code`) ORDER BY `Group` ";
        $result = mysqli_query($con, $query);
        while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
      ?>
        <option value="<?= $row['Group'] ?>"><?= $row['Group'] . " - " . $row['Name'] ?></option>
      <?php
        }
      ?>
    </select>
    <button onclick="getNumbers()" class="btn btn-primary">Get SKU's</button>

    <button class="btn btn-primary" onclick="$('#editListModal').modal('show')">Edit List</button>
    
      </div>
      <script type="text/javascript">
      function getNumbers(){
        let list = $("#skuList").val();
        if(list.length > 0){
          if(!confirm("ARE YOU SRE YOU WANT TO CLEAR THE CURRENT LIST?")){
            return false;
          }
        }
        $.get("mod.php?p=printcatalog&a=functions&f=getNumbers", {
          line  : $("#filterLine").val(),
          group  : $("#filterGroup").val(),
        }, function(data){
          $("#skuList").val(data);
          divideInFour();
          fetchImages();
        });
      }
      function fetchImages(){
        $.post("mod.php?p=printcatalog&a=functions&f=getProductImages", {
          
          skuList : $("#skuList").val()
        }, function(data){
          $(".itemContainer").html("");
          console.log(data);
        
            for(var i = 0; i < data.Items.length; i++){
              var itemElement = $("<div/>").addClass("col-xs-6 center centered itemDiv").css("height", "5in").css("border","none");
              itemElement.append($("<img/>").attr("src",data.Items[i].ImageURL).css("max-height", "3.75in") )
              var textElement = $("<div/>").addClass("itemText");
              textElement.append($("<h2/>").text(data.Items[i].SKU))
              textElement.append($("<h4/>").text(data.Items[i].Description + " " + data.Items[i].Notes ))
              itemElement.append(textElement)
              
              $(".itemContainer").append(itemElement);
              if(i+1%4==0 && i!=0){
                $(".itemContainer").append($("<hr/>").addClass("page-break"))
              }
            }
         

        });
        $("#editListModal").modal("hide");
      }
      $.fn.selectRange = function(start, end) {
    var e = document.getElementById($(this).attr('id')); // I don't know why... but $(this) don't want to work today :-/
    if (!e) return;
    else if (e.setSelectionRange) { e.focus(); e.setSelectionRange(start, end); } /* WebKit */ 
    else if (e.createTextRange) { var range = e.createTextRange(); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', start); range.select(); } /* IE */
    else if (e.selectionStart) { e.selectionStart = start; e.selectionEnd = end; }
};
      </script>
		</div>
	</div>
  <div class="itemContainer">
		
  </div>
    <hr />
    <div id="editListModal" class="modal fade" data-backdrop="static" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Edit List</h4>
      </div>
      <div class="modal-body">
        <div class="row">
           Enter SKU separated by "Enter" (One per line)<br>
            Special Characters:<br>
            <b>[blank line]</b> - Leaves a blank spot in the catalog<br>
            <b>*</b> - puts the company logo on that spot in the catalog.
          <div class="col-md-6">
            

            <textarea style="width: 200px; height:300px;" class="form-control" name="skuList" id="skuList"></textarea>
          </div>
          <div class="col-md-6">
            <label for="skuSearch">Search in List:</label>
            <div class="form-inline">
              <input type="text" class="form-control" name="skuSearch" id="skuSearch" />
              <button type="button" class="btn btn-primary" onclick="skuSearch()">Search</button>
            </div>
       
          </div>
        </div>
        <div class="row">
        <button onclick="fetchImages()" class="btn btn-primary">Create Catalog</button> <button class="btn btn-success" onclick="divideInFour()">Place Page Divisor</button>
       <button class="btn btn-danger" onclick="clearList()">Clear List</button>
        </div>
      
      
      
      </div>
      <div class="modal-footer">
      <button data-dismiss="modal" class="btn btn-primary">Close</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
 <script type="text/javascript">
    function clearList(){
      let list = $("#skuList").val();
      if(list.length > 0){
        if(confirm("ARE YOU SRE YOU WANT TO CLEAR THE CURRENT LIST?")){
          $("#skuList").val("");
        }
      }
    }
    function divideInFour(){
      let list = $("#skuList").val();
      list = list.replace(/-----\d*\n/gm,"");
      list = list.split("\n");
      let cursor = 0;
      let list2 = [];
      for(var i = 0; i < list.length; i++){
        
        if(i%4 == 0){
          list2.push("-----" + ((i/4)+1))
        }
        list2.push(list[i])
      }
      $("#skuList").val(list2.join("\n"));
    }
    function getNextReturn(cursor){
      let list = $("#skuList").val();
      return list.indexOf("\n", cursor+1);
    } 
    $(document).ready(function () {
      $("#skuList").on("change", function(){
        divideInFour();
      })
    });
    function setSelectionRange(textarea, selectionStart, selectionEnd) {
    // First scroll selection region to view
    const fullText = textarea.value;
    textarea.value = fullText.substring(0, selectionEnd);
    // For some unknown reason, you must store the scollHeight to a variable
    // before setting the textarea value. Otherwise it won't work for long strings
    const scrollHeight = textarea.scrollHeight
    textarea.value = fullText;
    let scrollTop = scrollHeight;
    const textareaHeight = textarea.clientHeight;
    if (scrollTop > textareaHeight){
        // scroll selection to center of textarea
        scrollTop -= textareaHeight / 2;
    } else{
        scrollTop = 0;
    }
    textarea.scrollTop = scrollTop;

    // Continue to set selection range
    textarea.setSelectionRange(selectionStart, selectionEnd);
}

    function skuSearch(){
      let term = $("#skuSearch").val();
      let searchVal = $('#skuList').val()
      setTimeout(() => {
        setSelectionRange($('#skuList')[0],searchVal.indexOf(term),(searchVal.indexOf('\n',searchVal.indexOf(term))));
      }, 250);
     
      
      // $('#skuList').selectRange(searchVal.indexOf(term), (searchVal.indexOf('\n',searchVal.indexOf(term))));
      // let secondPart = searchVal.substring(searchVal.indexOf('\n',searchVal.indexOf(term)));
      // $('#skuList').val(searchVal.substring(0,searchVal.indexOf('\n',searchVal.indexOf(term))));
      // $('#skuList').scrollTop(10000000000)
      // $('#skuList').selectRange(searchVal.indexOf(term), (searchVal.indexOf('\n',searchVal.indexOf(term))));
      // $('#skuList').val(searchVal);
      
      
    }
    $("#skuSearch").on("keyup", function(e){
      if(e.keyCode == 13){
        skuSearch();
      }
    })
 </script>

   </body>
 </html>
