<?php
/**
 * Created by PhpStorm.
 * User: stana
 * Date: 20.02.2017
 * Time: 16:15
 */

namespace App\Http\Controllers;


use Illuminate\Http\Request;
use Validator;
use Auth;
use App\Accommodation;
use App;
use App\RoomType;
use App\User;

class NewRoomController extends Controller
{
    public function __construct()
    {
    }

    public function index(){
        $accommodation_id = User::where('user_id', '=', Auth::user()->user_id)->pluck('accommodation_id')->first();
        $accommodation = Accommodation::find($accommodation_id);

        return view('new_room', ['accommodation' => $accommodation]);
    }

    // SAVE NEW ROOM
    public function storeRoom(Request $request){
        // REWRITE MESSAGES
        $messages = [
            'room_name.required' => 'Vyplňte název pokoje',
            'beds.required' => 'Vyplňte počet lůžek na pokoji',
            'price.required' => 'Vyplňte cenu pokoje',
            'beds.integer' => 'Neplatné znaky, zadejte číslice',
            'price.integer' => 'Neplatné znaky, zadejte číslice',
            'image.max' => 'Zadejte obrázek s maximální velikostí 1 MB',
            'image.mimes' => 'Zadejte pouze obrázky ve formátu PNG nebo JPEG',
        ];

        // VALIDATE USER INPUT
        $validator = Validator::make($request->all(), [
            'room_name' => 'required|max:45',
            'beds' => 'required|max:255|integer',
            'price' => 'required|max:100000|integer',
            'image' => 'max:1000|mimes:jpeg,jpg,png',
        ],$messages);


        if ($validator->fails()) {
            return redirect('new_room')->withErrors($validator)->withInput();
        }

        // GET ID's
        $room_type_id = RoomType::where('room_type_name','=',$request->select)->pluck('room_type_id')->first();
        $accommodation_id = User::where('user_id', '=', Auth::user()->user_id)->pluck('accommodation_id')->first();

        // SAVE NEW ROOM
        $room = new App\Room([
            'room_name' => $request->room_name,
            'beds' => $request->beds,
            'price' => $request->price,
            'room_type_id' => $room_type_id,
            'accommodation_id' => $accommodation_id,
            'image_id' => null
        ]);

        if($request->image != null){
            $image = new App\Image([
                'image' => file_get_contents($request->file('image'))
            ]);
            $image->save();
            $room->image_id = $image->image_id;
        }

        $room->save();

        // REDIRECT TO NEW ROOM VIEW
        return redirect('edit_rooms');

    }
}