<!DOCTYPE html>
<html lang="cs-cz" dir="ltr">
  <head>
  <meta charset="UTF-8">
  <title>Search for person</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="smart-forms.css" type="text/css" rel="stylesheet">
  <link href="js/fancy/jquery.fancybox.css" type="text/css" rel="stylesheet">
  <link href="style.css" rel="stylesheet"> 
  <!--[if lte IE 9]>
    <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>    
    <script type="text/javascript" src="js/jquery.placeholder.min.js"></script>
  <![endif]-->
  <!--[if lte IE 8]>
    <link type="text/css" rel="stylesheet" href="smart-forms-ie8.css">
  <![endif]-->
  <script src="js/jquery.js"></script>
  <script src="js/fancy/jquery.fancybox.js"></script>
  <script src="js/form.js"></script>
  <script src="js/jquery.validate.min.js"></script>
  <script src="js/additional-methods.min.js"></script>
  <script src="js/jquery-ui-1.10.4.custom.min.js"></script>
  <script src="js/jquery-ui-touch-punch.min.js"></script>   
  </head>
  <body>
    <?php 
    include_once 'db.php';     
    if(!isset($_POST['search']) && !isset($_GET['id'])){
    ?>  
    <div class="page">
      <div class="smart-wrap">
        <div class="smart-forms smart-container wrap-3">
          <div class="form-header header-primary">
            <h4>Search for person</h4>
          </div>
          <form id="mainform" action="index.php" method="POST">
            
            <div class="form-body"> 
              <h4>
                All fields are optional
              </h4>
              <div class="frm-row">
                <div class="section colm colm3">
                  <div class="spacer-b15">
                    <label>Height:</label><br>
                    <input type="text" id="heightSearch" class="slider-input" value="" readonly>
                    <input type="text" id="heightInput" name="HeightFrom">
                    <input type="text" id="heightInput" name="HeightTo">
                  </div>            
                  <div class="sliderv-wrapper green-slider">
                    <div id="heightSlider"></div>
                  </div> 
                </div>
                <div class="section colm colm9">
                  <div class="spacer-b15">
                    <label>Years:</label>
                    <input type="text" id="yearSearch" class="slider-input" value="" readonly>
                    <input type="text" id="yearInput" name="YearFrom">
                    <input type="text" id="yearInput" name="YearTo">
                  </label>
                  </div>                 
                  <div class="slider-wrapper green-slider">
                    <div id="yearSlider"></div>
                  </div>
                  <span class="small-text block spacer-t20 fine-grey">Tip: click on slider and slide with arrow keys</span>
                  <div class="spacer-t20">
                    <?php echo RadioButton("traits", "Gender", 1); ?>
                  </div> 
                  <div class="spacer-t20">
                    <?php echo RadioButton("traits", "SkinColor", 1); ?> 
                  </div>
                  <div class="spacer-t20">
                    <?php echo YesNo("Beard"); ?> 
                  </div>
                  <div class="spacer-t20">
                    <?php echo YesNo("Scar"); ?>
                  </div>
                  <div class="spacer-t20">
                    <?php echo YesNo("Tattoo"); ?>
                  </div>
                </div>
              </div>
              <div class="section">
                <div class="spacer-t20">
                  <label class="field-label" for="HairColor">Hair Color</label>
                  <?php echo Select("traits", "HairColor", "whatever"); ?>
                </div>
              </div>
              <div class="section">
                <div class="spacer-t20">
                  <label class="field-label" for="EyeColor">Eye Color</label>
                  <?php echo Select("traits", "EyeColor", "whatever"); ?>
                </div>
              </div>
              <div class="section">
                <label class="field-label" for="ClothesUpperHalf">Clothes upper half</label>
                <?php echo Select("traits", "ClothesUpperHalf", "whatever"); ?>
              </div>
              <div class="section">
                <label class="field-label" for="ColorUpperHalf">Color of upper half clothes</label>
                <?php echo CheckBox("traits", "ColorUpperHalf", 1); ?>
              </div>
              <div class="section">
                <label class="field-label" for="ClothesLowerHalf">Clothes lower half</label>
                <?php echo Select("traits", "ClothesLowerHalf", "whatever"); ?>
              </div>
              <div class="section">
                <label class="field-label" for="ColorLowerHalf">Color of lower half clothes</label>
                <?php echo CheckBox("traits", "ColorLowerHalf", 2); ?>
                <div id="message"></div>  
              </div>
              <input type="submit" value="Search for Person" name="submit" class="button btn-primary">
              <input type="hidden" value="1" name="search">  
            </div>
          </form> 
        </div>
      </div>
    </div>
    <?php
    }
    if (isset($_POST['search'])){
    ?> 
    <div class="results">
    <?php
    
        function Color($what)
            { 
              	$colors = "";
                $first = 0;      
              foreach($_POST["$what"] as $polozka) {
              if ($first == 0){$colors .= " AND";} else {$colors .= " OR";}
                $colors .= " FIND_IN_SET('$polozka', $what)>0";
                $first++;
              }
              return $colors;
            } 
       /* foreach ($_POST as $key=>$value) {
       	  if ($value != "" && $value != -1){
          echo "$key => ";
          print_r ($value);
          echo "<br>";}
       } */  
       
       $heightFrom = ($_POST['HeightFrom']-5);
       $heightTo = ($_POST['HeightTo']+5);
       $yearFrom = (Date("Y", Time()) - $_POST['YearTo'] - 1);
       $yearTo = (Date("Y", Time()) - $_POST['YearFrom'] + 1);
       $query = ("WHERE (Height BETWEEN $heightFrom AND $heightTo) AND (YearOfBirth BETWEEN $yearFrom AND $yearTo)");
       if (isset($_POST['Gender']) && $_POST['Gender'] != "") {$query .= " AND Gender = '".$_POST['Gender']."'";}
       if (!isset($_POST['Gender']) && isset($_POST['SkinColor']) && $_POST['SkinColor'] != "") {$query .= " AND SkinColor = '".$_POST['SkinColor']."'";}
       
       $search = $mysqli->query("SELECT * FROM traits $query;");  
       $nothing = mysqli_num_rows($search);
       while ($row = $search->fetch_assoc()) {
          $rows[] = $row;
      }
       /*$rows = (mysqli_fetch_all($search,MYSQLI_ASSOC)); */
       
       if ($nothing) {
       	foreach ($rows as $id => $row) {
         $shoda = 0;
         $pocet = 0;
         foreach ($row as $key => $value) {
           foreach ($_POST as $form => $set) {
             if ($set != "" && $set != -1){
               if ($key == $form){
                if(is_array($set)){
                  foreach ($set as $barva) {
                    if (in_array($barva, explode(",",$value))) 
                        {$shoda = $shoda + 100;}  	
                  }
                  $pocet = $pocet + max(sizeof(explode(",",$value)),sizeof($set));  
                } 
                else {
                if($value == $set){$shoda = $shoda + 100;}
                $pocet++;
                }
                
                }   
             }	
           }	
         }
         if ($shoda == 0 && $pocet == 0){$shoda = 100; $pocet = 1;}
         $rows[$id]["shoda"] = sprintf('%0.1f', ($shoda/$pocet));
       }
       
      
      foreach($rows as $k=>$v) {
        $sort['ID'][$k] = $v['ID'];
        $sort['shoda'][$k] = $v['shoda'];
      }
      array_multisort($sort['shoda'], SORT_DESC, $sort['ID'], SORT_ASC,$rows);
      $i = 0;
      foreach ($rows as $id => $row) {
        if ($row['shoda'] > 10){ 
           echo "<a href=\"index.php?id=".$row['ID']."\" class=\"person\">
                    <div class=\"photo\">
                      <img src=\"pictures/".strtolower(iso2ascii($row['Name']))."_".strtolower(iso2ascii($row['Surname']))."_small.jpg\" alt=\"ID ".$row['ID']."\">  
                    </div>
                    <div class=\"name\">
                      ID: {$row['ID']}<br>Accordance: {$row['shoda']}%<br> 
                    </div>
                  </a>";
        if ($row['shoda'] == 100)  $i++;
        }
      }
      }
       else {echo "<h2>Your search did not match any records. <a href='search.php'>Try it again</a></h2>";}  

          
          
      ?>
    </div>
    <?php } 
      if (isset($_GET['id'])){
      $person = $mysqli->query("SELECT * FROM traits WHERE ID = ".$_GET['id'].";");  
        while ($record = $person->fetch_assoc()) 
        { 
          $age = (Date("Y", Time()) - $record['YearOfBirth']);
          if ($record['Beard'] == 0){$beard = "NO";}else{$beard = "YES";}
          if ($record['Scar'] == 0){$scar = "NO";}else{$scar = "YES";}
          if ($record['Tattoo'] == 0){$tattoo = "NO";}else{$tattoo = "YES";}
          $body = "";
          if ($record['SkinColor'] == "Light skin"){$body .= "white";}else{$body .= "black";}
          if ($record['Gender'] == "Male"){$body .= "man";}else{$body .= "women";}
          echo "<div class=\"detail\">
                  <a href=\"pictures/".strtolower(iso2ascii($record['Name']))."_".strtolower(iso2ascii($record['Surname'])).".jpg\" class=\"fancy\"><img src=\"pictures/".strtolower(iso2ascii($record['Name']))."_".strtolower(iso2ascii($record['Surname']))."_small.jpg\" alt=\"".$record['Name'] ." ". $record['Surname']."\"></a>
                  <h1>ID: {$record['ID']}</h1><br>
                  $age years<br>
                  <a href=\"https://www.google.cz/maps/place/{$record['City']}, {$record['State']}\" class=\"map\" target=\"_blank\">{$record['City']}, {$record['State']}</a><br>
                  {$record['Gender']}, {$record['SkinColor']}<br>
                  Height: {$record['Height']} cm<br>
                  Eye Color: {$record['EyeColor']}, Hair Color: {$record['HairColor']}<br>
                  Beard: $beard, Scar: $scar, Tattoo: $tattoo<br>
                  {$record['ClothesUpperHalf']}: {$record['ColorUpperHalf']}<br>
                  {$record['ClothesLowerHalf']}: {$record['ColorLowerHalf']}<br>  
                </div>";
        } 
      }
    ?>
    <script>
      $(document).ready(function(){
        
        $(".fancy").fancybox();
        var n = $(".color input[type='checkbox']").length;
        var colors = {
            "Red": "#ED1B24",                                             
            "Pink": "#FEAEC9",
            "Purple": "#A349A3",
            "Blue": "#3F47CC",
            "Turquoise": "#00A3E8",
            "Green": "#23B14D",
            "Yellow": "#FEF200",
            "Black": "#000000",
            "White": "#FFFFFF",
            "Brown": "#B97A57",
            "Orange": "#FF7F26",
            "Grey": "#7F7F7F"
        };
        
        for ( var i = 0; i < n; i++ ) {
          neco = $(".color input[type='checkbox']:eq("+i+")").attr("value");
          $(".color input[type='checkbox']:eq("+i+") + span").css("background-color",colors[neco]);    
        }
    
      $( "#heightSlider" ).slider({
          orientation: "vertical",
					range: true, 
					values: [0,250],
					min: 0,
					max: 250,
					slide: function(event, ui) {
						$("#heightSearch").val(ui.values[0] + " - " + ui.values[1] + " cm");
            $("input[name=\"HeightFrom\"]").val(ui.values[0]);
            $("input[name=\"HeightTo\"]").val(ui.values[1]);
					}
				});
         
      $( "#yearSlider" ).slider({
					range: true,
					values: [0,100],
          slide: function(event, ui) {
						$("#yearSearch").val(ui.values[0] + " - " + ui.values[1] + " years");
            $("input[name=\"YearFrom\"]").val(ui.values[0]);
            $("input[name=\"YearTo\"]").val(ui.values[1]);
					}
				});
        
        $("#heightSearch").val($("#heightSlider").slider("values", 0) + " - " + $("#heightSlider").slider("values", 1) + " cm");
        $("#yearSearch").val($("#yearSlider").slider("values", 0) + " - " + $("#yearSlider").slider("values", 1) + " years");
        $("input[name=\"HeightFrom\"]").val($("#heightSlider").slider("values", 0));
        $("input[name=\"HeightTo\"]").val($("#heightSlider").slider("values", 1));
        $("input[name=\"YearFrom\"]").val($("#yearSlider").slider("values", 0));
        $("input[name=\"YearTo\"]").val($("#yearSlider").slider("values", 1));
    
      row();
      $(window).resize(function() {
        row();
      });
      function row() {
      var pocet = Math.floor($(window).width()/300);
      $(".results").css({ "width": (pocet*300)});    
      }

    });			
  </script>
  <?php  mysqli_close($mysqli); ?>
  </body>
</html>