<?php

namespace Wave\Http\Controllers\CMS;

use App\Http\Controllers\Controller;
use App\Models\OnlineHelp;
use App\Models\SiteSetting;
use App\Models\User;
use App\Models\UserNotificationSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Yajra\DataTables\Facades\DataTables;

class SettingController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $siteSetting = SiteSetting::latest()->first();
        return view('theme::cms.settings.index', [
            'siteSetting' => $siteSetting,
        ]);
    }

    public function updateContactUs(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'phone' => 'required|string',
            'whatsapp' => 'required|string',
            'email' => 'required|string|email',
            'office_hour_english' => 'required|string',
            'office_hour_chinese' => 'required|string',
            'address_english' => 'required|string',
            'address_chinese' => 'required|string',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => __('Fill up all required fields!')
            ], 200);
        }
        else {
            $siteSetting = SiteSetting::latest()->first();
            if ($siteSetting) {
                $siteSetting->update($request->all());
            }
            else {
                SiteSetting::create($request->all());
            }
    
            return response()->json([
                'success' => true,
                'message' => __("All changes have been saved!"),
            ]);
        }
    }

    public function updatePassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'current_password' => ['required', 'string', 'min:6', function ($attribute, $value, $fail) use ($request) {
                if (!\Hash::check($value, $request->user()->password)) {
                    return $fail(__('The current password is incorrect.'));
                }
            }],
            'new_password' => 'required|string|min:6|confirmed',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first(),
            ], 200);
        }
        else {
            $user = User::find($request->user()->id);
            if ($user) {
                $user->password = bcrypt($request->new_password);
                $user->save();
            }
    
            return response()->json([
                'success' => true,
                'message' => __("Password has successfully saved!"),
            ]);
        }
    }

    public function tableOnlineHelp(Request $request)
    {
        $onlineHelps = OnlineHelp::query()
            ->select(
                'id',
                'category',
                'sort',
                'title_english',
                'title_chinese',
                'details_english',
                'details_chinese',
            );

        return Datatables::of($onlineHelps)
            ->escapeColumns(['id'])
            ->addColumn('category_name_display', function ($onlineHelp) { // Temporary
                return $onlineHelp->category_name_display;
            })
            ->addColumn('actions', function ($onlineHelp) {
                $viewAction = '<a href="#" class="primary-text show-online-help-frm" data-fields="' . htmlspecialchars(json_encode($onlineHelp->toArray())) . '" data-frm-type="view" data-id="' . $onlineHelp->id .  '">' . __("View") . '</a>';
                $editAction = '<a href="#" class="primary-text show-online-help-frm" data-fields="' . htmlspecialchars(json_encode($onlineHelp->toArray())) . '" data-frm-type="edit" data-id="' . $onlineHelp->id .  '">' . __("Edit") . '</a>';
                $removeAction = '<a href="#" class="item-list-note failed delete-online-help" data-action="' . route('cms.settings.destroy-online-help', $onlineHelp->id) . '">' . __("Delete") . '</a>';
                $actions = $viewAction . '<span class="long-pipe mx-2">|</span>' . $editAction . '<span class="long-pipe mx-2">|</span>' . $removeAction;
                return $actions;
            })
            ->make(true);
    }

    public function storeOnlineHelp(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'category' => 'required|string',
            'title_english' => 'required|string|max:255',
            'title_chinese' => 'required|string|max:255',
            'details_english' => 'required|string',
            'details_chinese' => 'required|string',
            'sort' => 'required|integer|min:1',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }
        else {
            $onlineHelpSortExists = OnlineHelp::where('category', $request->category)->where('sort', $request->sort)->first();
            if ($onlineHelpSortExists) {
                return response()->json([
                    'success' => false,
                    'message' => __("Sort value already exists!"),
                ]);
            }

            OnlineHelp::create($request->all());
    
            return response()->json([
                'success' => true,
                'message' => __("Online Help has successfully saved!"),
            ]);
        }
    }

    public function updateOnlineHelp(OnlineHelp $onlineHelp, Request $request)
    {
        $validator = Validator::make($request->all(), [
            'category' => 'required|string',
            'title_english' => 'required|string|max:255',
            'title_chinese' => 'required|string|max:255',
            'details_english' => 'required|string',
            'details_chinese' => 'required|string',
            'sort' => 'required|integer|min:1',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }
        else {
            $onlineHelp->update($request->all());
    
            return response()->json([
                'success' => true,
                'message' => __("Online Help has successfully saved!"),
            ]);
        }
    }

    public function destroyOnlineHelp(OnlineHelp $onlineHelp)
    {
        $onlineHelp->delete();

        return response()->json([
            'success' => true,
            'message' => __("Online Help has successfully removed!"),
        ]);
    }

    public function updateNotificationSettings(Request $request)
    {
        UserNotificationSetting::where('user_id', $request->user()->id)->update(['is_active' => false]);
        if (isset($request->notifications) && count($request->notifications) > 0) {
            foreach ($request->notifications as $notification) {
                $userNotificationSetting = UserNotificationSetting::updateOrCreate(
                    [
                        'user_id' => $request->user()->id,
                        'notification' => $notification,
                    ],
                    [
                        'is_active' => true,
                    ],
                );
            }
        }

        return response()->json([
            'success' => true,
            'message' => __("All changes have been saved!"),
        ]);
    }

    public function updateApiKey(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'google_drive_api_key' => 'required|string',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => __('Fill up all required fields!')
            ], 200);
        }
        else {
            $siteSetting = SiteSetting::latest()->first();
            if ($siteSetting) {
                $siteSetting->update($request->all());
            }
            else {
                SiteSetting::create($request->all());
            }
    
            return response()->json([
                'success' => true,
                'message' => __("All changes have been saved!"),
            ]);
        }
    }
}
