<?php
    include("./connection1.php");

    $msgErr = "";
    if (!isset($_REQUEST["sessionid"]) || empty($_REQUEST["sessionid"]) ) {header("HTTP/1.1 400"); $msgErr .= "(falta sessionid)";}
    if (!isset($_REQUEST["dir"])    || empty($_REQUEST["dir"]))     { header("HTTP/1.1 400"); $msgErr .= "(falta dir)";}
    if (!isset($_REQUEST["ref"])    || empty($_REQUEST["ref"]))     { header("HTTP/1.1 400"); $msgErr .= "(falta ref)";}
    
    $salida = new stdClass();
    
    if (!empty($msgErr)){
        header("Content-Type:application/json");
        http_response_code(400);
        $salida->rsp = false;
        $salida->msg = "No se recibio el parámetro ". $msgErr;
        echo (json_encode($salida));
        return;
    }

    $sessid = preg_replace("/[^a-zA-Z0-9]/", "", $db->real_escape_string($_REQUEST["sessionid"]));
    $dir    = preg_replace("/[^a-zA-Z0-9]/", "", $db->real_escape_string($_REQUEST["dir"]));
    $ref    = preg_replace("/[^a-zA-Z0-9]/", "", $db->real_escape_string($_REQUEST["ref"]));
    // validar tipos
    if (!ctype_alnum($sessid)) {header("HTTP/1.1 400"); $msgErr .= " (sessionid invalido)";}
    if (!ctype_alnum($dir)) {header("HTTP/1.1 400"); $msgErr .= " (dir invalido)";}
    if (!ctype_alnum($ref)) {header("HTTP/1.1 400"); $msgErr .= " (ref invalido)";}
    
    if (!empty($msgErr)){
        header("Content-Type:application/json");
        http_response_code(400);
        $salida->rsp = false;
        $salida->msg = "No se recibio el parámetro". $msgErr;
        echo (json_encode($salida));
        return;
    }

    $sql =  "SELECT     C.id " .
            "FROM       ret" . $dir . " R " .
            "INNER JOIN documents D " .
            "ON         R.documentid = D.id " .
            "INNER JOIN customers C " .
            "ON         D.customerid = C.id " .
            "WHERE      sessionid= ? " .
            "AND        D.id= ?";
    //Preparamos el statement
    $stmt =  $db->prepare($sql);
    //Remplazamos los parametros en la consulta almacenada
    $stmt->bind_param("ss", $sessid, $ref);
            
    //Validamos la ejecuci
    if (!($stmt->execute())){
        header("Content-Type:application/json");
        http_response_code(500);
        $salida->rsp = false;
        $salida->msg = mysqli_error($db);
        echo (json_encode($salida));
        return;
    }
    //Obtenemos los resultados y recorremos
    $result = $stmt->get_result();
    if (!($rs = mysqli_fetch_array($result))){
        header("Content-Type:application/json");
    	switch (mysqli_errno($db)){
    	    case 0:
        	    http_response_code(401);
                $salida->rsp = false;
                $salida->msg = "Documento no encontrado";
                echo (json_encode($salida));
                return;
                break;
            default:
                http_response_code(500);
    	        $salida->rsp = false;
                $salida->msg = mysqli_error($db);
                echo (json_encode($salida));
                return;
                break;
        }
    }

    $file = "../../data/customer/".$dir."/".$ref.".pdf";
    if (!file_exists($file)){
        header("Content-Type:application/json");
        http_response_code(404);
        $salida->rsp = false;
        $salida->msg = "Archivo no encontrado";
        echo (json_encode($salida));
        return;
    }else{
        header("Content-type:application/pdf");
        // It will be called downloaded.pdf
        //header("Content-Disposition:attachment;filename='downloaded.pdf'");
        // The PDF source is in original.pdf
        readfile($file);
    }
            
?>