<?php
    ob_start();
    
    // continue the session
    session_start();
    
    include '../php_only_scripts/database.php';
    
    if (isset($_GET['id']) && basename($_GET['id']) == $_GET['id'] && 
        isset($_GET['tbl']) && basename($_GET['t']) == $_GET['t']&& 
        isset($_GET['idf']) && basename($_GET['idf']) == $_GET['idf'] && 
        isset($_GET['bf']) && basename($_GET['bf']) == $_GET['bf']) {
        // Init 
        $userRow=null;

        // Create and Setup the database
        $db = new Database();
        $db->setupTmsDB();

        // Attempt to log in with this user
        $currentUser = $db->getLoggedInSessionUser(session_id());

        // If there is only one result for a username/password combo, then they are good to go.
        if ($currentUser == null){
            exit;
        }
        elseif (mysqli_num_rows($currentUser)==1){
            // Attempt to get the user row
            $userRow = $currentUser->fetch_assoc();
        }

        // if id is set then get the file with the id from database
        $id = $_GET['id'];
        $table = $_GET['tbl'];
        $idField = $_GET['idf'];
        $blobField = $_GET['bf'];
        
        // check for a passed type
        $typeFieldSQL='';
        if (isset($_GET['tyf']) ){
            // get the passed in type
            $typeFieldSQL = ', ' . $_GET['tyf'] . ' AS Type ';
        }

        // check for a passed size
        $sizeFieldSQL='';
        if (isset($_GET['szf']) ){
            // get the passed in size
            $sizeFieldSQL = ', ' . $_GET['szf'] . ' AS Size ';
        }

        // check for a passed name
        $nameFieldSQL = ', "tempName" AS Name ';
        if (isset($_GET['nmf']) ){
            // get the passed in name
            $nameFieldSQL = ', ' . $_GET['nmf'] . ' AS Name ';
        }

        $sql = 'SELECT ' . $blobField . ' AS Datum' .
               $typeFieldSQL .
               $sizeFieldSQL .
               $nameFieldSQL .
               'FROM ' . $table . ' ' . 
               'WHERE ' . $idField . '=' . $id . ';';

        // Get the attachment from the database
        $row = $db->queryDB($sql, $userRow, "show_blob Form occurance 1");
        
        // Get the current task row to work with as the assoc style
        $currentRow = $row->fetch_assoc();

        // Show the file
        if ($typeFieldSQL!='') {header("Content-Type: " . $currentRow["Type"]);}
        if ($sizeFieldSQL!='') {header("Content-Length: " . $currentRow["Size"]);}
        header("Content-Disposition: attachment; filename=" .$currentRow["Name"]);
        header('Content-Transfer-Encoding: binary');
        
        // Clean it up before we send out the file
        while (ob_get_level()) {
            ob_end_clean();
        }
        
        // Spit out the data
        die($currentRow["Datum"]);
    }
    exit;
?>