<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\BusinessSetting;
use Illuminate\Support\Facades\Artisan;

class BusinessSettingsController extends Controller
{
    public function index()
    {
        return view('backend.pages.setting');
    }

    public function update(Request $request)
    {

        foreach ($request->types as $key => $type) {
            $business_settings = BusinessSetting::where('type', $type)->first();
            if ($business_settings != null) {
                $business_settings->value = $request[$type];
                $business_settings->save();
            } else {
                $business_settings = new BusinessSetting;
                $business_settings->type = $type;
                $business_settings->value = $request[$type];
                $business_settings->save();
            }
        }
        if (env('APP_MODE') == 'demo') {
            notify()->error('This Feature is not available in Demo');
            return back();
        } else {
            if ($request->system_icon != null) {
                $business_settings = BusinessSetting::where('type', 'system_icon')->first();
                $image = $request->file('system_icon');
                $imgName = date('YmdHi') . $image->getClientOriginalName();
                $image->move('public/uploads/logo/', $imgName);
                if (file_exists('public/uploads/logo/' . $business_settings->value) and ! empty($business_settings->value)) {
                    unlink('public/uploads/logo/' . $business_settings->value);
                }
                $business_settings->value = $imgName;
                $business_settings->save();
            }
            if ($request->system_logo != null) {
                $business_settings = BusinessSetting::where('type', 'system_logo')->first();
                $image = $request->file('system_logo');
                $imgName = date('YmdHi') . $image->getClientOriginalName();
                $image->move('public/uploads/logo/', $imgName);
                if (file_exists('public/uploads/logo/' . $business_settings->value) and ! empty($business_settings->value)) {
                    unlink('public/uploads/logo/' . $business_settings->value);
                }
                $business_settings->value = $imgName;
                $business_settings->save();
            }
        }
        Artisan::call('cache:clear');
        notify()->success('Successfully System Settings Update!');
        return Redirect()->back();
    }
}
