<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Question;
use App\Models\ChatCategory;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\JsonResponse;
use Yajra\DataTables\Facades\DataTables;

class QuestionController extends Controller
{
    public function index()
    {
        $questions = Question::with('chatCategory')->orderBy('created_at', 'desc')->get();
        $chatCategories = ChatCategory::where('status', 1)->get();

        return view('admin.questions.index', compact('questions', 'chatCategories'));
    }

    public function getQuestionList(Request $request)
    {
        $sqlBuilder = Question::with('chatCategory')->select([
            'questions.id',
            'questions.chat_category_id',
            'questions.name',
            'questions.name_ar',
            'questions.status',
        ]);

        return DataTables::of($sqlBuilder)
            ->addColumn('chat_category_name', function ($data) {
                return $data->chatCategory ? $data->chatCategory->name : 'N/A';
            })
            ->filter(function ($query) use ($request) {
                if ($request->has('search') && !empty($request->search['value'])) {
                    $query->where('questions.name', 'ilike', "%" . $request->search['value'] . "%")
                    ->orWhere('questions.name_ar', 'ilike', "%" . $request->search['value'] . "%");
                }
            })
            ->editColumn('status', function ($data) {
                return '<div class="status">
                <div class="form-check form-switch ">
                    <input class="form-check-input status-checkbox" type="checkbox" role="switch" id="SwitchCheck4" data-url="' . route('admin.questions.status', ['id' => $data->id]) . '" data-id="' . $data->id . '" ' . (!empty($data->status) && $data->status == 1 ? 'checked' : '') . ' />
                </div>
            </div>';
            })
            ->addColumn('action', function ($data) {
                $html = '<div class="dropdown">
                                        <a href="#" class="btn btn-soft-secondary btn-sm" role="button" id="dropdownMenuLink5" data-bs-toggle="dropdown" aria-expanded="false">
                                            <i class="ri-more-2-fill"></i>
                                        </a>
                                        <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink5">
                                            <li><a class="dropdown-item" href="' . route('admin.questions.edit', ['id' => $data->id]) . '">Edit</a></li>
                                            <li><a class="dropdown-item" href="' . route('admin.answers', ['question_id' => $data->id]) . '">List Answers</a></li>
                                            <li><a class="dropdown-item" href="' . route('admin.answers.create', ['question_id' => $data->id]) . '">Create Answer</a></li>
                                            <li><a class="dropdown-item delete-btn" data-url="' . route('admin.questions.destroy', ['id' => $data->id]) . '">Delete</a></li>
                                        </ul>
                                    </div>';
                return $html;
            })
            ->rawColumns(['status', 'action'])
            ->make(true);
    }

    public function create()
    {
        $question = "";
        $chatCategories = ChatCategory::where('status', 1)->get();

        return view('admin.questions.create', compact('question', 'chatCategories'));
    }

    public function store(Request $request)
    {
        $rules = [
            'chat_category_id' => 'required|exists:chat_categories,id',
            'name' => 'required|string|max:255',
            'name_ar' => 'required|string|max:255',
            'status' => 'required|in:0,1',
        ];

        $validator = Validator::make($request->all(), $rules);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'errors' => $validator->errors(),
            ], 422);
        }

        if ($request->id) {
            $question = Question::find($request->id);

            if (!$question) {
                return response()->json(['status' => 'error', 'message' => 'Question not found'], 404);
            }

            $question->chat_category_id = $request->chat_category_id;
            $question->name = $request->name;
            $question->name_ar = $request->name_ar;
            $question->status = $request->status;
            $question->save();

            return response()->json(['status' => 'success', 'message' => 'Question updated successfully']);
        } else {
            $question = Question::create([
                'chat_category_id' => $request->chat_category_id,
                'name' => $request->name,
                'name_ar' => $request->name_ar,
                'status' => $request->status,
            ]);

            return response()->json(['status' => 'success', 'message' => 'Question added successfully', 'question' => $question]);
        }
    }

    public function edit($id)
    {
        $question = Question::findOrFail($id);
        $chatCategories = ChatCategory::where('status', 1)->get();

        return view('admin.questions.create', compact('question', 'chatCategories'));
    }

    public function destroy($id): JsonResponse
    {
        try {
            $question = Question::findOrFail($id);
            $question->delete();
            return response()->json([
                'status' => 'success',
                'message' => 'Question deleted successfully.'
            ], 200);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Question not found.'
            ], 404);
        } catch (Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while deleting the question.'
            ], 500);
        }
    }

    public function statusChange(Request $request, $id)
    {
        $question = Question::find($id);

        if (!$question) {
            return response()->json([
                'status' => 'error',
                'message' => 'Question not found.'
            ], 404);
        }

        $question->status = $request->status;
        $question->save();

        return response()->json([
            'status' => 'success',
            'message' => 'Question status updated successfully.'
        ]);
    }
}