<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Support\Facades\DB;

class UpgradeController extends AdminController
{
    /**
     * Execute an action on the controller.
     *
     * @param string $method
     * @param array $parameters
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function callAction($method, $parameters)
    {
        $this->authorize('super_admin');

        return parent::callAction($method, $parameters);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function index()
    {
        return \view('admin.upgrade.index');
    }

    public function process()
    {
        @ini_set('memory_limit', '1024M');
        @set_time_limit(10 * 60);
        @ini_set('max_execution_time', 10 * 60);

        try {
            $result = \Artisan::call('migrate', ['--force' => true]);
        } catch (\Exception $ex) {
            $result = $ex->getMessage();
        }

        if ($result !== 0) {
            \session()->flash('danger', $result);

            return \redirect()->route('admin.upgrade');
        }

        DB::table('options')
            ->where('name', 'version')
            ->update(['value' => APP_VERSION]);

        \Artisan::call('optimize:clear');

        \session()->flash('success', __('Database upgraded successfully.'));

        return \redirect()->route('admin.dashboard');
    }
}
