<?php

namespace App\Http\Controllers;

use App\Interfaces\MemberRepositoryInterface;
use App\Services\Data\SettingsService;

class RouteGetController extends Controller
{
    protected $dash;
    protected $gate;
    protected $theme;
    protected $front;
    protected $member;
    protected $settings;

    public function __construct(
        DashController $dashController,
        AuthController $authController,
        ThemeController $themeController,
        FrontController $frontController,
        MemberRepositoryInterface $memberRepo,
        SettingsService $settingsService,
    ) {
        $this->dash     = $dashController;
        $this->gate     = $authController;
        $this->theme    = $themeController;
        $this->front    = $frontController;
        $this->member   = $memberRepo;
        $this->settings = $settingsService;
    }

    public function handleRequest($first = null, $second = null, $third = null, $fourth = null)
    {
        if (isset($first) && !is_numeric($first)) {
            switch ($first) {
                case 'dashboard':
                    if ($this->member::status()) {
                        return $this->dash->init($second, $third, $fourth);
                    } else {
                        return $this->dash->login();
                    }
                    break;
                case 'theme':
                    if ($this->member::status()) {
                        if (isset($second)) {
                            return $this->theme->getView($third, $fourth);
                        } else {
                            return $this->theme->start();
                        }
                    } else {
                        return $this->dash->login();
                    }
                    break;
                case 'tags':
                case 'archives':
                    return $this->front->page($first, $second, $third);
                    break;
                case 'backup':
                    return $this->downloadBackup($second);
                    break;
            }
        } else {
            return $this->front->index($first, $second, $third);
        }
    }

    private function downloadBackup($type)
    {
        if ($this->member::status()) {
            $latest = '';
            $file   = '';
            if ($type == 'content-download') {
                $latest = $this->settings->getGlobal()['last_content_backup'];
                $file   = 'backup-content-' . $latest . '.zip';
            } else {
                $latest = $this->settings->getGlobal()['last_files_backup'];
                $file   = 'backup-files-' . $latest . '.zip';
            }

            return response()->download(
                '../content/backups/' . $file,
                $file,
                ['Content-Type: application/zip']
            );
        }
    }
}