<?php

namespace Database\Seeders;

use App\Models\Device;
use App\Models\Documentation;
use App\Models\User;
use App\Models\Package;
use App\Models\Setting;
use App\Http\Controllers\SettingController;
use Carbon\Carbon;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;

class DatabaseSeeder extends Seeder
{
  /**
   * Seed the application's database.
   *
   * @return void
   */
  public function run()
  {
    $this->specialMigration();

    // table users seeder
    $users = [
      [
        'id' => 1,
        'name' => 'admin',
        'email' => 'admin@admin.com',
        'email_verified_at' => now(),
        'phone' => '16264838489',
        'password' => Hash::make('password'),
        'role' => 'admin',
        'package_id' => 1,
        'trial_period' => 125,
        'billing_interval' => 'monthly',
        'billing_start' => now(),
        'billing_end' => Carbon::now()->addYears(1),
      ],
      [
        'id' => 2,
        'name' => 'bank',
        'email' => 'bank@bank.com',
        'email_verified_at' => now(),
        'phone' => '18184838489',
        'password' => Hash::make('password'),
        'role' => 'admin',
        'package_id' => 1,
        'trial_period' => 125,
        'billing_interval' => 'monthly',
        'billing_start' => now(),
        'billing_end' => Carbon::now()->addYears(1),
      ],
      [
        'id' => 3,
        'name' => 'demo',
        'email' => 'demo@demo.com',
        'email_verified_at' => now(),
        'phone' => '13235609448',
        'password' => Hash::make('password'),
        'role' => 'user',
        'package_id' => 2,
        'trial_period' => 125,
        'billing_interval' => 'monthly',
        'billing_start' => now(),
        'billing_end' => Carbon::now()->addYears(1),
      ],
    ];
    foreach ($users as $user) {
      if (User::where('id', '=', $user['id'])->count() == 0 && User::where('name', '=', $user['name'])->count() == 0 && User::where('email', '=', $user['email'])->count() == 0) {
        User::insert($user);
      }
    }

    // table packages seeder
    $packages = [
      [
        'name' => 'super',
        'description' => 'Super Package',
        'rate_monthly' => 0,
        'rate_yearly' => 0,
        'max_outgoing' => -1,
        'max_device' => -1,
        'max_autoreply' => -1,
        'max_phonebook' => -1,
        'webhook' => 1,
      ],
      [
        'name' => 'trial',
        'description' => 'Trial Package',
        'rate_monthly' => 0,
        'rate_yearly' => 0,
        'max_outgoing' => 100,
        'max_device' => 1,
        'max_autoreply' => 10,
        'max_phonebook' => 1,
        'webhook' => 0,
      ],
    ];
    foreach ($packages as $package) {
      if (Package::where('name', '=', $package['name'])->count() == 0) {
        Package::insert($package);
      }
    }

    // table settings seeder
    $settings = [
      [
        'key' => 'appName',
        'value' => config('app.name'),
      ],
      [
        'key' => 'appNodePort',
        'value' => config('app.node_port'),
      ],
      [
        'key' => 'appNodeUrl',
        'value' => rtrim(config('app.node_url'), '/'),
      ],
      [
        'key' => 'awg_encType',
        'value' => 'awg_encType',
      ],
      [
        'key' => 'awg_orderId',
        'value' => 'awg_orderId',
      ],
      [
        'key' => 'awg_token',
        'value' => 'awg_token',
      ],
      [
        'key' => 'currencyCode',
        'value' => 'USD',
      ],
      [
        'key' => 'landingPage',
        'value' => 'landing-v5',
      ],
      [
        'key' => 'logoUrl',
        'value' => url('/app-assets/images/logo/logo.png'),
      ],
      [
        'key' => 'nfDecimalpoint',
        'value' => '.',
      ],
      [
        'key' => 'nfDecimals',
        'value' => '2',
      ],
      [
        'key' => 'nfSeparator',
        'value' => ',',
      ],
      [
        'key' => 'supportButton',
        'value' => 1,
      ],
      [
        'key' => 'supportPhone',
        'value' => '14088999448',
      ],
      [
        'key' => 'trialPeriod',
        'value' => 15,
      ],
      [
        'key' => 'waResetPassword',
        'value' => 1,
      ],
      [
        'key' => 'waVerification',
        'value' => 1,
      ],
      [
        'key' => 'requireStrongPassword',
        'value' => 0,
      ],
      [
        'key' => 'allowUserDeleteAccount',
        'value' => 0,
      ],
    ];
    foreach ($settings as $setting) {
      if (Setting::where('key', '=', $setting['key'])->count() == 0) {
        Setting::insert($setting);
      }
    }
    // Import sql file
    $documentations = Documentation::all();
    if (empty($documentations[0])) {
      if (file_exists(public_path('app-assets/data/documentations.sql'))) DB::unprepared(file_get_contents(public_path('app-assets/data/documentations.sql')));
    }
    Documentation::where('lang', 'en')->update(['lang' => 'us']);

    // Setting::updateOrInsert(['key' => 'awg_valUrl'], ['value' => 'aHR0cDovL2xvY2FsaG9zdC92bS1sYXJhL2FwaS92YWxLZXk=']); // DO NOT EDIT !!!
    Setting::updateOrInsert(['key' => 'awg_valUrl'], ['value' => 'aHR0cHM6Ly92aXNpbWlzaS5uZXQvYXBpL3ZhbEtleQ==']); // DO NOT EDIT !!!
    Setting::updateOrInsert(['key' => 'appUrl'], ['value' => url('/')]);
    SettingController::clearCache();
  }

  private function specialMigration()
  {
    if (DB::table('migrations')->where('migration', '=', '2038_05_16_000000_Remove_After_Update_Done')) {
      DB::table('migrations')
        ->where('migration', '=', '2038_05_16_000000_Remove_After_Update_Done')
        ->delete();
    }

    Schema::table('autoreplies', function (Blueprint $table) {
      if (Schema::hasColumn('autoreplies', 'mediafile')) {
        $table->dropColumn('mediafile');
      }
    });

    Schema::table('devices', function (Blueprint $table) {
      if (Schema::hasColumn('devices', 'reset')) {
        $table->dropColumn('reset');
      }
      if (Schema::hasColumn('devices', 'mobile')) {
        $table->dropColumn('mobile');
      }
      if (Schema::hasColumn('devices', 'mobotp')) {
        $table->dropColumn('mobotp');
      }
      if (Schema::hasColumn('devices', 'backups')) {
        $table->dropColumn('backups');
      }
      if (Schema::hasColumn('devices', 'welcome_time')) {
        $table->dropColumn('welcome_time');
      }
      if (Schema::hasColumn('devices', 'welcome_pause')) {
        $table->dropColumn('welcome_pause');
      }

      if (!Schema::hasColumn('devices', 'working_hours')) {
        $table->json('working_hours')->after('status')->nullable();
      }
      if (!Schema::hasColumn('devices', 'openai')) {
        $table->json('openai')->after('status')->nullable();
      }
      if (!Schema::hasColumn('devices', 'idle')) {
        $table->smallInteger('idle')->after('status')->unsigned()->nullable()->default(0);
      }
      if (!Schema::hasColumn('devices', 'welcome_cust')) {
        $table->json('welcome_cust')->after('status')->nullable();
      }
      if (!Schema::hasColumn('devices', 'welcome_msg')) {
        $table->text('welcome_msg')->after('status')->nullable();
      }
      if (!Schema::hasColumn('devices', 'incall_msg')) {
        $table->text('incall_msg')->after('status')->nullable();
      }
      if (!Schema::hasColumn('devices', 'autoreply_reset_msg')) {
        $table->text('autoreply_reset_msg')->after('status')->nullable();
      }
      if (!Schema::hasColumn('devices', 'autoreply_resume_msg')) {
        $table->text('autoreply_resume_msg')->after('status')->nullable();
      }
      if (!Schema::hasColumn('devices', 'autoreply_pause_msg')) {
        $table->text('autoreply_pause_msg')->after('status')->nullable();
      }
      if (!Schema::hasColumn('devices', 'autoreply_reset')) {
        $table->string('autoreply_reset', 50)->after('status')->nullable()->default('M');
      }
      if (!Schema::hasColumn('devices', 'autoreply_resume')) {
        $table->string('autoreply_resume', 50)->after('status')->nullable()->default('R');
      }
      if (!Schema::hasColumn('devices', 'autoreply_pause')) {
        $table->string('autoreply_pause', 50)->after('status')->nullable()->default('P');
      }
      if (!Schema::hasColumn('devices', 'autoreply_group')) {
        $table->boolean('autoreply_group')->after('status')->nullable()->default(0);
      }
      if (!Schema::hasColumn('devices', 'wu_receiver')) {
        $table->string('wu_receiver')->after('status')->nullable();
      }
      if (!Schema::hasColumn('devices', 'warmingup')) {
        $table->boolean('warmingup')->after('status')->default(0);
      }
      if (!Schema::hasColumn('devices', 'autoswitch')) {
        $table->boolean('autoswitch')->after('status')->nullable()->default(1);
      }
      if (!Schema::hasColumn('devices', 'autoread')) {
        $table->boolean('autoread')->after('status')->nullable()->default(0);
      }
      if (!Schema::hasColumn('devices', 'busy')) {
        $table->boolean('busy')->after('status')->nullable()->default(0);
      }
      $table->integer('user_id')->unsigned()->nullable()->change();
      if (!Schema::hasColumn('devices', 'unsubscribe_message')) {
        $table->text('unsubscribe_message')->after('wu_receiver')->nullable();
      }
      if (!Schema::hasColumn('devices', 'subscribe_message')) {
        $table->text('subscribe_message')->after('wu_receiver')->nullable();
      }
      if (!Schema::hasColumn('devices', 'unsubscribe_keyword')) {
        $table->string('unsubscribe_keyword')->after('wu_receiver')->nullable();
      }
      if (!Schema::hasColumn('devices', 'subscribe_keyword')) {
        $table->string('subscribe_keyword')->after('wu_receiver')->nullable();
      }
      if (!Schema::hasColumn('devices', 'ext_webhook')) {
        $table->json('ext_webhook')->after('webhook')->nullable();
      }
    });

    $devices = Device::get();
    foreach ($devices as $device) {
      if (empty($device->openai)) {
        $device->openai = json_encode([
          'apikey' => '',
          'contain' => '',
          'model' => 'gpt-3.5-turbo',
          'image_contain' => __('Generate image'),
          'image_model' => 'dall-e-3',
          'max_tokens' => 2048,
          'save_chats' => 0,
          'persona' => "Your name is $device->name. You are a smart, polite, and gentle assistant",
        ]);
        $device->save();
      } else {
        $openai = json_decode($device->openai, true);
        if ($openai['model'] !== 'gpt-3.5-turbo' || $openai['model'] !== 'gpt-4' || $openai['image_model'] !== 'dall-e-2' || $openai['image_model'] !== 'dall-e-3') {
          $openai['contain'] = empty($openai['contain']) ? '' : $openai['contain'];
          $openai['model'] = 'gpt-3.5-turbo';
          $openai['image_contain'] = empty($openai['image_contain']) ? __('Generate image') : $openai['image_contain'];
          $openai['image_model'] = 'dall-e-3';
          $openai['save_chats'] = 0;
          $openai['persona'] = "Your name is $device->name. You are a smart, polite, and gentle assistant";
          $device->openai = json_encode($openai);
          $device->save();
        }
      }
    }

    Schema::table('devices', function (Blueprint $table) {
        if (Schema::hasColumn('devices', 'openai_prefix')) {
            $table->dropColumn('openai_prefix');
        }
        if (Schema::hasColumn('devices', 'openai_apikey')) {
            $table->dropColumn('openai_apikey');
        }
    });

    Schema::table('messages', function (Blueprint $table) {
      if (Schema::hasColumn('messages', 'my_jid')) {
        $table->renameColumn('my_jid', 'sender');
      }
      if (Schema::hasColumn('messages', 'remote_jid')) {
        $table->renameColumn('remote_jid', 'key_remoteJid');
      }
      if (Schema::hasColumn('messages', 'from_me')) {
        $table->renameColumn('from_me', 'key_fromMe');
      }
      if (Schema::hasColumn('messages', 'mid')) {
        $table->renameColumn('mid', 'key_id');
      }
      if (Schema::hasColumn('messages', 'push_name')) {
        $table->renameColumn('push_name', 'pushName');
      }
      if (Schema::hasColumn('messages', 'data')) {
        $table->dropColumn('data');
      }
      if (!Schema::hasColumn('messages', 'messageTimestamp')) {
        $table->integer('messageTimestamp')->unsigned()->nullable();
      }
      if (!Schema::hasColumn('messages', 'broadcast')) {
        $table->boolean('broadcast')->nullable();
      }
      if (!Schema::hasColumn('messages', 'message')) {
        $table->json('message')->nullable();
      }
    });

    Schema::table('outboxes', function (Blueprint $table) {
      if (Schema::hasColumn('outboxes', 'try')) {
        $table->dropColumn('try');
      }
      if (!Schema::hasColumn('outboxes', 'recurring')) {
        $table->string('recurring', 20)->nullable();
      }
      if (Schema::hasColumn('outboxes', 'mediafile')) {
        $table->dropColumn('mediafile');
      }
      $table->string('status', 50)->default('PENDING')->comment('PENDING, SENT, FAILED')->change();
    });

    Schema::table('packages', function (Blueprint $table) {
      if (Schema::hasColumn('packages', 'max_template')) {
        $table->renameColumn('max_template', 'max_autoreply');
      }
      if (Schema::hasColumn('packages', 'max_outbox')) {
        $table->renameColumn('max_outbox', 'max_outgoing');
      }
      if (!Schema::hasColumn('packages', 'footer')) {
        $table->text('footer')->nullable();
      }
      if (!Schema::hasColumn('packages', 'webhook')) {
        $table->boolean('webhook')->default(0);
      }
      if (!Schema::hasColumn('packages', 'global_senders')) {
        $table->boolean('global_senders')->default(0);
      }
      if (Schema::hasColumn('packages', 'max_outgoing')) {
        $table->integer('max_outgoing')->default(-1)->change();
      }
      if (Schema::hasColumn('packages', 'max_device')) {
        $table->integer('max_device')->default(-1)->change();
      }
      if (Schema::hasColumn('packages', 'max_autoreply')) {
        $table->integer('max_autoreply')->default(-1)->change();
      }
      if (Schema::hasColumn('packages', 'max_phonebook')) {
        $table->integer('max_phonebook')->default(-1)->change();
      }
      if (!Schema::hasColumn('packages', 'hidden')) {
        $table->boolean('hidden')->default(0);
      }
    });
    DB::table('packages')->where('max_outgoing', '=', 0)->update(['max_outgoing'=> -1]);
    DB::table('packages')->where('max_device', '=', 0)->update(['max_device'=> -1]);
    DB::table('packages')->where('max_autoreply', '=', 0)->update(['max_autoreply'=> -1]);
    DB::table('packages')->where('max_phonebook', '=', 0)->update(['max_phonebook'=> -1]);

    Schema::table('pbtemps', function (Blueprint $table) {
      if (!Schema::hasColumn('pbtemps', 'email')) {
        $table->string('email', 191)->nullable();
      }
      if (!Schema::hasColumn('pbtemps', 'memo')) {
        $table->string('memo', 191)->nullable();
      }
      if (!Schema::hasColumn('pbtemps', 'column1')) {
        $table->string('column1', 191)->nullable();
      }
      if (!Schema::hasColumn('pbtemps', 'column2')) {
        $table->string('column2', 191)->nullable();
      }
      if (!Schema::hasColumn('pbtemps', 'column3')) {
        $table->string('column3', 191)->nullable();
      }
      if (!Schema::hasColumn('pbtemps', 'column4')) {
        $table->string('column4', 191)->nullable();
      }
      if (!Schema::hasColumn('pbtemps', 'column5')) {
        $table->string('column5', 191)->nullable();
      }
    });

    DB::table('settings')->where('key', '=', 'appLang')->delete();
    DB::table('settings')->where('key', '=', 'appTheme')->delete();
    DB::table('settings')->where('key', '=', 'landingPage')->update(['value'=>'landing-v5']);
    if (
      (DB::table('settings')
        ->where('key', '=', 'orderID')
        ->count() > 0 ||
        DB::table('settings')
          ->where('key', '=', 'orderId')
          ->count() > 0 ||
        DB::table('settings')
          ->where('key', '=', 'wz_orderId')
          ->count() > 0 ||
        DB::table('settings')
          ->where('key', '=', 'ar_orderId')
          ->count() > 0) &&
      DB::table('settings')
        ->where('key', '=', 'awg_orderId')
        ->count() > 0
    ) {
      DB::table('settings')
        ->where('key', '=', 'awg_orderId')
        ->delete();
    }
    if (
      (DB::table('settings')
        ->where('key', '=', 'restApi')
        ->count() > 0 ||
        DB::table('settings')
          ->where('key', '=', 'wz_restApi')
          ->count() > 0 ||
        DB::table('settings')
          ->where('key', '=', 'ar_restApi')
          ->count() > 0) &&
      DB::table('settings')
        ->where('key', '=', 'awg_restApi')
        ->count() > 0
    ) {
      DB::table('settings')
        ->where('key', '=', 'awg_restApi')
        ->delete();
    }
    if (
      (DB::table('settings')
        ->where('key', '=', 'encType')
        ->count() > 0 ||
        DB::table('settings')
          ->where('key', '=', 'wz_encType')
          ->count() > 0 ||
        DB::table('settings')
          ->where('key', '=', 'ar_encType')
          ->count() > 0) &&
      DB::table('settings')
        ->where('key', '=', 'awg_encType')
        ->count() > 0
    ) {
      DB::table('settings')
        ->where('key', '=', 'awg_encType')
        ->delete();
    }
    if (
      (DB::table('settings')
        ->where('key', '=', 'wz_pgMercadopago')
        ->count() > 0 ||
        DB::table('settings')
          ->where('key', '=', 'ar_pgMercadopago')
          ->count() > 0) &&
      DB::table('settings')
        ->where('key', '=', 'awg_pgMercadopago')
        ->count() > 0
    ) {
      DB::table('settings')
        ->where('key', '=', 'awg_pgMercadopago')
        ->delete();
    }
    if (
      (DB::table('settings')
        ->where('key', '=', 'wz_pgMidtrans')
        ->count() > 0 ||
        DB::table('settings')
          ->where('key', '=', 'ar_pgMidtrans')
          ->count() > 0) &&
      DB::table('settings')
        ->where('key', '=', 'awg_pgMidtrans')
        ->count() > 0
    ) {
      DB::table('settings')
        ->where('key', '=', 'awg_pgMidtrans')
        ->delete();
    }
    if (
      (DB::table('settings')
        ->where('key', '=', 'wz_pgPaypal')
        ->count() > 0 ||
        DB::table('settings')
          ->where('key', '=', 'ar_pgPaypal')
          ->count() > 0) &&
      DB::table('settings')
        ->where('key', '=', 'awg_pgPaypal')
        ->count() > 0
    ) {
      DB::table('settings')
        ->where('key', '=', 'awg_pgPaypal')
        ->delete();
    }
    if (
      (DB::table('settings')
        ->where('key', '=', 'wz_pgRazorpay')
        ->count() > 0 ||
        DB::table('settings')
          ->where('key', '=', 'ar_pgRazorpay')
          ->count() > 0) &&
      DB::table('settings')
        ->where('key', '=', 'awg_pgRazorpay')
        ->count() > 0
    ) {
      DB::table('settings')
        ->where('key', '=', 'awg_pgRazorpay')
        ->delete();
    }
    if (
      (DB::table('settings')
        ->where('key', '=', 'wz_pgStripe')
        ->count() > 0 ||
        DB::table('settings')
          ->where('key', '=', 'ar_pgStripe')
          ->count() > 0) &&
      DB::table('settings')
        ->where('key', '=', 'awg_pgStripe')
        ->count() > 0
    ) {
      DB::table('settings')
        ->where('key', '=', 'awg_pgStripe')
        ->delete();
    }
    if (
      (DB::table('settings')
        ->where('key', '=', 'wz_pgGopay')
        ->count() > 0 ||
        DB::table('settings')
          ->where('key', '=', 'ar_pgGopay')
          ->count() > 0) &&
      DB::table('settings')
        ->where('key', '=', 'awg_pgGopay')
        ->count() > 0
    ) {
      DB::table('settings')
        ->where('key', '=', 'awg_pgGopay')
        ->delete();
    }

    if (
      DB::table('settings')
        ->where('key', '=', 'decimalpoint')
        ->count() > 0 &&
      DB::table('settings')
        ->where('key', '=', 'nfDecimalpoint')
        ->count() > 0
    ) {
      DB::table('settings')
        ->where('key', '=', 'nfDecimalpoint')
        ->delete();
    }
    if (
      DB::table('settings')
        ->where('key', '=', 'decimals')
        ->count() > 0 &&
      DB::table('settings')
        ->where('key', '=', 'nfDecimals')
        ->count() > 0
    ) {
      DB::table('settings')
        ->where('key', '=', 'nfDecimals')
        ->delete();
    }
    if (
      DB::table('settings')
        ->where('key', '=', 'separator')
        ->count() > 0 &&
      DB::table('settings')
        ->where('key', '=', 'nfSeparator')
        ->count() > 0
    ) {
      DB::table('settings')
        ->where('key', '=', 'nfSeparator')
        ->delete();
    }

    DB::table('settings')
      ->where('key', '=', 'orderID')
      ->update(['key' => 'awg_orderId']);
    DB::table('settings')
      ->where('key', '=', 'orderId')
      ->update(['key' => 'awg_orderId']);
    DB::table('settings')
      ->where('key', '=', 'restApi')
      ->update(['key' => 'awg_restApi']);
    DB::table('settings')
      ->where('key', '=', 'encType')
      ->update(['key' => 'awg_encType']);

    DB::table('settings')
      ->where('key', '=', 'wz_orderId')
      ->update(['key' => 'awg_orderId']);
    DB::table('settings')
      ->where('key', '=', 'wz_restApi')
      ->update(['key' => 'awg_restApi']);
    DB::table('settings')
      ->where('key', '=', 'wz_encType')
      ->update(['key' => 'awg_encType']);
    DB::table('settings')
      ->where('key', '=', 'wz_pgMercadopago')
      ->update(['key' => 'awg_pgMercadopago']);
    DB::table('settings')
      ->where('key', '=', 'wz_pgMidtrans')
      ->update(['key' => 'awg_pgMidtrans']);
    DB::table('settings')
      ->where('key', '=', 'wz_pgPaypal')
      ->update(['key' => 'awg_pgPaypal']);
    DB::table('settings')
      ->where('key', '=', 'wz_pgRazorpay')
      ->update(['key' => 'awg_pgRazorpay']);
    DB::table('settings')
      ->where('key', '=', 'wz_pgStripe')
      ->update(['key' => 'awg_pgStripe']);
    DB::table('settings')
      ->where('key', '=', 'wz_pgGopay')
      ->update(['key' => 'awg_pgGopay']);

    DB::table('settings')
      ->where('key', '=', 'ar_orderId')
      ->update(['key' => 'awg_orderId']);
    DB::table('settings')
      ->where('key', '=', 'ar_restApi')
      ->update(['key' => 'awg_restApi']);
    DB::table('settings')
      ->where('key', '=', 'ar_encType')
      ->update(['key' => 'awg_encType']);
    DB::table('settings')
      ->where('key', '=', 'ar_pgMercadopago')
      ->update(['key' => 'awg_pgMercadopago']);
    DB::table('settings')
      ->where('key', '=', 'ar_pgMidtrans')
      ->update(['key' => 'awg_pgMidtrans']);
    DB::table('settings')
      ->where('key', '=', 'ar_pgPaypal')
      ->update(['key' => 'awg_pgPaypal']);
    DB::table('settings')
      ->where('key', '=', 'ar_pgRazorpay')
      ->update(['key' => 'awg_pgRazorpay']);
    DB::table('settings')
      ->where('key', '=', 'ar_pgStripe')
      ->update(['key' => 'awg_pgStripe']);
    DB::table('settings')
      ->where('key', '=', 'ar_pgGopay')
      ->update(['key' => 'awg_pgGopay']);

    DB::table('settings')
      ->where('key', '=', 'landingPage')
      ->where('value', '=', 'true')
      ->update(['value' => 'landing-v5']);
    DB::table('settings')
      ->where('key', '=', 'decimalpoint')
      ->update(['key' => 'nfDecimalpoint']);
    DB::table('settings')
      ->where('key', '=', 'decimals')
      ->update(['key' => 'nfDecimals']);
    DB::table('settings')
      ->where('key', '=', 'separator')
      ->update(['key' => 'nfSeparator']);

    Schema::table('templates', function (Blueprint $table) {
        if (Schema::hasColumn('templates', 'mediafile')) {
        $table->dropColumn('mediafile');
      }
    });

    Schema::table('users', function (Blueprint $table) {
      if (Schema::hasColumn('users', 'webhook')) {
        $table->dropColumn('webhook');
      }
      if (!Schema::hasColumn('users', 'ip_address')) {
        $table->string('ip_address', 50)->nullable();
      }
      if (!Schema::hasColumn('users', 'banned')) {
        $table->boolean('banned')->default(0);
      }
      if (!Schema::hasColumn('users', 'rtl')) {
        $table->boolean('rtl')->default(0);
      }
      if (!Schema::hasColumn('users', 'otp')) {
        $table->string('otp', 20)->nullable();
      }
    });

    Schema::table('documentations', function (Blueprint $table) {
      if (Schema::hasColumn('documentations', 'lang')) {
        $table->string('lang', 20)->default('us')->change();
      }
    });

    $tables = [
      'autoreplies',
      'captures',
      'capture_items',
      'contact_groups',
      'devices',
      'documentations',
      'failed_jobs',
      'migrations',
      'outboxes',
      'packages',
      'password_resets',
      'pbtemps',
      'personal_access_tokens',
      'settings',
      'phonebooks',
      'subscribers',
      'transactions',
      'users',
    ];
    foreach ($tables as $table) {
      // DB::statement('ALTER TABLE ' . $table . ' ENGINE = InnoDB');
      DB::statement('ALTER TABLE ' . $table . ' ENGINE = InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci');
    }

    if(file_exists(base_path('storage/version-last'))) unlink(base_path('storage/version-last'));
    if(file_exists(base_path('storage/version-local'))) unlink(base_path('storage/version-local'));
    if(file_exists(base_path('storage/version-remote'))) unlink(base_path('storage/version-remote'));
    if(file_exists(base_path('config/modules.php'))) unlink(base_path('config/modules.php'));
  }
}
