<?php

Kirby::plugin('kangaroopunch/download-kirbytag', [

	'routes' => function() {
		return [
			[
				'pattern' => 'download/(:any)/(:any)',
				'action' => function($sourcepage, $filerequested) {
					$file = "";
					kirby()->impersonate('kirby');
					try {
						// Unmuddle the page ID that called us.
						$slug = str_rot13(urldecode($sourcepage));
						$slug = str_replace('|', '/', $slug);
						// Get page object.
						$page = kirby()->api()->page($slug);
						// Find the current download count.
						$file = $page->file($filerequested);
						$content = $file->content();
						if ($content->has('downloads')) {
							$count = $content->get('downloads')->toInt();
						} else {
							// Initialize counter.
							$count = 0;
						}
						// Update download count.
						$count++;
						$file->update([ 'downloads' => $count ]);
					} catch (Exception $ex){
						$file = $ex->getMessage();
					}
					kirby()->impersonate();
					// Send file to user.
					return $file;
				}
			]
		];
	},

	'tags' => [
		'download' => [
			'attr' => [
				'desc'
			],
			'html' => function($tag) {
				try {
					// Did we get a valid file?
					$file = $tag->file($tag->value());
					if (!$file === true) {
						return '<div class="downloadlinkerror">ERROR:  Cannot locate "' . $tag->value() . '"!</div>';
					}
					// Ensure we're using the proper blueprint.
					kirby()->impersonate('kirby');
					$file->update([ 'template' => 'download' ]);
					kirby()->impersonate();
					// Did they provide a description?
					if (is_null($tag->desc) === true) {
						// No.  Does the file itself have one?
						$desc = $file->content()->get('description')->value();
						if (is_null($desc) || strlen($desc) == 0) {
							// Nope.  Use the filename.
							$desc = $tag->value();
						}
					} else {
						// Yep.  Use the provided description.
						$desc = $tag->desc;
					}
					// Find pretty file size.
					$units = array('B', 'KB', 'MB', 'GB', 'TB');
					$bytes = max($file->size(), 0);
					$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
					$pow = min($pow, count($units) - 1);
					$bytes /= pow(1024, $pow);
					$size = round($bytes, 2) . ' ' . $units[$pow];
					// Muddle up the page slug a bit to discourage direct linking to the file.
					$slug = str_replace('/', '|', $tag->parent()->id());
					$slug = esc(str_rot13($slug), 'url');
				} catch (Exception $ex) {
					return $ex->getMessage();
				}
				// Send the link.
				return '<a href="/download/' . $slug . '/' . esc($tag->value(), 'url') . '" class="downloadlink">' . $desc . ' (' . $size . ')</a>';
			}
		]
	]

]);
