<?php

namespace App\Http\Controllers\panel;

use App\Http\Controllers\Controller;
use App\Mail\Test;
use App\Rules\Mobile;
use App\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Mail;
use Illuminate\Validation\Rule;

class SettingController extends Controller
{

    private $fileAllowedFormats = [
        'pdf',
        'txt',
        'jpeg',
        'jpg',
        'html',
        'png',
        'csv',
        'pptx',
        'ppt',
        'json',
        'xls',
        'apk',
        'avi',
        'css',
        'js',
        'docx',
        'doc',
        'mp4a',
        'psd',
        'rar',
        'svg',
        'tiff',
        'tar',
        'webp',
        'xml',
        'zip',
        'wav',
        '3gp',
        'dwg'
    ];

    public function __construct()
    {
        $this->middleware('can:manage-settings');
    }

    public function showGeneralSettings()
    {
        $generalSettings = [
            'site_title',
            'site_logo',
            'site_url',
            'site_logo_img',
            'must_verify_mobile',
            'register_enabled',
            'rules',
            'use_google_nocaptcha',
            'google_nocaptcha_sitekey',
            'google_nocaptcha_secret',
            'must_verify_email',
            'site_homepage_enabled',
            'email_notifications',
            'sms_notifications',
            'site_email',
            'site_activity_email'
        ];

        $settings = $this->get($generalSettings);

        return view('panel.settings.general', compact('settings'));
    }

    public function updateGeneralSettings(Request $request)
    {
        $generalSettings = [
            'site_title',
            'site_logo',
            'must_verify_mobile',
            'register_enabled',
            'rules',
            'use_google_nocaptcha',
            'google_nocaptcha_sitekey',
            'google_nocaptcha_secret',
            'must_verify_email',
            'site_homepage_enabled',
            'email_notifications',
            'sms_notifications',
            'site_email',
            'site_activity_email'
        ];
        $dataToSave = [];

        $request->validate([
            'must_verify_email' => 'sometimes|accepted',
            'must_verify_mobile' => 'sometimes|accepted',
            'use_google_nocaptcha' => 'sometimes|accepted',
            'site_homepage_enabled' => 'sometimes|accepted',
            'sms_notifications' => 'sometimes|accepted',
            'email_notifications' => 'sometimes|accepted',
            'register_enabled' => 'sometimes|accepted',
            'site_email' => 'nullable|email',
        ]);

        if ($request->hasFile('site_logo_img')) {
            $request->validate([
                'site_logo_img' => 'file|image'
            ]);
            $logoPath = $request->site_logo_img->store('system');
            $dataToSave['site_logo_img'] = asset('files/'.$logoPath);
        }

        foreach ($generalSettings as $generalSetting) {
            $dataToSave[$generalSetting] = $request->$generalSetting ?? null;
        }

        $this->save($dataToSave);

        updateDotEnv('APP_NAME', $request->site_title);
        updateDotEnv('MAIL_FROM_ADDRESS', $request->site_email);

        return redirect()->back()->withSuccess('با موفقیت انجام شد');
    }

    public function showSmsSettings(Request $request)
    {
        $smsSettings = json_decode(getconfig('sms_settings'), true);
        $activeDriver = $smsSettings['active_driver'];
        $driverSettingsPath = config('sms.drivers.'.$activeDriver.'.settings_file');
        $settings = $smsSettings['drivers'][$activeDriver];
        $smsDrivers = config('sms.drivers');

        return view('panel.settings.sms', compact('activeDriver', 'smsDrivers', 'settings', 'driverSettingsPath'));
    }

    public function updateSmsSettings(Request $request)
    {
        $request->validate([
            'sms_settings' => ['required', 'array'],
            'sms_settings.driver' => ['required', Rule::in(array_keys(config('sms.drivers')))],
        ]);

        $smsSettings = json_decode(getConfig('sms_settings'), true);

        $smsSettings['active_driver'] = $request->sms_settings['driver'];
        $smsSettings['drivers'][$request->sms_settings['driver']] = Arr::except($request->sms_settings, 'driver');

        $this->save(['sms_settings' => $smsSettings]);

        return redirect()->back()->withSuccess('با موفقیت انجام شد');
    }

    public function loadSmsDriverSettings(Request $request)
    {
        $request->validate([
            'driver' => ['required', Rule::in(array_keys(config('sms.drivers')))]
        ]);


        $smsSettings = json_decode(getconfig('sms_settings'), true);
        $driverSettingsPath = config('sms.drivers.'.$request->driver.'.settings_file');
        $settings = $smsSettings['drivers'][$request->driver] ?? [];

        return view($driverSettingsPath, compact('settings'));
    }

    public function showEmailSettings(Request $request)
    {
        $settings = [
            'mail_host' => env('MAIL_HOST', ''),
            'mail_username' => env('MAIL_USERNAME', ''),
            'mail_password' => env('MAIL_PASSWORD', ''),
            'mail_port' => env('MAIL_PORT', ''),
            'mail_encryption' => env('MAIL_ENCRYPTION', '')
        ];

        return view('panel.settings.email', compact('settings'));
    }

    public function updateEmailSettings(Request $request)
    {
        $request->validate([
            'mail_host' => 'required',
            'mail_username' => 'required',
            'mail_password' => 'required',
            'mail_port' => 'required',
        ]);

        $settings = ['mail_host', 'mail_username', 'mail_password', 'mail_port', 'mail_encryption'];

        foreach ($settings as $setting) {
            updateDotEnv(strtoupper($setting), $request->$setting);
        }

        return redirect()->back()->withSuccess('با موفقیت انجام شد');
    }


    public function sendTestEmail(Request $request)
    {
        $request->validate([
            'email' => 'required|email'
        ]);

        Mail::to($request->email)->send(new Test());

        return response()->json(['status' => 'success', 'msg' => 'با موفقیت انجام شد']);
    }

    public function sendTestSms(Request $request)
    {
        if ($request->has('action') and $request->action == 'sendTestSms') {
            $request->validate([
                'mobile' => ['required', new Mobile()],
                'driver' => ['required', Rule::in(array_keys(config('sms.drivers')))]
            ]);

            try {
                $result = sms()
                    ->via($request->driver)
                    ->to([$request->mobile])
                    ->text('پیامک آزمایشی سیستم پشتیبانی و ارسال تیکت پاترونیک')
                    ->send();
            } catch (\Exception $e) {
                return response()->json(['status' => 'fail', 'msg' => $e->getMessage()]);
            }

            if ($result->wasSuccessful()) {
                $status = 'success';
                $msg = 'با موفقیت ارسال شد';
            }

            return response()->json(
                ['status' => $status ?? 'fail', 'msg' => $msg ?? 'در ارسال پیامک مشکلی بوجود آمده است']
            );
        } else {
            return response()->json(['status' => $status ?? 'fail', 'msg' => 'پارامتر های ارسالی نامعتبر میباشد']);
        }
    }

    public function showTicketSettings()
    {
        $ticketSettings = [
            'can_user_change_department',
            'can_user_close_ticket',
            'can_user_reopen_ticket',
            'can_user_attach_file',
            'can_staff_create_ticket',
            'ticket_signature',
            'upload_max_file_size',
            'upload_max_file_count',
            'upload_allowed_formats',
        ];

        $settings = $this->get($ticketSettings);
        $fileFormats = $this->fileAllowedFormats;
        $allowedMimes = $settings['upload_allowed_formats'] ? explode(',', $settings['upload_allowed_formats']) : [];

        return view('panel.settings.ticket', compact('settings', 'fileFormats', 'allowedMimes'));
    }


    public function updateTicketSettings(Request $request)
    {
        $ticketSettings = [
            'can_user_change_department',
            'can_user_close_ticket',
            'can_user_reopen_ticket',
            'can_user_attach_file',
            'can_staff_create_ticket',
            'ticket_signature',
            'upload_max_file_size',
            'upload_max_file_count'
        ];
        $dataToSave = [];

        $request->validate([
            'can_user_change_department' => 'sometimes|accepted',
            'can_user_close_ticket' => 'sometimes|accepted',
            'can_user_reopen_ticket' => 'sometimes|accepted',
            'can_user_attach_file' => 'sometimes|accepted',
            'can_staff_create_ticket' => 'sometimes|accepted',
            'ticket_signature' => 'required|in:user,superior,both,none',
            'upload_max_file_size' => 'required|numeric',
            'upload_max_file_count' => 'required|numeric',
            'upload_allowed_formats' => 'in:'.implode(',', array_values($this->fileAllowedFormats))
        ]);

        foreach ($ticketSettings as $ticketSetting) {
            $dataToSave[$ticketSetting] = $request->$ticketSetting ?? null;
        }

        $dataToSave['upload_allowed_formats'] = $request->filled('formats') ? implode(',', $request->formats) : null;

        $this->save($dataToSave);

        return redirect()->back()->withSuccess('با موفقیت ذخیره شد');
    }

    public function showTemplateSettings()
    {
        $templateSettings = ['site_template'];
        $settings = json_decode((string)$this->get($templateSettings)['site_template'], true);
        return view('panel.settings.template', compact('settings'));
    }

    public function updateTemplateSettings(Request $request)
    {
        $templateData = [];
        $files = $request->file('avatars');

        $request->validate([
            'showOpenHoursSection' => 'sometimes|accepted',
            'showOurTeamSection' => 'sometimes|accepted',
            'telegrams.*' => 'nullable|url',
            'instagrams.*' => 'nullable|url',
            'twitters.*' => 'nullable|url',
            'linkedins.*' => 'nullable|url',
            'avatars.*' => 'nullable|file|image'
        ]);

        $templateData['showOpenHoursSection'] = $request->showOpenHoursSection ?? null;
        $templateData['showOurTeamSection'] = $request->showOurTeamSection ?? null;
        $templateData['openDays'] = $request->openDays;
        $templateData['openHours'] = $request->openHours;
        $templateData['phone'] = $request->phone;
        $templateData['ourTeamHeader'] = $request->ourTeamHeader;

        $teamMembers = [];

        for ($i = 0; $i < count($request->members); $i++) {
            $teamMembers[$i] = [
                'name' => $request->names[$i],
                'position' => $request->positions[$i],
                'bio' => $request->bios[$i],
                'telegram' => $request->telegrams[$i],
                'instagram' => $request->instagrams[$i],
                'twitter' => $request->twitters[$i],
                'linkedin' => $request->linkedins[$i],
                'avatar' => $request->preavatars[$i],
            ];

            if (isset($files[$i])) {
                $avatarPath = $files[$i]->store('avatars');
                $teamMembers[$i]['avatar'] = $avatarPath;
            }
        }

        $templateData['teamMembers'] = $teamMembers;

        $this->save([
            'site_template' => json_encode($templateData)
        ]);


        return redirect()->back()->withSuccess('با موفقیت ذخیره شد');
    }

    public function save(array $data)
    {
        foreach ($data as $key => $val) {
            Setting::where('config_name', $key)->update(['config_value' => $val]);
        }
    }

    public function get(array $settings)
    {
        return Setting::whereIn('config_name', $settings)->pluck('config_value', 'config_name')->toArray();
    }
}
