<?php
  require '../conf/config.php';
  require './common.php';

  ////////////////////////////////// Connecting with DB
  if( !$conn = new mysqli($host, $user, $pswd, $db)) {
    error_log("Connection failed.\n");
    exit;
  }

  ////////////////////////////////// Parameters
  (isset($_GET['prm_Phenotype']) && !empty($_GET['prm_Phenotype'])) ? $prm_Phenotype=$_GET['prm_Phenotype']:returnError("Error");
  (isset($_GET['prm_Zoom']) && !empty($_GET['prm_Zoom'])) ? $prm_Zoom=$_GET['prm_Zoom']:returnError("Error");
  (isset($_GET['prm_Chr']) && !empty($_GET['prm_Chr'])) ? $prm_Chr=$_GET['prm_Chr']:returnError("Error");
  (isset($_GET['prm_Pos']) && !empty($_GET['prm_Pos'])) ? $prm_Pos=$_GET['prm_Pos']:returnError("Error");
  (isset($_GET['prm_Block']) && !empty($_GET['prm_Block'])) ? $prm_Block=$_GET['prm_Block'] : returnError("Error");
  if(preg_match("/\;|\||\&|\`|\(|\)|\<|\>|\*|\?|\{|\}|\[|\]|\!/",$prm_Zoom)) {
        $prm_Zoom = "1k";
  }
  if(!_validate_chrs($conn,$prm_Chr)){exit;}
  _pregMatch($prm_Phenotype);
  if (!(is_numeric($prm_Pos)) || !(is_numeric($prm_Block))) {
        $errmsg = "<div align=\"center\"><font color=\"red\" style=\"font-size:18px;\">Invalid Value!!</font></div>";
        echo $errmsg;
        exit;
  } 
  $db_range_start=$prm_Pos*_cvtZoom($prm_Zoom);
  $db_range_end=($prm_Pos+$prm_Block)*_cvtZoom($prm_Zoom);
  //$query = "SELECT a.phenotype, b.pos, b.prob FROM sys_phenotype a, sys_phenotype_prob b WHERE a.phenotype_id = b.phenotype_id and chr= ? and b.pos >= ? and b.pos <= ? and prob > 0 order by phenotype, pos";
  $query = "SELECT a.phenotype, b.pos, b.prob FROM sys_phenotype a, sys_phenotype_prob b WHERE a.phenotype = ? and a.phenotype_id = b.phenotype_id and chr= ? and b.pos >= ? and b.pos <= ? and prob > 0 order by chr, pos";
  $stmt = $conn->stmt_init();
  $stmt->prepare($query);
  $stmt->bind_param("ssii", $prm_Phenotype, $prm_Chr, $db_range_start, $db_range_end);
  $stmt->execute();
  $stmt->store_result();
  $stmt->bind_result($rowN0,$rowN1,$rowN2);
  $stmt->fetch();
  $rtnString = preg_replace("/\s+/", "_", $rowN0) . "|[{\"dot_pos\":\"".($rowN1 - $db_range_start)/($db_range_end - $db_range_start)."\",\"prob\":\"".$rowN2."\",\"pos\":\"".$rowN1."\"}";
  $prev_pheno = preg_replace("/\s+/", "_", $rowN0);
  $max_prob = $rowN2;
  while ($stmt->fetch()) {
  	$pheno = $rowN0;
  	if(strcmp($pheno, $prev_pheno) != 0){
  		$rtnString = $rtnString . "]|" . $max_prob . ";" .  preg_replace("/\s+/", "_", $rowN0) . "|[";
  		$max_prob = "";
  	}else{
  		$rtnString = $rtnString . ",";
  	}
    $rtnString = $rtnString . "{\"dot_pos\":\"".($rowN1 - $db_range_start)/($db_range_end - $db_range_start)."\",\"prob\":\"".$rowN2."\",\"pos\":\"".$rowN1."\"}"; 
   if($rowN2 > $max_prob){
    	$max_prob = $rowN2;
    }
    $prev_pheno = $pheno;
  }
  $rtnString = $rtnString . "]|" . $max_prob;
	
  $stmt->free_result();
  $stmt->close();
  mysqli_close($conn);
  
  echo $rtnString;
  
  function returnError($str){
    echo $str;
  }

  function _cvtZoom($str) {
    preg_match("/^[0-9]+/", $str, $r1);
    preg_match('/[b,k]$/', $str, $r2);
    $v=$r1[0];
    if($r2[0] == "b"){
      $r=1*(int)$v;
    } else {
      $r=1000*(int)$v;
    }
    return (int)$r;
  }

  function _validate_chrs($conn, $prm_Chr){
    $flag = false;
    $query = "select seq from sys_chromosome where id=? limit 1";
    $stmt = $conn->stmt_init();
    $stmt->prepare($query);
    $stmt->bind_param("s", $prm_Chr);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($row0);
    while ($stmt->fetch()) {
        $flag = true;
    }
    $stmt->free_result();
    $stmt->close();
    if($flag){
       return true;
    }else{
       return false;
    }
  }

?>
