<?php

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

  ////////////////////////////////// prepare
  $prm_Chr = $_POST['chr'];
  (isset($_POST['phenotype'])) ? $prm_Pheno = $_POST['phenotype']:returnError("Error");
  $phenotypes = array();
  $str;

  $stmtP = $conn->stmt_init();
  if (isset($prm_Chr) && $prm_Chr != "all") {
  	$queryP = "SELECT chr,pos, prob FROM sys_phenotype_prob where chr= ? and prob > 2 and phenotype_id = (select phenotype_id from sys_phenotype where phenotype = ?)";
	$stmtP->prepare($queryP);
	$stmtP->bind_param("ss", $prm_Chr,$prm_Pheno);
  } else {
  	$queryP = "SELECT chr, pos, prob FROM sys_phenotype_prob where prob > 2 and phenotype_id = (select phenotype_id from sys_phenotype where phenotype = ?)";
	$stmtP->prepare($queryP);
	$stmtP->bind_param("s", $prm_Pheno);
  }
  $stmtP->execute();
  $stmtP->store_result();
  $stmtP->bind_result($row0,$row1,$row2);

  $phenotypes = array();
  while ($stmtP->fetch()) {
	$phenotypes[$row0.",".$row1] = $row2;
  }

  $stmtP->close();
  
  if(isset($prm_Chr) && $prm_Chr != "all") {
  	$queryQ = "SELECT size FROM sys_chromosome where id = ?";
  } else {
  	$queryQ = "SELECT id,size FROM sys_chromosome order by id";
  }

  $stmtQ = $conn->stmt_init();
  $stmtQ->prepare($queryQ);
  if(isset($prm_Chr) && $prm_Chr != "all") {
	$stmtQ->bind_param("s", $prm_Chr);
  }
  $stmtQ->execute();
  $stmtQ->store_result();
  $stmtQ->bind_result($row0,$row1);
  $chrlen = array();
  $chrnum;
  $chrcount = 0;
  $chrsize;
  while ($stmtQ->fetch()) {
	$chrlen[$row0] = $row1;
	$chrnum[$row0] = $chrcount;
	$chrcount++;
  }

  $stmtQ->close();

  foreach($phenotypes as $pos => $prob) {
        $poss = explode(",",$pos);
        $chr = $poss[0];
        $len = $poss[1];
	$len2 = number_format($len);
	if (isset($prm_Chr) && $prm_Chr != "all") {
		$str .= $len.'--SPL--'.$prob.'--SPL--'.$chr." ".$len2."--SPL--".$chrlen[$chr]."|";
	} else {
		$lenpos = $len/$chrlen[$chr] + $chrnum[$chr];
                $str .= $lenpos.'--SPL--'.$prob.'--SPL--'.$chr." ".$len2."--SPL--".$chrlen[$chr]."|";
	}	
  }
  $str = rtrim($str, '|');
  echo $str;

function returnError($str){
    echo $str;
}
?>
