<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Facility;
use App\Room;
use App\Roomfacility;

class RoomfacilityController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }
    
    public function getViewByGrid(){
    
        $facilities = Facility::where('active', '=', 1) -> get();
        foreach ($facilities as $facility) {
            $facility_ids[] = $facility -> id;
        }

        $rooms = Room::orderBy('id', 'ASC') -> where('active','=', 1) ->get();
        
        foreach ($rooms as $room) {
            if(!empty($facility_ids)){
                foreach ($facility_ids as $fid) {
                    $roomfacility = Roomfacility::where('facility_id','=',$fid)->where('room_id','=',$room->id)->first();
                    if ($roomfacility) {
                        $matrix[$room->id][$fid] = $roomfacility;
                    } else {
                        $matrix[$room->id][$fid] = null;
                    }
                }
            }else{
                $matrix = null;
            }
        }

        return view('roomfacilities.viewbygrid')
            -> with('title', 'Room Facilities')
            -> with('facilities', $facilities)
            -> with('rooms', $rooms)
            -> with('matrix', $matrix);
    }
    public function getActiveAjax(Request $request){

        $room_id = $request -> roomId; 
        $facility_id = $request -> facilityId;  
        $checked = $request -> checked;
        
        $room = Room::find($room_id);
    
        if ($room) {
            $roomfacility = Roomfacility::where('room_id','=',$room_id)->where('facility_id','=',$facility_id)->first();        
            if (!$roomfacility) {
                $roomfacility = new Roomfacility();
                $roomfacility -> facility_id = $facility_id; 
                $roomfacility -> room_id = $room_id;    
                $roomfacility -> active = true;            
            } else {
                $roomfacility -> active = ($checked == 'true') ? true : false;    
            }

            $roomfacility -> save();            
            $success = true;

        } else {
            $success = false;
            $roomfacility = null;
        }
    
        $response = array(
            'success' => $success,
            'roomfacility'=> $roomfacility
        );
    
        return response()->json($response);
    }

}
