<?php

namespace App\Http\Controllers\Admins;

use App\Http\Controllers\Controller;
use App\Models\Master\Kabupatens;
use App\Models\Master\Kecamatans;
use App\Models\Master\Kelurahans;
use App\Models\Master\ManagementMasters;
use App\Models\Master\Provinsis;
use App\Models\QuestionAnswers;
use App\Models\QuestionDetails;
use App\Models\QuestionSurveys;
use App\Models\Surveys;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;

class SurveyController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // call data
        $surveys = Surveys::where('status', '!=', 'Deleted')->paginate(10);

        // return view
        return view('pages.admins.surveys.index', compact('surveys'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $survey = Surveys::create([
            'name' => 'Survey Tanpa Nama',
            'status' => 'Published'
        ]);

        QuestionSurveys::create([
            'survey_id' => $survey->id,
            'name' => 'Pertanyaan anda?',
            'type' => 'Iya atau Tidak',
        ]);

        // redirect
        return Redirect::to('admin/surveys/' . $survey->id . '/edit');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        return [
            'semua' => $request->all(),
            'test' => $request->type[1] . " " . $request->valuefromtype[1]
        ];
    }

    // Preview / Give Answer for Admin
    public function preview_admin(string $id)
    {
        // find data
        $survey = Surveys::where('status', '!=', 'Deleted')
            ->with(['questionSurveys' => fn ($query) => $query->where('status', '!=', 'Deleted')])
            ->findOrFail($id);
        // $responden = User::role('Staff')->get();

        // return json_decode($survey->questionSurveys[15]->questionDetails->question_value)[0];
        // return view
        return view('pages.admins.surveys.preview-admin', compact('survey'));
    }

    // Preview / Give Answer for User
    public function preview_user(string $id)
    {
        $answer = QuestionAnswers::where('survey_id', $id)->where('user_id', Auth::user()->id)->count();
        if ($answer) {
            // Create Session message
            Session::flash('surveys-message', [
                'type' => 'warning',
                'msg' => 'Anda sudah mengisi survey!'
            ]);
            return Redirect::to('admin/surveys');
        }
        // find data
        $survey = Surveys::where('status', '!=', 'Deleted')
            ->with(['questionSurveys' => fn ($query) => $query->where('status', '!=', 'Deleted')])
            ->findOrFail($id);

        // return view
        return view('pages.admins.surveys.preview-user', compact('survey'));
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        // find data
        $survey = Surveys::where('status', '!=', 'Deleted')->with('questionSurveys')->findOrFail($id);

        // Data Answers
        $answerPerson = QuestionAnswers::where('survey_id', $id);
        if (auth()->user()->getRoleNames()->first() == 'Responden') {
            $answerPerson = $answerPerson->where('user_id', auth()->user()->id);
        }
        $answerPerson = $answerPerson->groupBy('user_id')->get();

        // return view
        return view('pages.admins.surveys.detail', compact('survey', 'answerPerson'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        // find data
        $survey = Surveys::where('status', '!=', 'Deleted')->findOrFail($id);
        $management_master = ManagementMasters::get();

        // return view
        return view('pages.admins.surveys.edit', compact('survey', 'management_master'));
    }

    // SaveSurvey (Autosaved)
    public function saveSurvey(Request $request, string $id)
    {
        $survey = Surveys::findOrFail($id);
        $survey->update($request->all());
        return $survey;
    }

    // Add Data Question (Autosaved)
    public function addQuestion(string $id)
    {
        $questionSurvey = QuestionSurveys::create([
            'survey_id' => $id,
            'name' => 'Pertanyaan anda?',
            'type' => 'Iya atau Tidak',
        ]);

        QuestionDetails::create([
            'question_id' => $questionSurvey->id,
            'question_label' => '["Iya", "Tidak"]',
            'question_value' => '[1, 0]',
        ]);

        // return data
        return $questionSurvey;
    }

    // Save Question (Autosaved)
    public function saveQuestion(Request $request, string $id)
    {
        $questionSurveys = QuestionSurveys::findOrFail($id);
        foreach ($request->questionSurvey as $key => $value) {
            if ($value['type'] == null) $value['type'] = 'Iya atau Tidak';
            $questionSurveys->update([
                'name' => $value['question'],
                'type' => $value['type']
            ]);

            if ($value['type'] == 'Skala') {
                QuestionDetails::updateOrCreate([
                    'question_id' => $questionSurveys->id,
                ], [
                    'question_label' => '["' . $value['labelfrom'] . '","' . $value['labelto'] . '"]',
                    'question_value' => '["' . $value['valuefrom'] . '","' . $value['valueto'] . '"]',
                ]);
            } else if ($value['type']  == 'Jawaban Angka') {
                QuestionDetails::updateOrCreate([
                    'question_id' => $questionSurveys->id,
                ], [
                    'question_label' => '["Jawaban Angka"]',
                    'question_value' => '["Angka"]',
                ]);
            } else if ($value['type']  == 'Jawaban Singkat') {
                QuestionDetails::updateOrCreate([
                    'question_id' => $questionSurveys->id,
                ], [
                    'question_label' => '["Jawaban Singkat"]',
                    'question_value' => '["Teks Jawaban Singkat"]',
                ]);
            } else if ($value['type']  == 'Esai') {
                QuestionDetails::updateOrCreate([
                    'question_id' => $questionSurveys->id,
                ], [
                    'question_label' => '["Esai"]',
                    'question_value' => '["Teks"]',
                ]);
            } else if ($value['type']  == 'Master') {
                QuestionDetails::updateOrCreate([
                    'question_id' => $questionSurveys->id,
                ], [
                    'question_label' => '["Master"]',
                    'question_value' => $value['master'],
                    // 'question_value' => '["' . $value['master'] . '"]',
                ]);
            } else {
                QuestionDetails::updateOrCreate([
                    'question_id' => $questionSurveys->id,
                ], [
                    'question_label' => '["Iya", "Tidak"]',
                    'question_value' => '[1, 0]',
                ]);
            }
        }
        return $questionSurveys;
    }

    // Delete Question
    public function deleteQuestion(string $id)
    {
        // Find Question
        $question = QuestionSurveys::findOrFail($id);

        if ($question->questionAnswers) {
            $question->update([
                'status' => 'Deleted'
            ]);

            return [
                'msg_status' => "Success Deleted (s)",
                'question' => $question,
            ];
        } else {
            $question = $question->delete();
            return [
                'msg_status' => "Success Deleted",
                'question' => $question,
            ];
        }
    }

    // Add Data Answers
    public function addAnswers(Request $request)
    {
        // return $request;
        // create unique answer_id
        $unique_answer_id = QuestionAnswers::select('answer_id')->groupby('answer_id')->latest()->first();
        $unique_answer_id = empty($unique_answer_id) ? 1 : $unique_answer_id['answer_id'] + 1;

        // validation
        $request->validate([
            'question.*.answer' => 'required',
            'survey_id' => 'required',
        ]);

        $question = QuestionSurveys::where('survey_id', $request->survey_id)->get();

        foreach ($question as $_question) {
            QuestionAnswers::create([
                'user_id' => ($request->responden) ?? Auth::user()->id,
                'question_id' => $_question->id,
                'answer_id' => $unique_answer_id,
                'answer_type' => $_question->type,
                'answer' => isset($request->question[$_question->id]) ? $request->question[$_question->id]['answer'] : null,
                'survey_id' => $request->survey_id,
            ]);
        }

        // Create Session message
        Session::flash('surveys-message', [
            'type' => 'success',
            'msg' => 'Anda berhasil mengirimkan jawaban survey!'
        ]);
        return Redirect::to('admin/surveys');
    }

    public function cariResponden(Request $request, String $survey_id)
    {
        $answer = QuestionAnswers::select('user_id')->where('survey_id', $survey_id)->groupBy('user_id')->pluck('user_id');
        $data = [];
        if ($request->has('q')) {
            $search = $request->q;
            $data = User::role('Responden')->select("id", "nik", "name")
                ->where(function ($query) use ($search) {
                    $query->where('name', 'LIKE', "%$search%")
                        ->orWhere('nik', 'LIKE', "%$search%");
                })
                ->whereNotIn('id', $answer)
                ->limit(10)
                ->get();
        }
        return response()->json($data);
    }

    public function cariMaster(Request $request, String $master)
    {
        $master = ManagementMasters::where('master_value', $master)->first();
        $data = [];
        if ($request->has('q')) {
            $search = $request->q;
            $data = 'App\Models\Master\\' . $master->master_value;
            $data = $data::selectRaw($master->master_column . ' as name, id')
                ->where($master->master_column, 'LIKE', "%$search%")
                ->limit(15)
                ->get();
        }
        return response()->json($data);
    }

    public function cariProvinsi(Request $request)
    {
        $data = [];
        if ($request->has('q')) {
            $search = $request->q;
            $data = Provinsis::selectRaw('nama as name, id')
                ->where('nama', 'LIKE', "%$search%")
                ->limit(15)
                ->get();
        }
        return response()->json($data);
    }

    public function cariKabupaten(Request $request, String $provId)
    {
        $data = [];
        if ($request->has('q')) {
            $search = $request->q;
            $data = Kabupatens::selectRaw('nama as name, id')
                ->where('nama', 'LIKE', "%$search%")
                ->where('provinsi_id', $provId)
                ->limit(15)
                ->get();
        }
        return response()->json($data);
    }

    public function cariKecamatan(Request $request, String $kabId)
    {
        $data = [];
        if ($request->has('q')) {
            $search = $request->q;
            $data = Kecamatans::selectRaw('nama as name, id')
                ->where('nama', 'LIKE', "%$search%")
                ->where('kabupaten_id', $kabId)
                ->limit(15)
                ->get();
        }
        return response()->json($data);
    }

    public function cariKelurahan(Request $request, String $kecId)
    {
        $data = [];
        if ($request->has('q')) {
            $search = $request->q;
            $data = Kelurahans::selectRaw('nama as name, id')
                ->where('nama', 'LIKE', "%$search%")
                ->where('kecamatan_id', $kecId)
                ->limit(15)
                ->get();
        }
        return response()->json($data);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function delete(Surveys $survey)
    {
        // // remove
        // $survey->update([
        //     'status' => 'Deleted'
        // ]);

        // // Create Session message
        // Session::flash('users-message', [
        //     'type' => 'success',
        //     'msg' => 'Anda berhasil menambahkan data!'
        // ]);

        // return Redirect::to('admin/users');

        // try {
        //     //code...
        // } catch (\Throwable $th) {
        //     //throw $th;
        // }
    }
}
