<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Exports\Normal_Question_Export;
use App\Imports\Normal_Question_Import;
use App\Models\Category;
use App\Models\Common;
use App\Models\Classification;
use App\Models\Level;
use App\Models\Normal_Quiz_Question;
use App\Models\Skill;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;
use Exception;

class NormalQuestionController extends Controller
{
    private $folder = "question";
    public $common;
    public function __construct()
    {
        $this->common = new Common;
    }

    public function index(Request $request)
    {
        try {
            $params['category'] = Category::orderBy('sort_order', 'asc')->latest()->get();
            $params['skill'] = Skill::orderBy('sort_order', 'asc')->latest()->get();
            $params['classification'] = Classification::orderBy('sort_order', 'asc')->latest()->get();
            $params['level'] = Level::orderBy('sort_order', 'asc')->latest()->get();

            if ($request->ajax()) {

                $input_search = $request['input_search'];
                $input_category = $request['input_category'];
                $input_skill = $request['input_skill'];
                $input_classification = $request['input_classification'];
                $input_level = $request['input_level'];

                $query = Normal_Quiz_Question::latest();
                if ($input_search) {
                    $query->where(function ($q) use ($input_search) {
                        $q->where('question', 'LIKE', "%{$input_search}%")
                            ->orWhere('option_a', 'LIKE', "%{$input_search}%")
                            ->orWhere('option_b', 'LIKE', "%{$input_search}%")
                            ->orWhere('option_c', 'LIKE', "%{$input_search}%")
                            ->orWhere('option_d', 'LIKE', "%{$input_search}%");
                    });
                }
                if ($input_category != 0) {
                    $query->where('category_id', $input_category);
                }
                if ($input_skill != 0) {
                    $query->where('skill_id', $input_skill);
                }
                if ($input_classification != 0) {
                    $query->where('classification_id', $input_classification);
                }
                if ($input_level != 0) {
                    $query->where('level_id', $input_level);
                }
                $data = $query->with('category', 'skill', 'classification', 'level')->latest()->get();

                $this->common->imageNameToUrl($data, 'image', $this->folder);

                return DataTables()::of($data)
                    ->addIndexColumn()
                    ->addColumn('action', function ($row) {

                        $question_delete = __('label.delete_question');

                        $delete = '<form onsubmit="return confirm(\'' . $question_delete . '\');" method="POST" action="' . route('admin.normalquestion.destroy', [$row->id]) . '">
                        <input type="hidden" name="_token" value="' . csrf_token() . '">
                        <input type="hidden" name="_method" value="DELETE">
                        <button type="submit" class="edit-delete-btn" style="outline: none;"><i class="fa-solid fa-trash-can fa-xl"></i></button></form>';

                        $btn = '<div class="d-flex justify-content-around">';
                        $btn .= '<a href="' . route('admin.normalquestion.edit', [$row->id]) . '" class="edit-delete-btn mr-2">';
                        $btn .= '<i class="fa-solid fa-pen-to-square fa-xl"></i>';
                        $btn .= '</a>';
                        $btn .= $delete;
                        $btn .= '</div>';
                        return $btn;
                    })
                    ->addColumn('status', function ($row) {
                        if ($row->status == 1) {
                            $showLabel = __('label.show');
                            return "<button type='button' id='$row->id' onclick='change_status($row->id)' class='show-btn'>$showLabel</button>";
                        } else {
                            $hideLabel = __('label.hide');
                            return "<button type='button' id='$row->id' onclick='change_status($row->id)' class='hide-btn'>$hideLabel</button>";
                        }
                    })
                    ->rawColumns(['action', 'status'])
                    ->make(true);
            }
            return view('admin.normal_question.index', $params);
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function create()
    {
        try {

            $params['quiz_configuration'] = $this->common->Quiz_Configuration(2);
            $params['category'] = Category::where('status', 1)->orderBy('sort_order', 'asc')->latest()->get();
            $params['skill'] = Skill::where('status', 1)->orderBy('sort_order', 'asc')->latest()->get();
            $params['classification'] = Classification::where('status', 1)->orderBy('sort_order', 'asc')->latest()->get();
            $params['level'] = Level::where('status', 1)->orderBy('sort_order', 'asc')->latest()->get();

            return view('admin.normal_question.add', $params);
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'question' => 'required',
                'option_a' => 'required',
                'option_b' => 'required',
                'option_c' => 'required',
                'option_d' => 'required',
                'correct_answer' => 'required',
                'image' => 'image|mimes:jpeg,png,jpg|max:5120',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(['status' => 400, 'errors' => $errs]);
            }

            $question = new Normal_Quiz_Question();
            $question['category_id'] = $request['category_id'] ?? 0;
            $question['skill_id'] = $request['skill_id'] ?? 0;
            $question['classification_id'] = $request['classification_id'] ?? 0;
            $question['level_id'] = $request['level_id'] ?? 0;
            $question['image'] = '';
            if (isset($request['image'])) {
                $file = $request['image'];
                $question['image'] = $this->common->saveImage($file, $this->folder, 'normal_img_');
            }
            $question['question'] = $request['question'];
            $question['option_a'] = $request['option_a'];
            $question['option_b'] = $request['option_b'];
            $question['option_c'] = $request['option_c'];
            $question['option_d'] = $request['option_d'];
            $question['correct_answer'] = $request['correct_answer'];
            $question['note'] = $request['note'] ?? '';
            $question['status'] = 1;
            if ($question->save()) {
                return response()->json(['status' => 200, 'success' => __('label.success_add_question')]);
            } else {
                return response()->json(['status' => 400, 'errors' => __('label.error_add_question')]);
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function edit($id)
    {
        try {

            $params['result'] = Normal_Quiz_Question::where('id', $id)->first();
            if ($params['result']) {

                $this->common->imageNameToUrl(array($params['result']), 'image', $this->folder);

                $params['quiz_configuration'] = $this->common->Quiz_Configuration(2);
                $params['category'] = Category::where('status', 1)->orderBy('sort_order', 'asc')->latest()->get();
                $params['skill'] = Skill::where('status', 1)->orderBy('sort_order', 'asc')->latest()->get();
                $params['classification'] = Classification::where('status', 1)->orderBy('sort_order', 'asc')->latest()->get();
                $params['level'] = Level::where('status', 1)->orderBy('sort_order', 'asc')->latest()->get();

                return view('admin.normal_question.edit', $params);
            } else {
                return redirect()->back()->with('error', __('label.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function update(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'question' => 'required',
                'option_a' => 'required',
                'option_b' => 'required',
                'option_c' => 'required',
                'option_d' => 'required',
                'correct_answer' => 'required',
                'image' => 'image|mimes:jpeg,png,jpg|max:5120',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(['status' => 400, 'errors' => $errs]);
            }

            $question = Normal_Quiz_Question::where('id', $request['id'])->first();
            if (isset($question)) {

                $question['category_id'] = $request['category_id'] ?? 0;
                $question['skill_id'] = $request['skill_id'] ?? 0;
                $question['classification_id'] = $request['classification_id'] ?? 0;
                $question['level_id'] = $request['level_id'] ?? 0;
                if (isset($request['image'])) {
                    $file = $request['image'];
                    $question['image'] = $this->common->saveImage($file, $this->folder, 'normal_img_');

                    $this->common->deleteImageToFolder($this->folder, basename($request['old_image']));
                }
                $question['question'] = $request['question'];
                $question['option_a'] = $request['option_a'];
                $question['option_b'] = $request['option_b'];
                $question['option_c'] = $request['option_c'];
                $question['option_d'] = $request['option_d'];
                $question['correct_answer'] = $request['correct_answer'];
                $question['note'] = $request['note'] ?? '';
                if ($question->save()) {
                    return response()->json(['status' => 200, 'success' => __('label.success_edit_question')]);
                } else {
                    return response()->json(['status' => 400, 'errors' => __('label.error_edit_question')]);
                }
            } else {
                return response()->json(['status' => 400, 'errors' => __('label.error_edit_question')]);
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function destroy($id)
    {
        try {

            $question = Normal_Quiz_Question::where('id', $id)->first();
            if (isset($question)) {
                $this->common->deleteImageToFolder($this->folder, $question['image']);
                $question->delete();
            }
            return redirect()->route('admin.normalquestion.index')->with('success', __('label.question_delete'));
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function show($id)
    {
        try {

            $data = Normal_Quiz_Question::where('id', $id)->first();
            if (isset($data)) {

                $data['status'] = $data['status'] === 1 ? 0 : 1;
                $data->save();
                return response()->json(['status' => 200, 'success' => __('label.status_changed'), 'status_code' => $data->status]);
            } else {
                return response()->json(['status' => 400, 'errors' => __('label.data_not_found')]);
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    // Import-Export 
    public function import_export_index()
    {
        try {

            $params['data'] = [];
            return view('admin.normal_question.import', $params);
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function export(Request $request)
    {
        try {
            return Excel::download(new Normal_Question_Export(), 'Normal-Quiz-Question-Formate.csv');
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function import(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'import_file' => 'required|file|mimetypes:text/plain,text/csv,application/csv',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(['status' => 400, 'errors' => $errs]);
            }

            Excel::import(new Normal_Question_Import, $request->file('import_file'));

            return response()->json(['status' => 200, 'success' => __('label.success_import_file')]);
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
}
