<?php
// app/api/uploads/show

    //header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid");
    if (!parametrosValidos($_GET, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(",", $parmsob)));
    }
    
    //Definicion de variables y almacenamiento de valores enviados por GET
    $sessionid = $_GET["sessionid"];
    $upid = '';
    $payid = '';
    
    // Validamos que id obtenemos upid = uploads
    if(isset($_GET['upid']) && $_GET['upid'] != '' && isset($_GET['payid']) && $_GET['payid'] != ''){
        badEnd('500',array("msg"=>"No enviar ambos parametros payid y upid"));
    }else{
        if(isset($_GET['upid']) && $_GET['upid'] != ''){
            $upid = (int)$_GET['upid'];
        }else if(isset($_GET['payid']) && $_GET['payid'] != ''){
            $payid = (int)$_GET['payid'];
        }
    }
    
    //Validamos la session
    $userid = isSessionValid($db, $sessionid);
    
    if($upid != ''){
        // Verificamos que exista la imagen
        $sql = "SELECT COUNT(userid) AS qty FROM useruploads".
        "       WHERE userid = ".$userid.
        "       AND prefuploadid = ".$upid;
        if (!$rs=$db->query($sql)){
            badEnd("500", array("msg"=>determinateDBError($db)));
        }
            
        $row = $rs->fetch_assoc();
        
        // Si es 0 no existe
        if($row['qty'] == 0){
            header("HTTP/1.1 404");
            die();
        }
        
        // Obtenemos los detalles del documento
        $sql = "SELECT * FROM useruploads".
        "       WHERE userid = ".$userid.
        "       AND prefuploadid = ".$upid;
        if (!$rs=$db->query($sql)){
            badEnd("500", array("msg"=>determinateDBError($db)));
        }
        
        $row = $rs->fetch_assoc();
        
        // Buscamos el documento en los directorios
        $urlLocal = "../../../uploads/users/".$userid."/".str_pad($row["prefuploadid"], 2, "0", STR_PAD_LEFT).".{jpg,png,jpeg,pdf,PNG,JPG,JPEG,PDF}";
        //#NEW
        //$urlLocal = "../../../uploads/users/".$userid."/".md5((str_pad($row["prefuploadid"], 2, "0", STR_PAD_LEFT))."afxdecodekey").".{jpg,png,jpeg,pdf,PNG,JPG,JPEG,PDF}";
                
        //Buscamos el archivo para obtener su nombre y extension
        $filestest = glob($urlLocal, GLOB_BRACE);
        
        //El primer resultado
        $info = pathinfo($filestest[0]);
        
        if($info['basename'] != ""){
            $fl = fopen($info['dirname']."/".$info['basename'], 'rb');
            
            header("Content-Length: " . filesize($info['dirname']."/".$info['basename']));
            header("Content-Type: ".$row['filetype']);
            fpassthru($fl);
        }else{
            header("HTTP/1.1 404");
            die();
        }
    }else if($payid != ''){
        // Validamos si existe el deposito
        $sql = "SELECT COUNT(deposits.transactionid) AS qty ".
        "       FROM deposits, accounts, transactions ".
        "       WHERE deposits.transactionid = ".$payid.
        "       AND transactions.id = deposits.transactionid ".
        "       AND transactions.accountid = accounts.id".
        "       AND accounts.userid = ".$userid;
        if (!$rs=$db->query($sql)){
            badEnd("500", array("msg"=>determinateDBError($db)));
        }
        
        $rowDeposit = $rs->fetch_assoc();
        
        // Validamos si existe el retiro
        $sql = "SELECT COUNT(withdrawals.transactionid) AS qty ".
        "       FROM withdrawals, accounts, transactions ".
        "       WHERE withdrawals.transactionid = ".$payid.
        "       AND transactions.id = withdrawals.transactionid ".
        "       AND transactions.accountid = accounts.id".
        "       AND accounts.userid = ".$userid;
        if (!$rs=$db->query($sql)){
            badEnd("500", array("msg"=>determinateDBError($db)));
        }
        
        $rowWithdrawal = $rs->fetch_assoc();
        
        // SI ambos son 0 no existe el movimiento
        if($rowDeposit['qty'] == 0 && $rowWithdrawal == 0){
            header("HTTP/1.1 404");
            die();
        }
        
        // Validamos cual es el existente
        // Si deposit es 0 buscamos el detalle del retiro
        if($rowDeposit['qty'] == 0){
            $sql = "SELECT withdrawals.* ".
            "       FROM withdrawals, accounts, transactions ".
            "       WHERE withdrawals.transactionid = ".$payid.
            "       AND transactions.id = withdrawals.transactionid ".
        "       AND transactions.accountid = accounts.id".
            "       AND accounts.userid = ".$userid;
            if (!$rs=$db->query($sql)){
                badEnd("500", array("msg"=>determinateDBError($db)));
            }
            
            $row = $rs->fetch_assoc();
        }else{
            $sql = "SELECT deposits.* ".
            "       FROM deposits, accounts, transactions ".
            "       WHERE deposits.transactionid = ".$payid.
            "       AND transactions.id = deposits.transactionid ".
            "       AND transactions.accountid = accounts.id".
            "       AND accounts.userid = ".$userid;
            if (!$rs=$db->query($sql)){
                badEnd("500", array("msg"=>determinateDBError($db)));
            }
            
            $row = $rs->fetch_assoc();
        }
        
        // Buscamos el documento en los directorios
        $urlLocal = "../../../uploads/payments/".$row['transactionid'].".{jpg,png,jpeg,pdf,PNG,JPG,JPEG,PDF}";
        
        //Buscamos el archivo para obtener su nombre y extension
        $filestest = glob($urlLocal, GLOB_BRACE);
        
        //El primer resultado
        $info = pathinfo($filestest[0]);
        
        if($info['basename'] != ""){
            $fl = fopen($info['dirname']."/".$info['basename'], 'rb');
            
            header("Content-Length: " . filesize($info['dirname']."/".$info['basename']));
            header("Content-Type: ".$row['filetype']);
            fpassthru($fl);
        }else{
            header("HTTP/1.1 404");
            die();
        }
    }
?>
