<?php

namespace App\Services;

use App\Setting;
use Illuminate\Support\Facades\Artisan;

class UpdateService
{
    private static $updates = [
        '2.4.0',
        '2.5.0',
        '2.6.0',
        '2.7.3',
    ];

    public static function checkForUpdate(): ?string
    {
        foreach (static::$updates as $update) {
            if (self::versionIsLowerThan(static::normalizeVersion($update))) {
                return $update;
            }
        }
        return null;
    }

    private static function normalizeVersion($version): string
    {
        return str_replace('.', '', $version);
    }

    private static function versionIsLowerThan(string $version): bool
    {
        return static::normalizeVersion(config('app.version')) < static::normalizeVersion($version);
    }

    public static function update_to_2_4_0()
    {
        if (self::versionIsLowerThan('2.4.0')) {
            updateDotEnv('APP_VERSION', '2.4.0');
            updateDotEnv('BROADCAST_DRIVER', 'log');
            updateDotEnv('PUSHER_APP_ID', '');
            updateDotEnv('PUSHER_APP_KEY', '');
            updateDotEnv('PUSHER_APP_SECRET', '');
            updateDotEnv('PUSHER_APP_CLUSTER', '');
            updateDotEnv('MIX_PUSHER_APP_KEY', '');
            updateDotEnv('MIX_PUSHER_APP_CLUSTER', '');

            $dbUpdates = [
                'sms_use_patterns' => false,
                'sms_patterns' => [
                    'ticketCreate' => [
                        'code' => '',
                        'text' => ''
                    ],
                    'userReply' => [
                        'code' => '',
                        'text' => ''
                    ],
                    'staffReply' => [
                        'code' => '',
                        'text' => ''
                    ],
                    'userRegister' => [
                        'code' => '',
                        'text' => ''
                    ],
                ],
                'sms_driver' => 'mellipayamak'
            ];

            foreach ($dbUpdates as $key => $val) {
                Setting::updateOrCreate(
                    ['config_name' => $key],
                    ['config_value' => is_array($val) ? json_encode($val) : $val]
                );
            }
        }
    }

    public static function update_to_2_5_0()
    {
        if (static::versionIsLowerThan('2.5.0')) {
            updateDotEnv('APP_VERSION', '2.5.0');
        }
    }

    public static function update_to_2_6_0()
    {
        if (static::versionIsLowerThan('2.6.0')) {
            $smsSettings = [];
            $settings = Setting::query()
                ->whereIn('config_name', [
                    'sms_number',
                    'sms_username',
                    'sms_password',
                    'sms_use_patterns',
                    'sms_patterns',
                    "sms_driver",
                ])
                ->pluck('config_value', 'config_name')
                ->toArray();

            $smsSettings['active_driver'] = MELLIPAYAMAK_SMS_DRIVER;
            $smsSettings['drivers'] = [
                MELLIPAYAMAK_SMS_DRIVER => [
                    'username' => $settings['sms_number'],
                    'password' => $settings['sms_username'],
                    'number' => $settings['sms_number'],
                    'send_by_patterns' => (bool)$settings['sms_use_patterns'],
                    'patterns' => $settings['sms_patterns']
                ]
            ];

            Setting::create([
                'config_name' => 'sms_settings',
                'config_value' => json_encode($smsSettings),
                'is_global' => false,
            ]);

            Setting::query()
                ->whereIn('config_name', [
                    'sms_number',
                    'sms_username',
                    'sms_password',
                    'sms_use_patterns',
                    'sms_patterns',
                    "sms_driver",
                ])
                ->delete();

            updateDotEnv('APP_VERSION', '2.6.0');
        }
    }

    public static function update_to_2_7_3()
    {
        if (self::versionIsLowerThan('2.7.3')) {
            Artisan::call("migrate", ['--force' => true]);
            updateDotEnv('APP_VERSION', '2.7.3');
        }
    }
}
