<?php

namespace Modules\Survey\Http\Controllers;

use App\Exports\ExportSurveySampleQuestion;
use App\Http\Controllers\Controller;
use App\Imports\SurveyQuestionBankImport;
use App\Traits\UploadMedia;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Facades\Excel;
use Modules\CourseSetting\Entities\Category;
use Modules\Survey\Entities\SurveyGroup;
use Modules\Survey\Entities\SurveyQuestionBank;
use Modules\Survey\Entities\SurveyQuestionBankMuOption;
use Yajra\DataTables\Facades\DataTables;

class SurveyQuestionBankController extends Controller
{
    use UploadMedia;

    public function form()
    {
        try {
            $groups = SurveyGroup::latest()->get();
            $categories = Category::where('status', 1)->get();

            return view('survey::survey_bank', compact('groups', 'categories'));
        } catch (\Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }

    public function show($id)
    {
        try {
            $groups = SurveyGroup::latest()->get();
            $categories = Category::where('status', 1)->get();
            $bank = SurveyQuestionBank::with('category', 'subCategory', 'group')->find($id);


            return view('survey::survey_bank', compact('groups', 'bank', 'categories'));
        } catch (\Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }

    public function index(Request $request)
    {
        try {
            if ($request->group) {
                $group = $request->group;
            } else {
                $group = '';
            }
            if ($request->category) {
                $category = $request->category;
            } else {
                $category = '';
            }
            $groups = SurveyGroup::latest()->get();
            $categories = Category::where('status', 1)->get();
            return view('survey::survey_bank_list', compact('group', 'groups', 'categories', 'category'));
        } catch (\Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }

    public function store(Request $request)
    {
        $user = Auth::user();
        if (demoCheck()) {
            return redirect()->back();
        }
//        linear_option
        $options = [
            'checkbox',
            'dropdown',
            'radio'
        ];

        if (in_array($request->question_type, $options)) {
            $rules = [
                'group' => "required",
                'category' => "required",
                'question' => "required",
                'question_type' => "required",
                'number_of_option' => "required"
            ];

        } elseif ($request->question_type == 'linear_scale') {
            $rules = [
                'group' => "required",
                'category' => "required",
                'question' => "required",
                'question_type' => "required",
                'linear_option' => "required",
            ];
        } else {
            $rules = [
                'group' => "required",
                'category' => "required",
                'question' => "required",
                'question_type' => "required",
            ];
        }

        $this->validate($request, $rules, validationMessage($rules));

        try {
            $question = new SurveyQuestionBank();
            $question->type = $request->question_type;
            $question->group_id = (int)$request->group;
            $question->category_id = (int)$request->category;
            $question->sub_category_id = (int)$request->sub_category;
            $question->question = $request->question;
            $question->number_of_option = (int)($request->question_type == 'linear_scale' ? $request->linear_option : $request->number_of_option);
            $question->user_id = (int)$user->id;
            $question->save();

            if (in_array($request->question_type, $options)) {
                $i = 0;
                if (isset($request->option)) {
                    foreach ($request->option as $option) {
                        $i++;
                        $online_question_option = new SurveyQuestionBankMuOption();
                        $online_question_option->survey_question_bank_id = (int)$question->id;
                        $online_question_option->title = $option;
                        $online_question_option->save();
                    }
                }
            }
            $question->save();
            if ($request->image) {
                $question->image = $this->generateLink($request->image, $question->id, get_class($question), 'image');
            }
            $question->save();


            Toastr::success(trans('common.Operation successful'), trans('common.Success'));
            return redirect(route('survey.survey-bank-list'));
        } catch (\Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }

    public function update(Request $request, $id)
    {
        if (demoCheck()) {
            return redirect()->back();
        }
        $user = Auth::user();
        $options = [
            'checkbox',
            'dropdown',
            'radio',
            'linear_scale'
        ];

        if (in_array($request->question_type, $options)) {
            $rules = [
                'group' => "required",
                'category' => "required",
                'question' => "required",
                'question_type' => "required",
                'number_of_option' => "required"
            ];

        } else {
            $rules = [
                'group' => "required",
                'category' => "required",
                'question' => "required",
                'question_type' => "required",
            ];
        }

        $this->validate($request, $rules, validationMessage($rules));

        try {

            $question = SurveyQuestionBank::find($id);
            $question->type = $request->question_type;
            $question->group_id = $request->group;
            $question->category_id = $request->category;
            $question->sub_category_id = $request->sub_category;
            $question->question = $request->question;
            $question->number_of_option = $request->type == 'linear_scale' ? $request->linear_option : $request->number_of_option;
            $question->user_id = $user->id;
            $question->save();


            $question->questionMu()->delete();

            if (in_array($request->question_type, $options)) {
                if (isset($request->option)) {
                    foreach ($request->option as $option) {
                        $online_question_option = new SurveyQuestionBankMuOption();
                        $online_question_option->survey_question_bank_id = $question->id;
                        $online_question_option->title = $option;
                        $online_question_option->save();
                    }
                }
            }

            $question->image = null;
            $question->save();

            $this->removeLink($question->id, get_class($question));
            if ($request->image) {
                $question->image = $this->generateLink($request->image, $question->id, get_class($question), 'image');
            }
            $question->save();


            Toastr::success(trans('common.Operation successful'), trans('common.Success'));
            return redirect(route('survey.survey-bank-list'));

        } catch (\Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }


    public function destroy(Request $request)
    {

        if (demoCheck()) {
            return redirect()->back();
        }

        try {
            $id = $request->id;

            $question = SurveyQuestionBank::findOrFail($id);

            $question->questionMu()->delete();

            $result = $question->delete();

            if ($result) {
                Toastr::success(trans('common.Operation successful'), trans('common.Success'));
                return redirect(route('survey.survey-bank-list'));
            } else {
                Toastr::error(trans('common.Operation failed'), trans('common.Failed'));
                return redirect()->back();
            }
        } catch (\Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }

    public function data(Request $request)
    {
        try {
            $user = Auth::user();

            if ($user->role_id == 2) {
                $queries = SurveyQuestionBank::latest()->with('category', 'subCategory', 'group')->where('user_id', $user->id);
            } else {
                $queries = SurveyQuestionBank::latest()->with('category', 'subCategory', 'group');
            }

            if ($request->category) {
                $queries->where('category_id', $request->category);
            }
            if ($request->question_type) {
                $queries->where('type', $request->question_type);
            }


            return Datatables::of($queries)
                ->addIndexColumn()
                ->addColumn('group_title', function ($query) {
                    return $query->group->title;

                })->editColumn('category_name', function ($query) {
                    return $query->category->name;

                })->editColumn('question', function ($query) {
                    return Str::limit(strip_tags($query->question), 100);
                })->editColumn('image', function ($query) {
                    if (empty($query->image)) {
                        $return = '';
                    } else {
                        $return = '<img style="max-width: 150px;" src="' . asset($query->image) . '">';
                    }
                    return $return;
                })->editColumn('type', function ($query) {

                    if ($query->type == "checkbox") {
                        return trans('survey.Checkbox');
                    } elseif ($query->type == "dropdown") {
                        return trans('survey.Dropdown');
                    } elseif ($query->type == "radio") {
                        return trans('survey.Radio');
                    } elseif ($query->type == "linear_scale") {
                        return trans('survey.Linear Scale');
                    } else {
                        return trans('survey.TextArea');
                    }


                })->addColumn('action', function ($query) {

                    if (permissionCheck('survey.survey-bank-update')) {

                        $quiz_bank_edit = ' <a class="dropdown-item edit_brand"
                                                               href="' . route('survey.survey-bank-edit', [$query->id]) . '">' . trans('common.Edit') . '</a>';
                    } else {
                        $quiz_bank_edit = "";
                    }


                    if (permissionCheck('survey.survey-bank-delete')) {

                        $quiz_bank_delete = '<button class="dropdown-item deleteQuiz_bank"
                                                                    data-id="' . $query->id . '"
                                                                    type="button">' . trans('common.Delete') . '</button>';
                    } else {
                        $quiz_bank_delete = "";
                    }

                    $actioinView = ' <div class="dropdown CRM_dropdown">
                                                    <button class="btn btn-secondary dropdown-toggle" type="button"
                                                            id="dropdownMenu2" data-bs-toggle="dropdown"
                                                            aria-haspopup="true"
                                                            aria-expanded="false">
                                                        ' . trans('common.Action') . '
                                                    </button>
                                                    <div class="dropdown-menu dropdown-menu-right"
                                                         aria-labelledby="dropdownMenu2">
                                                        ' . $quiz_bank_edit . '
                                                        ' . $quiz_bank_delete . '




                                                    </div>
                                                </div>';

                    return $actioinView;


                })
                ->rawColumns(['action', 'image', 'question'])->make(true);
        } catch (\Exception $e) {
        }
    }

    public function questionBulkImport()
    {
        $groups = SurveyGroup::latest()->get();
        $categories = Category::whereNull('parent_id')->latest()->get();

        return view('survey::bulk-import', compact('groups', 'categories'));
    }

    public function downloadSample()
    {
        return Excel::download(new ExportSurveySampleQuestion(), 'sample-survey-questions.xlsx');

    }

    public function questionBulkImportSubmit(Request $request)
    {

        if (demoCheck()) {
            return redirect()->back();
        }

        $rules = [
            'group' => "required",
            'category' => "required",
            'excel_file' => 'required',
        ];

        $this->validate($request, $rules, validationMessage($rules));

        if ($request->hasFile('excel_file')) {
            $extension = File::extension($request->excel_file->getClientOriginalName());
            if ($extension != "xlsx" && $extension != "xls") {
                Toastr::error(trans('frontend.Excel File is Required'), trans('common.Failed'));
                return redirect()->back();
            }
        }

        try {
            Excel::import(new SurveyQuestionBankImport($request->group, $request->category, $request->sub_category), $request->excel_file);

            Toastr::success(trans('common.Operation successful'), trans('common.Success'));

            return redirect(route('survey.survey-bank-list'));
        } catch (\Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());

        }
    }

}
