<?php
session_start();
if(!$_SESSION['researcher_id']) {
    header("Location: login.php");
    exit;
}

require_once 'db.function.php';

$db = getDB();

if(isset($_GET['search_q']) && trim($_GET['search_q'])) {
    $q  = $_GET['search_q'];
    $_SESSION['last_search_q'] = $q;
    $q = str_replace("%", "%%", $q);
    $_SESSION['last_search_result'] = $db->getCol("select bedfile_id from bedfile where name like ? or header like ? or descr like ?", 0, array("%$q%", "%$q%", "%$q%"));
} else if(isset($_GET['name'])) {    // this is an advanced search
    //file_put_contents("/tmp/dasrsearch.log", print_r($_GET, true));
    if(trim($_GET['bool']) == 'and') {
        $bool = 'and';
    } else {
        $bool = 'or';
    }
    $date_cl = '';
    if(isset($_GET['date']) && trim($_GET['date'])) {
        if(strpos($_GET['date'], '-') !== false) {
            list($start, $end) = explode('-', $_GET['date'], 2);
            $date_elts = array();
            if(trim($start)) {
                $date_elts[] = "date_format(upload_date, '%Y-%m-%d') >= " . date("'Y-m-d'", strtotime($start));
            }
            if(trim($end)) {
                $date_elts[] = "date_format(upload_date, '%Y-%m-%d') <= " . date("'Y-m-d'", strtotime($end));
            }
            if(count($date_elts)) {
                $date_cl = $bool . ' (' . join(' AND ', $date_elts) . ')';
            }
        } else if(preg_match("/\d\d?\/\d\d?\/\d\d(\d\d)?/", $_GET['date'])) {
            $date_cl = "$bool date_format(upload_date, '%Y-%m-%d') = " . date("'Y-m-d'", strtotime($_GET['date']));
        }
    }
    $name = "%$_GET[name]%";
    $header = "%$_GET[header]%";
    $descr = "%$_GET[descr]%";
    $params = array($name, $header, $descr);
    $genome_cl = $method_cl = '';
    if($_GET['genome']) {
        $params[] = $_GET['genome'];
        $genome_cl = "$bool genome_id = ?";
    }
    if($_GET['method']) {
        $params[] = $_GET['method'];
        $genome_cl = "$bool method_id = ?";
    }
    $q = '';
    foreach($_GET as $k => $v) {
        $q .= "$k:$v ";
    }
    $_SESSION['last_search_q'] = $q;
    $_SESSION['last_search_result'] = $db->getCol("select bedfile_id from bedfile where name like ? $bool header like ? $bool descr like ? $date_cl $genome_cl $method_cl", 0, $params);
    //file_put_contents("/tmp/dasrsearch.log", "select bedfile_id from bedfile where name like ? $bool header like ? $bool descr like ? $date_cl $genome_cl $method_cl\n".print_r($params, true));
    //print("select bedfile_id from bedfile where name like ? $bool header like ? $bool descr like ? $date_cl $genome_cl $method_cl\n".print_r($params, true));
}

header("Location: exp.php?id=0&search=1");
//print_r($_SESSION);

?>
