<?php

namespace Modules\AdvancedTransfer\Http\Controllers;

use App\System;
use Composer\Semver\Comparator;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;

class InstallController extends Controller
{
    /**
     * @var string
     */
    private $module_name;
    /**
     * @var string
     */
    private $app_version;

    public function __construct()
    {
        $this->module_name = config('tpstransfer.name');
        $this->app_version = config('tpstransfer.module_version');
    }

    /**
     * Install
     *
     * @return RedirectResponse
     */
    public function index()
    {
        if (!auth()->user()->can('superadmin')) {
            abort(403, 'Unauthorized action.');
        }

        ini_set('max_execution_time', 0);
        ini_set('memory_limit', '512M');

        $this->installSettings();

        //Check if installed or not.
        $is_installed = System::getProperty($this->module_name . '_version');
        if (empty($is_installed)) {
            DB::statement('SET default_storage_engine=INNODB;');
            Artisan::call('module:migrate', ['module' => $this->module_name]);
            Artisan::call('module:seed', ['module' => $this->module_name]);
            System::addProperty($this->module_name . '_version', $this->app_version);
        }

        $output = ['success' => 1,
            'msg' => 'AdvancedTransfer module installed successfully'
        ];

        return redirect()
            ->action('\App\Http\Controllers\Install\ModulesController@index')
            ->with('status', $output);
    }

    /**
     * Initialize all install functions
     *
     */
    private function installSettings()
    {
        config(['app.debug' => true]);
        Artisan::call('config:clear');
    }

    /**
     * Installing Module
     */
    public function install()
    {
        try {
            DB::beginTransaction();

            $is_installed = System::getProperty($this->module_name . '_version');
            if (!empty($is_installed)) {
                abort(404);
            }

            DB::statement('SET default_storage_engine=INNODB;');
            Artisan::call('module:migrate', ['module' => $this->module_name]);
            Artisan::call('module:publish', ['module' => $this->module_name]);
            System::addProperty($this->module_name . '_version', $this->appVersion);

            DB::commit();

            $output = ['success' => 1,
                'msg' => 'AdvancedTransfer module installed successfully'
            ];
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::emergency("File:" . $e->getFile(). "Line:" . $e->getLine(). "Message:" . $e->getMessage());

            $output = [
                'success' => false,
                'msg' => $e->getMessage()
            ];
        }
        return redirect()
            ->action('\App\Http\Controllers\Install\ModulesController@index')
            ->with('status', $output);
    }

    /**
     * Uninstall
     * @return RedirectResponse
     */
    public function uninstall()
    {
        if (!auth()->user()->can('superadmin')) {
            abort(403, 'Unauthorized action.');
        }

        try {
            System::removeProperty($this->module_name . '_version');

            $output = ['success' => true,
                'msg' => __("lang_v1.success")
            ];
        } catch (\Exception $e) {
            $output = ['success' => false,
                'msg' => $e->getMessage()
            ];
        }

        return redirect()->back()->with(['status' => $output]);
    }

    /**
     * update module
     * @return RedirectResponse
     */
    public function update()
    {
        if (!auth()->user()->can('superadmin')) {
            abort(403, 'Unauthorized action.');
        }

        try {
            DB::beginTransaction();
            ini_set('max_execution_time', 0);
            ini_set('memory_limit', '512M');

            $tps_version = System::getProperty($this->module_name . '_version');

            if (Comparator::greaterThan($this->app_version, $tps_version)) {
                ini_set('max_execution_time', 0);
                ini_set('memory_limit', '512M');

                //clear cache & config file
                config(['app.debug' => true]);
                Artisan::call('config:clear');
                Artisan::call('cache:clear');

                DB::statement('SET default_storage_engine=INNODB;');
                Artisan::call('module:migrate', ['module' => $this->module_name]);
                Artisan::call('module:publish', ['module' => $this->module_name]);
                System::setProperty($this->module_name . '_version', $this->app_version);

                Artisan::call('apidoc:generate');
            } else {
                abort(404);
            }

            DB::commit();

            $output = ['success' => 1,
                'msg' => 'AdvancedTransfer module updated Successfully to version ' . $this->app_version . ' !!'
            ];

            return redirect()->back()->with(['status' => $output]);
        } catch (Exception $e) {
            DB::rollBack();
            die($e->getMessage());
        }
    }
}
