<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Answer;
use App\Models\Question;
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 AnswerController extends Controller
{
    public function index(Request $request)
    {
        $answers = Answer::with('question.chatCategory')->orderBy('created_at', 'desc')->get();
        $questions = Question::where('status', 1)->with('chatCategory')->get();
        $selectedQuestion = null;

        if ($request->has('question_id') && $request->question_id) {
            $selectedQuestion = Question::find($request->question_id);
        }

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

    public function getAnswerList(Request $request)
    {
        $sqlBuilder = Answer::with('question.chatCategory')->select([
            'answers.id',
            'answers.question_id',
            'answers.name',
            'answers.name_ar',
            'answers.status',
        ]);

        if ($request->has('question_id') && $request->question_id) {
            $sqlBuilder->where('answers.question_id', $request->question_id);
        }

        return DataTables::of($sqlBuilder)
            ->addColumn('question_name', function ($data) {
                return $data->question ? $data->question->name : 'N/A';
            })
            ->addColumn('chat_category_name', function ($data) {
                return $data->question && $data->question->chatCategory ? $data->question->chatCategory->name : 'N/A';
            })
            ->filter(function ($query) use ($request) {
                if ($request->has('search') && !empty($request->search['value'])) {
                    $query->where('answers.name', 'ilike', "%" . $request->search['value'] . "%")
                    ->orWhere('answers.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.answers.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.answers.edit', ['id' => $data->id]) . '">Edit</a></li>
                                            <li><a class="dropdown-item delete-btn" data-url="' . route('admin.answers.destroy', ['id' => $data->id]) . '">Delete</a></li>
                                        </ul>
                                    </div>';
                return $html;
            })
            ->rawColumns(['status', 'action'])
            ->make(true);
    }

    public function create($question_id = null)
    {
        $answer = "";
        $questions = Question::where('status', 1)->with('chatCategory')->get();
        $selectedQuestion = null;
        if ($question_id) {
            $selectedQuestion = Question::find($question_id);
        }

        return view('admin.answers.create', compact('answer', 'questions', 'selectedQuestion'));
    }

    public function store(Request $request)
    {
        $rules = [
            'question_id' => 'required|exists:questions,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) {
            $answer = Answer::find($request->id);

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

            $answer->question_id = $request->question_id;
            $answer->name = $request->name;
            $answer->name_ar = $request->name_ar;
            $answer->status = $request->status;
            $answer->save();

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

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

    public function edit($id)
    {
        $answer = Answer::findOrFail($id);
        $questions = Question::where('status', 1)->with('chatCategory')->get();

        return view('admin.answers.create', compact('answer', 'questions'));
    }

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

    public function statusChange(Request $request, $id)
    {
        $answer = Answer::find($id);

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

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

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