<?php

namespace Modules\StockIssues\Http\Controllers;

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

use Illuminate\Support\Facades\DB;

class InstallController extends Controller
{
    protected $moduleName;
    protected $appVersion;

    public function __construct()
    {
        $this->moduleName = config('stock_issues.name');
        $this->appVersion = config('stock_issues.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');

        //Check if installed or not.
        $is_installed = System::getProperty($this->moduleName . '_version');
        if (empty($is_installed)) {
            Artisan::call('module:migrate', ['module' => "StockIssues"]);
            System::addProperty(strtolower($this->moduleName) . '_version', $this->appVersion);
        }

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

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

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

        try {
            System::removeProperty($this->moduleName . '_version');
            //Artisan::call('module:migrate-rollback', ['module' => "StockIssues"]);
            $output = [
                'success' => true,
                'msg' => __("lang_v1.success")
            ];
        } catch (\Exception $e) {
            $output = [
                'success' => false,
                'msg' => $e->getMessage()
            ];
        }

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