<?php

class AVForums_Competitions_ViewPublic_Download extends XenForo_ViewPublic_Base
{
	public function renderRaw()
	{
		$optIns = array();
		if (!empty($this->_params['optIns']))
		{
			$optIns = $this->_params['optIns'];
		}

		$winners = array();
		if (!empty($this->_params['winners']))
		{
			$winners = $this->_params['winners'];
		}

		$competition = $this->_params['competition'];

		$fileName = preg_replace('/[^A-Za-z0-9_ .-]/', '', strtolower($competition['competition_title'])) . '.csv';

		if ($winners)
		{
			$fileName = $competition['competition_id'] . '_winners_' . str_replace(' ', '_', $fileName);
		}
		else
		{
			$fileName = $competition['competition_id'] . '_' . str_replace(' ', '_', $fileName);
		}

		$filePath = XenForo_Helper_File::getTempDir() . '/' . $fileName;

		$fileHandle = fopen($filePath, 'w');

		if ($optIns)
		{
			$i = 0;
			foreach ($optIns AS $entryId => $optIn)
			{
				$i++;
				if ($i == 1)
				{
					$line = implode(',', array('entry_id', 'competition_id', 'user_id', 'username', 'email'));

					fwrite ($fileHandle, $line);
					fwrite ($fileHandle, "\n");

					$line = implode(',', $optIns[$entryId]);
				}
				else
				{
					$line = implode(',', $optIns[$entryId]);
				}

				fwrite ($fileHandle, $line);
				fwrite ($fileHandle, "\n");
			}
		}

		if ($winners)
		{
			$i = 0;
			foreach ($winners AS $entryId => $winner)
			{
				$i++;
				if ($i == 1)
				{
					$line = implode(',', array('entry_id', 'competition_id', 'user_id', 'username', 'email', 'entry_state'));

					fwrite ($fileHandle, $line);
					fwrite ($fileHandle, "\n");

					$line = implode(',', $winners[$entryId]);
				}
				else
				{
					$line = implode(',', $winners[$entryId]);
				}

				fwrite ($fileHandle, $line);
				fwrite ($fileHandle, "\n");
			}
		}

		fclose ($fileHandle);

		$this->_response->setHeader('Content-type', 'application/octet-stream', true);
		$this->setDownloadFileName($fileName);

		return new XenForo_FileOutput($filePath);
	}
}