<?php
	// stream a file from the media dir by db id
	$db = new SQLite3('netv-mam.sqlite');

	if (isset($_GET['id']) && $_GET['id'] !== '') {
		$query = $db->prepare("SELECT * FROM media WHERE id = :id");
		$query->bindValue(':id', intval($_GET['id']));
		$result = $query->execute();

		if ($result) {
			$row = $result->fetchArray(SQLITE3_ASSOC);
			$path = $row['source_path'];

			// get the file's mime type to send the correct content type header
			$finfo = finfo_open(FILEINFO_MIME_TYPE);
			$mime_type = finfo_file($finfo, $path);
			$public_name = basename($path);

			// send the headers
			if (isset($_GET['download']) && $_GET['download'] === "true") { header("Content-Disposition: attachment; filename=$public_name;"); }
			header("Content-Type: $mime_type");
			header('Content-Length: ' . filesize($path));

			$fp = fopen($path, 'rb');
			fpassthru($fp);
			exit;
		}
	}
?>