<?php

namespace Modules\IdexxLab\Http\Controllers;

use App\System;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;

/**
 * IdexxLab install flow. IdexxLab is a LabCore vendor module — it has no UI
 * of its own (LabCore serves /lab) and reuses LabCore's `lab.*` permissions.
 * Installing it migrates the IDEXX analyte-map seed.
 */
class InstallController extends Controller
{
    private $module_name;
    private $app_version;

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

    public function index()
    {
        if (!auth()->user()->can('superadmin')) {
            abort(403, 'Unauthorized action.');
        }

        if (empty(System::getProperty('LabCore_version'))) {
            $output = ['success' => 0, 'msg' => 'Please install the LabCore module first.'];
            return redirect()
                ->action('\App\Http\Controllers\Install\ModulesController@index')
                ->with('status', $output);
        }

        ini_set('max_execution_time', 0);
        ini_set('memory_limit', '512M');
        config(['app.debug' => true]);
        Artisan::call('config:clear');

        $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:publish', ['module' => $this->module_name]);
            System::addProperty($this->module_name . '_version', $this->app_version);
        }

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

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

    public function install()
    {
        if (!auth()->user()->can('superadmin')) {
            abort(403, 'Unauthorized action.');
        }

        try {
            if (empty(System::getProperty('LabCore_version'))) {
                throw new \Exception('Please install the LabCore module first.');
            }

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

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

            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->app_version);

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

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

    public function update()
    {
        if (!auth()->user()->can('superadmin')) {
            abort(403, 'Unauthorized action.');
        }

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

            Artisan::call('module:migrate', ['module' => $this->module_name]);
            System::setProperty($this->module_name . '_version', $this->app_version);

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

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

    public function uninstall()
    {
        if (!auth()->user()->can('superadmin')) {
            abort(403, 'Unauthorized action.');
        }

        try {
            System::removeProperty($this->module_name . '_version');
            $output = ['success' => 1, 'msg' => 'IdexxLab module uninstalled successfully'];
        } catch (\Exception $e) {
            \Log::emergency('File:' . $e->getFile() . ' Line:' . $e->getLine() . ' Message:' . $e->getMessage());
            $output = ['success' => 0, 'msg' => $e->getMessage()];
        }

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