<?php

namespace CCDN\Controllers;

use CCDN\Helpers\Controller;
use CCDN\Helpers\Http\Request;
use CCDN\Helpers\Facade\Http\Response;
use CCDN\Helpers\Facade\Http\Url;
use CCDN\Helpers\Logger\Log;
use CCDN\Helpers\Settings;
use DirectoryIterator;
use download;

class LogsController extends Controller
{

    protected $viewsFolder = 'log';
    protected $parent = '';

    public function __construct($parent = 'logs')
    {
        $this->parent = $parent;
    }

    public function main()
    {

        $log = new Log();

        $logFileList = $log->getLogList();
        asort($logFileList);

        return Response::make($this->render('log', [
            'logFileList' => $logFileList,
        ]));
    }

    public function printLog(Request $request)
    {
        $log = new Log();

        return Response::make($log->getLog($request->get('name')));
    }

    public function download(Request $request)
    {

        include ENGINE_DIR.'/classes/download.class.php';

        $logFile = Settings::LOG_PATH.'/'.$request->get('name');

        if (file_exists($logFile)) {
            $downLoad = new download($logFile);

            $downLoad->download_file();
        }

    }

    public function delete(Request $request)
    {

        $logFile = Settings::LOG_PATH.'/'.$request->get('name');

        if (file_exists($logFile)) {
            unlink($logFile);
        }
        Response::redirect(Url::to($this->parent));
    }

    public function deleteAll()
    {
        $i = new DirectoryIterator(Settings::LOG_PATH);

        foreach ($i as $f) {
            if ($f->isFile()) {
                unlink($f->getRealPath());
            }
        }

        Response::redirect(Url::to($this->parent));
    }

}
