<?php

namespace CCDN\Controllers;

use CCDN\Helpers\Controller;
use CCDN\Helpers\Facade\Cache;
use CCDN\Helpers\Facade\Http\Response;
use CCDN\Helpers\Facade\Http\Url;
use CCDN\Helpers\SecondIn;
use CCDN\Helpers\Settings;
use GuzzleHttp\Client;

class MainController extends Controller
{
    protected $viewsFolder = 'main';
    protected $parent = '';

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

    public function main()
    {
        global $config;

        $isLatestVersion = true;
        $latestVersion = json_decode(Cache::get('api_github_response'), true);

        if (!$latestVersion) {
            Cache::set('api_github_response', '', SecondIn::hour(2));
            $client = new Client([
                'timeout' => 10,
                'base_uri' => 'https://api.github.com/',
                'idn_conversion' => false,
            ]);
            $response = $client->get('/repos/dev-dle/dle-balance/commits');

            $body = json_decode($response->getBody()->getContents(), true);
            $commit = $body[0]['commit'];
            $message = explode("\n", $commit['message']);
            $version = $message[0];
            unset($message[0]);

            $latestVersion = [
                'sha' => $body[0]['sha'],
                'version' => $version,
                'message' => $message,
                'date' => date('Y-m-d H:i', strtotime($commit['committer']['date']))
            ];

            Cache::set('api_github_response', json_encode($latestVersion, JSON_UNESCAPED_UNICODE), SecondIn::HOUR);
        }

        if (isset($latestVersion['sha'])) {
            $isLatestVersion = Settings::get('git_commit_sha') === $latestVersion['sha'];
        }

        return Response::make($this->render('main', [
            'isLatestVersion' => $isLatestVersion,
            'latestVersion' => $latestVersion,
            'dleVersion' => (float)$config['version_id'],
        ]));
    }

    public function clearCache()
    {
        Cache::clear();

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

}
