<?php

namespace Velis\Redis;

use Resque_Failure_Interface;
use stdClass;
use Velis\App;

class Failure implements Resque_Failure_Interface
{
	/**
	 * Initialize a failed job class and save it (where appropriate).
	 *
	 * @param object $payload Object containing details of the failed job.
	 * @param object $exception Instance of the exception that was thrown by the failed job.
	 * @param object $worker Instance of Resque_Worker that received the job.
	 * @param string $queue The name of the queue the job was fetched from.
	 */
    public function __construct($payload, $exception, $worker, $queue)
    {
		$data = new stdClass;
		$data->failed_at = date('c');
		$data->payload = $payload;
		$data->exception = get_class($exception);
		$data->error = $exception->getMessage();
		$data->backtrace = explode("\n", $exception->getTraceAsString());
		$data->worker = (string) $worker;
		$data->queue = $queue;
		$data = json_encode($data);

		self::appendLog($data);
    }

	private static function appendLog(string $data): void
	{
		if (!App::$config->resque || App::$config->resque->logs != 1) {
			return;
		}

		$dir = DATA_PATH . 'log/resque/';
		$filename = date('Y-m-d') . '.log';

		file_put_contents($dir . $filename, $data . "\n", FILE_APPEND);
	}
}