<?php
$var = @$_GET['File'] ;
$file = trim($var);                 // Get the passed filename
if (empty($file)) {exit;}
$myArray = explode (".", $file);    // Split it up into dotted components
$extent = array_pop($myArray);      // Get extension of file
$ThisName = implode('.', $myArray); // Reconstruct the remaining of the passed file name
require_once("Downloader.inc");     Include the database login information
$sql = "SELECT COUNT(*) AS myRecs FROM information_schema.tables WHERE table_schema = '$database' AND table_name = '$tablename'";
$stmt = $conn->prepare($sql);
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC))  {
    $dcount = $row['myRecs'] ;
}

//   If dcount is 0 then the table does not exist, so we will create it

if ($dcount === 0){

    //      Change any details or fields below if required.

    //      ***** remember that additional fields may require the INSERT and UPDATE statements to be edited.

    $sql = "CREATE TABLE $tablename (
    Id int(10) AUTO_INCREMENT PRIMARY KEY NOT NULL COMMENT 'Primary Key',
    Collateral varchar(60) NOT NULL COMMENT 'Name of Collateral',
    Type varchar(10) NOT NULL COMMENT 'Type of Collateral',
    DownloadCount int(10) NOT NULL COMMENT 'Counter',
    FirstDownload timestamp NOT NULL DEFAULT current_timestamp() COMMENT 'Date of First Download',
    LastDownload timestamp NOT NULL DEFAULT current_timestamp() COMMENT 'Date and Time of Last Download'
    ) ENGINE=InnoDB DEFAULT CHARSET=ascii COLLATE=ascii_general_ci COMMENT='Table of Download Counters'";
    try {
        $conn->exec($sql);
        } catch(PDOException $e) {
            echo "Error creating table: " . $e->getMessage();
    }
}

if (!is_dir($DownDir)) {
    echo "Directory '{$DownDir}' not found.";
    exit;
}

$filename = $DownDir . '/' . $file;
clearstatcache();                   // Clear the cache

    //      Check to see if the file exists

if (!file_exists($filename)) {
    echo "The file '$file' does not exist on the server.";
    exit;
}
    //      Now we will check if the counter record for the file exists

$query = "SELECT Collateral, Type, DownloadCount, Id, COUNT(*) FROM $tablename WHERE Collateral = '" . $ThisName . "' AND Type = '". $extent  . "'" ;
$stmt = $conn->prepare($query);
$stmt->execute();
$count = $stmt->rowCount();

    //      Set to your time zone

date_default_timezone_set('America/Chicago');

$mydate = date('Y-m-d H:i:s', time());
while($row=$stmt->fetch(PDO::FETCH_ASSOC))  {
$myID = $row['Id'];
$dcount = $row['DownloadCount'] ;
}

    //      If the counter is empty or less than 1 insert a record

if (($dcount < "1") or (empty($dcount))) {
    $dcount = 1;

    //      If you add fields to the table you need to mirror those changes in here

    $query =  "INSERT INTO $tablename (Collateral, Type, DownloadCount, LastDownload)
                VALUES('$ThisName', '$extent', '$dcount', '$mydate')";
} else {

    //      If you add fields to the table you need to mirror those changes in here

    $dcount = $dcount + 1;
    $query = "UPDATE $tablename SET DownloadCount = '$dcount',
    LastDownload = '$mydate'
    WHERE Id = '$myID'";
}
$stmt = $conn->prepare($query);
try {
    $stmt->execute();
    }
catch(PDOException $e)
    {
    echo $query . "<br>" . $e->getMessage();
    }

    //      Close the connection

$conn = null;

//      redirect to the real file to be downloaded

header('Location: https://' .  $_SERVER["SERVER_NAME"] .'/' . $DownDir . '/' . $file);
?>