<?php

namespace App\Repositories\Admin;

use App\Models\ApiKey;
use App\Models\Config;
use App\Models\Package;
use App\Models\Season;
use App\Models\Star;
use App\Repositories\Interfaces\Admin\SettingInterface;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use App\Traits\ImageTrait;

class SettingRepository implements SettingInterface
{

    use ImageTrait;
    public function all()
    {
        return Season::get();
    }

    public function update($request): bool
    {
        $site_lang = $request->site_lang ?? 'en';

        foreach ($request->except('_token', 'payment_method', 'is_modal', '_method', 'site_lang', 'mobile_app', 'chat_messenger', 'countries', 'r') as $key => $value) {
            if ($key == 'default_language') {
                $setting = Config::where('title', $key)->first();
            } else {
                if (isset($site_lang) && in_array($key, get_yrsetting('setting_by_lang'))) {
                    $setting = Config::where('title', $key)->first();
                } else {
                    $setting = Config::where('title', $key)->first();
                }
            }



            if (in_array($key, get_yrsetting('setting_array'))) {
                $value = serialize($value);
            }

            if (blank($setting)) {
                $setting        = new Config();
                $setting->title = $key;

                $setting->value = $value;
            } else {

                $setting->value = $value;
            }

            $setting->save();
        }
        Cache::flush();
        return true;
    }

    public function systemStatus($request)
    {
        if ($request->has('data.name') && $request->has('data.value')) {
            $title = $request->input('data.name');
            $value = $request->input('data.value');

            Config::updateOrCreate(
                ['title' => $title],
                ['value' => $value]
            );

            return [
                'status'    => 'success',
                'message'   => __('setting_updated_successfully'),
                'title'     => __('success'),
                'is_reload' => true,
            ];
        }

        return [
            'status'    => 'error',
            'message'   => __('setting_updated_failled'),
            'title'     => __('error'),
            'is_reload' => true,
        ];
    }

    public function apiKeyStore($request)
    {
        try {
            $data = [
                'title' => $request->title,
                'key' => $request->api_key,
                'status' => 1,
                'user_id' => auth()->user()->id,
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
            ];
            return ApiKey::create($data);
        } catch (\Exception $e) {
            return false;
        }
    }
    public function apiKeyUpdate($request, $id)
    {
        try {
            $data = [
                'title' => $request->title,
                'key' => $request->api_key,
                'updated_at' => Carbon::now(),
            ];
            return ApiKey::where('id', $id)->update($data);
        } catch (\Exception $e) {
            return false;
        }
    }

    public function storageUpdate($request)
    {
        $site_lang = 'en';

        foreach ($request->except('_token', '_method', 'site_lang', 'mobile_app', 'chat_messenger', 'countries', 'r') as $key => $value) {
            if ($key == 'default_language') {
                $setting = Config::where('title', $key)->first();
            } else {
                if (isset($site_lang) && in_array($key, get_yrsetting('setting_by_lang'))) {
                    $setting = Config::where('title', $key)->where('lang', $site_lang)->first();
                } else {
                    $setting = Config::where('title', $key)->where('lang', 'en')->first();
                }
            }

            if (in_array($key, get_yrsetting('setting_image'))) {

                if (! blank($setting)) {
                    $this->deleteImage(setting($key));
                }

                $response = $this->saveImage($request->file($key), $key);

                $value    = serialize($response['images']);
            }

            if (in_array($key, get_yrsetting('setting_array'))) {
                $value = serialize($value);
            }

            if (blank($setting)) {
                $setting        = new Config();
                $setting->title = $key;
            }

            if (blank($setting)) {
                $setting        = new Config();
                $setting->title = $key;
                if (isset($site_lang) && in_array($key, get_yrsetting('setting_by_lang'))) {
                    $setting->lang = $site_lang;
                } else {
                    $setting->lang = 'en';
                }
                $setting->value = $value;
            } else {
                if (isset($site_lang) && in_array($key, get_yrsetting('setting_by_lang'))) {
                    $setting->lang = $site_lang;
                } else {
                    $setting->lang = 'en';
                }
                $setting->value = $value;
            }

            $setting->save();
        }
        Cache::flush();

        if ($request->has('system_name')) {
            $system_name = Config::where('title', 'system_name')->where('lang', 'en')->first();
            if (! blank($system_name)) {
                envWrite('APP_NAME', $system_name->value);
            } else {
                $system_name = Config::where('title', 'system_name')->first();
                if (! blank($system_name)) {
                    envWrite('APP_NAME', $system_name->value);
                }
            }
        }

        if ($request->has('is_cache_enabled')) {
            if (setting('is_cache_enabled') == 'enable') {
                if (setting('default_cache') == 'redis') {
                    envWrite('CACHE_DRIVER', 'redis');
                    envWrite('REDIS_CLIENT', 'predis');
                    envWrite('REDIS_HOST', setting('redis_host'));
                    envWrite('REDIS_PASSWORD', setting('redis_password'));
                    envWrite('REDIS_PORT', setting('redis_port'));
                } else {
                    envWrite('CACHE_DRIVER', 'file');
                }
            } else {
                envWrite('CACHE_DRIVER', 'file');
            }
        }
        if ($request->has('default_storage')) {
            switch ($request->default_storage) {
                case 'aws_s3':
                    $aws_url     = 'http://'.$request->aws_bucket.'.s3.'.$request->aws_default_region.'.amazonaws.com';
                    envWrite('AWS_ACCESS_KEY_ID', $request->aws_access_key_id);
                    envWrite('AWS_SECRET_ACCESS_KEY', $request->aws_secret_access_key);
                    envWrite('AWS_DEFAULT_REGION', $request->aws_default_region);
                    envWrite('AWS_BUCKET', $request->aws_bucket);
                    envWrite('AWS_URL', $aws_url);
                    envWrite('FILESYSTEM_DISK', 's3');
                    break;
                case 'do':
                    $do_endpoint = 'https://'.$request->do_default_region.'.digitaloceanspaces.com';
                    envWrite('DO_ACCESS_KEY_ID', $request->do_access_key_id);
                    envWrite('DO_SECRET_ACCESS_KEY', $request->do_secret_access_key);
                    envWrite('DO_DEFAULT_REGION', $request->do_default_region);
                    envWrite('DO_BUCKET', $request->do_bucket);
                    envWrite('DO_ENDPOINT', $do_endpoint);
                    envWrite('FILESYSTEM_DISK', 's3');
                    break;
                case 'wasabi':
                    $was_url     = 'https://'.'s3.'.setting('wasabi_default_region').'.wasabisys.com';
                    envWrite('WAS_ACCESS_KEY_ID', setting('wasabi_access_key_id'));
                    envWrite('WAS_SECRET_ACCESS_KEY', setting('wasabi_secret_access_key'));
                    envWrite('WAS_DEFAULT_REGION', setting('wasabi_default_region'));
                    envWrite('WAS_BUCKET', setting('wasabi_bucket'));
                    envWrite('WAS_URL', $was_url);
                    envWrite('FILESYSTEM_DISK', 'wasabi');
                    break;
                default:
                    envWrite('FILESYSTEM_DISK', 'local');
                    break;
            }
        }

        if ($request->has('pusher_app_key')) {
            if (checkEmptyProvider('is_pusher_notification_active')) {
                envWrite('PUSHER_APP_KEY', $request->pusher_app_key);
                envWrite('PUSHER_APP_SECRET', $request->pusher_app_secret);
                envWrite('PUSHER_APP_ID', $request->pusher_app_id);
                envWrite('PUSHER_APP_CLUSTER', $request->pusher_app_cluster);
            }
            if ($request->is_pusher_notification_active == '1') {
                envWrite('BROADCAST_DRIVER', 'pusher');
            } else {
                envWrite('BROADCAST_DRIVER', 'log');
            }
        }

        return true;
    }
}
