<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Exports\Ultimate_Challenge_Question_Export;
use App\Imports\Ultimate_Challenge_Question_Import;
use App\Models\Common;
use App\Models\Ultimate_Challenge;
use App\Models\Ultimate_Challenge_Leaderboard;
use App\Models\Ultimate_Challenge_Question;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;
use Exception;

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

    public function index(Request $request)
    {
        try {
            // Inactive 
            $this->common->Inactive_Challenge();

            $params['data'] = [];
            if ($request->ajax()) {

                $query = Ultimate_Challenge::query();

                $input_search = $request['input_search'];
                if ($input_search != null) {
                    $query->where('name', 'LIKE', "%{$input_search}%");
                }
                $data = $query->orderby('status', 'desc')->latest()->get();

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

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

                        $ultimate_challenge_delete = __('label.delete_ultimate_challenge');

                        $delete = '<form onsubmit="return confirm(\'' . $ultimate_challenge_delete . '\');" method="POST" action="' . route('admin.ultimatechallenge.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.ultimatechallenge.question.index', [$row->id]) . '" class="edit-delete-btn mr-2">';
                        $btn .= '<i class="fa-solid fa-circle-question fa-xl"></i>';
                        $btn .= '</a>';
                        $btn .= '<a href="' . route('admin.ultimatechallenge.leaderboard', [$row->id]) . '" class="edit-delete-btn mr-2">';
                        $btn .= '<i class="fa-solid fa-gauge fa-xl"></i>';
                        $btn .= '</a>';
                        $btn .= '<a class="edit-delete-btn mr-2 edit_ultimate_challenge" data-toggle="modal" href="#EditModel" data-id="' . $row->id . '" data-name="' . $row->name . '" data-image="' . $row->image . '" data-start_date="' . $row->start_date . '" data-end_date="' . $row->end_date . '" data-total_questions="' . $row->total_questions . '" data-quiz_duration="' . $row->quiz_duration . '" data-is_paid="' . $row->is_paid . '" data-joining_coin="' . $row->joining_coin . '" data-min_winning_percentage="' . $row->min_winning_percentage . '" data-winning_coin="' . $row->winning_coin . '">';
                        $btn .= '<i class="fa-solid fa-pen-to-square fa-xl"></i>';
                        $btn .= '</a>';
                        $btn .= $delete;
                        $btn .= '</a></div>';
                        return $btn;
                    })
                    ->addColumn('status', function ($row) {
                        if ($row->status == 1) {
                            $showLabel = __('label.active');
                            return "<button type='button' id='$row->id' onclick='change_status($row->id)' class='show-btn'>$showLabel</button>";
                        } else {
                            $hideLabel = __('label.inactive');
                            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.ultimate_challenge.index', $params);
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'name' => 'required|min:2',
                'image' => 'required|image|mimes:jpeg,png,jpg|max:5120',
                'start_date' => 'required|date|after_or_equal:today',
                'end_date'   => 'required|date|after_or_equal:start_date',
                'total_questions' => 'required|numeric|min:1',
                'quiz_duration' => 'required|numeric|min:1',
                'is_paid' => 'required',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(['status' => 400, 'errors' => $errs]);
            }

            $requestData = $request->all();
            $file = $requestData['image'];
            $requestData['image'] = $this->common->saveImage($file, $this->folder, 'ulti_ch_');
            $requestData['joining_coin'] = $request['joining_coin'] ?? 0;
            $requestData['min_winning_percentage'] = $request['min_winning_percentage'] ?? 0;
            $requestData['winning_coin'] = $request['winning_coin'] ?? 0;
            $requestData['status'] = 1;

            $data = Ultimate_Challenge::updateOrCreate(['id' => $requestData['id']], $requestData);
            if (isset($data['id'])) {
                return response()->json(['status' => 200, 'success' => __('label.success_add_ultimate_challenge')]);
            } else {
                return response()->json(['status' => 400, 'errors' => __('label.error_add_ultimate_challenge')]);
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function update($id, Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'name' => 'required|min:2',
                'image' => 'image|mimes:jpeg,png,jpg|max:5120',
                'start_date' => 'required|date',
                'end_date'   => 'required|date|after_or_equal:start_date',
                'total_questions' => 'required|numeric|min:1',
                'quiz_duration' => 'required|numeric|min:1',
                'is_paid' => 'required',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(['status' => 400, 'errors' => $errs]);
            }

            $requestData = $request->all();
            if (isset($requestData['image'])) {
                $file = $requestData['image'];
                $requestData['image'] = $this->common->saveImage($file, $this->folder, 'ulti_ch_');

                $this->common->deleteImageToFolder($this->folder, basename($requestData['old_image']));
            }
            unset($requestData['old_image']);
            $requestData['joining_coin'] = $request['joining_coin'] ?? 0;
            $requestData['min_winning_percentage'] = $request['min_winning_percentage'] ?? 0;
            $requestData['winning_coin'] = $request['winning_coin'] ?? 0;

            $data = Ultimate_Challenge::updateOrCreate(['id' => $requestData['id']], $requestData);
            if (isset($data['id'])) {
                return response()->json(['status' => 200, 'success' => __('label.success_edit_ultimate_challenge')]);
            } else {
                return response()->json(['status' => 400, 'errors' => __('label.error_edit_ultimate_challenge')]);
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function destroy($id)
    {
        try {

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

                // Question
                $question = Ultimate_Challenge_Question::where('ultimate_challenge_id', $id)->get();
                if (count($question) > 0) {

                    for ($i = 0; $i < count($question); $i++) {
                        $this->common->deleteImageToFolder($this->folder, $question[$i]['image']);
                        $question[$i]->delete();
                    }
                }

                $this->common->deleteImageToFolder($this->folder, $data['image']);
                $data->delete();
            }
            return redirect()->route('admin.ultimatechallenge.index')->with('success', __('label.ultimate_challenge_delete'));
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function show($id)
    {
        try {

            $data = Ultimate_Challenge::where('id', $id)->first();
            if ($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()]);
        }
    }
    public function question_index($id, Request $request)
    {
        try {

            $params['ultimate_challenge_id'] = $id;
            if ($request->ajax()) {

                $input_search = $request['input_search'];

                $query = Ultimate_Challenge_Question::where('ultimate_challenge_id', $id);
                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}%");
                    });
                }
                $data = $query->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.ultimatechallenge.question.delete', [$row->ultimate_challenge_id, $row->id]) . '">
                        <input type="hidden" name="_token" value="' . csrf_token() . '">
                        <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 class="edit-delete-btn mr-2 edit_ultimate_challenge_question" data-toggle="modal" href="#EditModel" data-id="' . $row->id . '" data-question="' . $row->question . '" data-image="' . $row->image . '" data-option_a="' . $row->option_a . '" data-option_b="' . $row->option_b . '" data-option_c="' . $row->option_c . '" data-option_d="' . $row->option_d . '" data-correct_answer="' . $row->correct_answer . '" data-note="' . $row->note . '">';
                        $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.ultimate_challenge.question', $params);
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function question_save(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'ultimate_challenge_id' => 'required',
                '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 Ultimate_Challenge_Question();
            $question['ultimate_challenge_id'] = $request['ultimate_challenge_id'];
            $question['image'] = '';
            if (isset($request['image'])) {
                $file = $request['image'];
                $question['image'] = $this->common->saveImage($file, $this->folder, 'ulti_ch_question_');
            }
            $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 question_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 = Ultimate_Challenge_Question::where('id', $request['id'])->first();
            if (isset($question)) {

                if (isset($request['image'])) {
                    $file = $request['image'];
                    $question['image'] = $this->common->saveImage($file, $this->folder, 'ulti_ch_question_');

                    $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 question_delete($ultimate_challenge_id, $id)
    {
        try {

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

            $data = Ultimate_Challenge_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 export(Request $request)
    {
        try {

            return Excel::download(new Ultimate_Challenge_Question_Export(), 'Ultimate-Challenge-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(), [
                'ultimate_challenge_id' => 'required|numeric',
                '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 Ultimate_Challenge_Question_Import($request['ultimate_challenge_id']), $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()]);
        }
    }
    // Leaderboard
    public function leaderboard($id, Request $request)
    {
        try {
            $params['ultimate_challenge_id'] = $id;
            $params['user'] = User::latest()->get();

            if ($request->ajax()) {

                $input_user = $request['input_user'];
                $input_start_date = $request['input_start_date'];
                $input_end_date = $request['input_end_date'];

                $query = Ultimate_Challenge_Leaderboard::where('ultimate_challenge_id', $id);
                if ($input_user != 0) {
                    $query->where('user_id', $input_user);
                }
                if (!empty($input_start_date)) {
                    $query->whereDate('created_at', '>=', date('Y-m-d', strtotime($input_start_date)));
                }
                if (!empty($input_end_date)) {
                    $query->whereDate('created_at', '<=', date('Y-m-d', strtotime($input_end_date)));
                }
                $data = $query->with('user')->latest()->get();

                return DataTables()::of($data)
                    ->addIndexColumn()
                    ->addColumn('status', function ($row) {
                        if ($row->status == 1) {
                            $showLabel = __('label.passed');
                            return "<button type='button' class='show-btn'>$showLabel</button>";
                        } else {
                            $hideLabel = __('label.failed');
                            return "<button type='button' class='hide-btn'>$hideLabel</button>";
                        }
                    })
                    ->addColumn('date', function ($row) {
                        return date("Y-m-d", strtotime($row['created_at']));
                    })
                    ->rawColumns(['status'])
                    ->make(true);
            }
            return view('admin.ultimate_challenge.leaderboard', $params);
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
}
