<?php

namespace App\Helpers\Classes;

use Theme;
use Setting;
use ZipArchive;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Session;
use Jackiedo\DotenvEditor\Facades\DotenvEditor;

class UpdatesManager
{
    protected $product = 'monster-tools';
    private $version = '3.0.0';

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->verifyData = [
            'code' => 'Megaeducate@555',
            'version' => $this->version,
            'item'  => $this->product,
            'return_uri'  => url('/'),
        ];
    }

    public function runUpdate()
    {
        $success = session('success');
        $error = session('error');

        $this->optimizeApp();
        $this->runMigration();
        $this->rebuildTheme();
        $this->updateAppVersion();
        $this->optimizeApp();

        // Flash success and error messages, if any
        Session::flash('success', $success);
        Session::flash('error', $error);

        return compact('success', 'error');
    }

    private function getAppVersion()
    {
        return $this->version;
    }

    public function rebuildTheme()
    {
        Theme::rebuildCache();
    }

   public function runMigration()
    {
        Artisan::call('migrate', ['--force' => true]);
        if (version_compare(setting('version'), '1.4.0', '<')) {
            Artisan::call("db:seed", ['--class' => 'HomepageSeeder', '--force' => true]);
        }

        if (file_exists(base_path('database/seeders/UpdateToolSeeder.php'))) {
            Artisan::call("db:seed", ['--class' => 'UpdateToolSeeder', '--force' => true]);
        }

        if (file_exists(base_path('database/seeders/UpdateToolSeeder210.php')) && version_compare(setting('version'), '2.0.0', '<')) {
            Artisan::call("db:seed", ['--class' => 'UpdateToolSeeder210', '--force' => true]);
        }

        if (file_exists(base_path('database/seeders/UpdateToolSeeder220.php'))) {
            Artisan::call("db:seed", ['--class' => 'UpdateToolSeeder220', '--force' => true]);
        }

        if (file_exists(base_path('database/seeders/NewToolsSeeder.php'))) {
            Artisan::call("db:seed", ['--class' => 'NewToolsSeeder', '--force' => true]);
        }
    }

    private function updateAppVersion()
    {
        $version = $this->getAppVersion();

        $env = DotenvEditor::load();
        $env->setKey('APP_VERSION', $version);
        $env->save();

        Setting::set('version', $version);
        Setting::save();
    }

    private function optimizeApp()
    {
        try {
            Artisan::call('cache:clear');
            Artisan::call('optimize');
        } catch (\Exception $e) {
            // Handle exceptions as needed
        }
    }

    public function checkUpdates()
    {
        // Skip any update checking since no valid update sources are available
        return true;
    }
}
