<?php

namespace App\Http\Controllers;

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

use App\Models\Institution;
use App\Models\SubCategory;
use Illuminate\Support\Facades\Auth;

class InstitutionController extends Controller
{

    const INSTITUTIONS_BLADE = 'src/institutions';
    /**
     * 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()
    {
        $institutions = Institution::all();
        $subcategories = SubCategory::all();
        return view(InstitutionController::INSTITUTIONS_BLADE,
        ['institutions' => $institutions, 'subcategories' => $subcategories,
         'selectedInstitution' => null]);
    }

    public function save(Request $request){

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

        $data['created_by'] = Auth::user()->user_id;
        $data['description'] = $request->description;
    
        $selected = $request->selected_institution;
    
        if($selected){
            $institution = tap(Institution::where('institution_id', 
            $selected)->update($data));
        }else {
            $institution = tap(new Institution($data))->save();
        }
        return redirect('/institutions');
    }

    public function search(Request $request){

        $keyword = $request->keyword;
        $institutions = DB::select(Db::raw("select * from institution inner join sub_category  
            on sub_category.sub_category_id = institution.sub_category_id where institution_name
             like '%".$keyword."%' or sub_category_name like '%".$keyword."%'"));
        return json_encode($institutions);
    }

    public function edit($id) {
        
        $institutionId = $id;
        $selectedInstitution = Institution::find($institutionId);
        $institutions = Institution::all();
        $subcategories = SubCategory::all();
        return view(InstitutionController::INSTITUTIONS_BLADE, 
        ['institutions' => $institutions, 'subcategories' => $subcategories,
        'selectedInstitution' => $selectedInstitution]);
    }

    public function del(Request $request) {

        $institutionId = $request->deleteinstitution;
        $institution = Institution::find($institutionId);
        $institution->delete();
        $institutions = Institution::all();
        $subcategories = SubCategory::all();
        return view(InstitutionController::INSTITUTIONS_BLADE, 
        ['institutions' => $institutions, 'subcategories' => $subcategories, 
        'selectedInstitution' => null]);
    }
}