<?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;
}

(isset($_POST['prm_fa_chr']) && !empty($_POST['prm_fa_chr'])) ? $prm_chr=$_POST['prm_fa_chr']:returnError("Error");
(isset($_POST['prm_fa_s']) && !empty($_POST['prm_fa_s'])) ? $prm_s=$_POST['prm_fa_s']:returnError("Error");
(isset($_POST['prm_fa_e']) && !empty($_POST['prm_fa_e'])) ? $prm_e=$_POST['prm_fa_e']:returnError("Error");
(isset($_POST['prm_blk']) && !empty($_POST['prm_blk'])) ? $prm_blk=$_POST['prm_blk']:returnError("Error");
if (!(is_numeric($prm_s)) || !(is_numeric($prm_e)) || !(is_numeric($prm_blk))) {
        $errflgs = $errflgs."1";
}
if ($prm_s > $prm_e) {
        if(isset($errflgs)) {
                $errflgs = $errflgs.",2";
        } else {
                $errflgs = $errflgs."2";
        }
}
if (($prm_e-$prm_s) > 100000*$prm_blk) {
        if(isset($errflgs)) {
                $errflgs = $errflgs.",3";
        } else {
                $errflgs = $errflgs."3";
        }
}
if (!_validate_pos($conn,$prm_chr,$prm_s,$prm_e)) {
	if(isset($errflgs)) {
                $errflgs = $errflgs.",4";
        } else {
                $errflgs = $errflgs."4";
        }
}
if(!_validate_chrs($conn,$prm_chr)) {
        if(isset($errflgs)) {
                $errflgs = $errflgs.",5";
        } else {
                $errflgs = $errflgs."5";
        }
}
echo $errflgs;
exit;

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 "1";
    }else{
       return "0";
    }
}

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

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