<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

use App\Models\QuestionnaireSection;
use App\Models\QuestionnairePart;
use Illuminate\Support\Facades\Auth;

class QuestionnaireSectionController extends Controller
{

    const SECTIONS_BLADE = 'src/questionnaire_sections';
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        $questionnairesections = QuestionnaireSection::all();
        $questionnaireparts = QuestionnairePart::all();

        return view(QuestionnaireSectionController::SECTIONS_BLADE,
            ['questionnairesections' => $questionnairesections,
             'questionnaireparts' => $questionnaireparts,
             'selectedQuestionnaireSection' => null]);
    }

    public function save(Request $request){

        $data = $request->validate([
            'section_name' => 'required|max:255',
            'questionnaire_part_id' => 'required'
        ]);

        $data['created_by'] = Auth::user()->user_id;
    
        $selected = $request->selected_questionnairesection;
    
        if($selected){
            tap(QuestionnaireSection::where('questionnaire_section_id', 
            $selected)->update($data));
        }else {
            tap(new QuestionnaireSection($data))->save();
        }

        return redirect('/questionnairesections');
    }

    public function search(Request $request){

        $keyword = $request->keyword;
        $questionnairesections = DB::select(Db::raw("select * from questionnaire_section
             inner join questionnaire_part on 
             questionnaire_section.questionnaire_part_id = 
             questionnaire_part.questionnaire_part_id where section_name
             like '%".$keyword."%' or part_name like '%".$keyword."%'"));
        return json_encode($questionnairesections);
    }

    public function edit($id) {
        
        $questionnaireSectionId = $id;
        $selectedQuestionnaireSection = QuestionnaireSection::find($questionnaireSectionId);
        $questionnairesections = QuestionnaireSection::all();
        $questionnaireparts = QuestionnairePart::all();

        return view(QuestionnaireSectionController::SECTIONS_BLADE, 
            ['questionnairesections' => $questionnairesections,
             'questionnaireparts' => $questionnaireparts,
            'selectedQuestionnaireSection' => $selectedQuestionnaireSection]);
    }

    public function del(Request $request) {

        $questionnaireSectionId = $request->deletequestionnairesection;
        $questionnairesection = QuestionnaireSection::find($questionnaireSectionId);
        $questionnairesection->delete();

        return redirect('/questionnairesections');
    }
}