<?php
/**
 * Created by PhpStorm.
 * User: stana
 * Date: 25.02.2017
 * Time: 19:24
 */

namespace App\Http\Controllers;


use App\Accommodation;
use App\AccommodationEquipment;
use App\Address;
use App\Image;
use App\Room;
use App\User;
use Illuminate\Http\Request;
use App\Equipment;
use Auth;
use Illuminate\Support\Facades\Input;
use Validator;
use Illuminate\Validation\Rule;
use App\RoomType;
use App\Booked;
use App\Reservation;
use App\Http\Controllers;


class AccoAdministrationController extends Controller
{
    // SHOW ACCOMMODATION EDIT FORM
    public function showEditAcco()
    {
        // GET EQUIPMENT AND CONVERT TO ARRAY
        $equipment = Equipment::all();
        $equip_array = $equipment->toArray();

        // GET ACCOMMODATION
        $accommodation_id = User::where('user_id', '=', Auth::user()->user_id)->pluck('accommodation_id')->first();
        $accommodation = Accommodation::find($accommodation_id);

        // ACCOOMMODATION DOESNT EXISTS
        if($accommodation == null){
            flash('Nemáte vytvořeno ubytování. Vytvořte si jej teď!','danger');
            return redirect('new_acco');
        }

        // GET ACCOMMODATION EQUIPMENT AND ADDRESS
        $equip_checked = AccommodationEquipment::where('accommodation_id', '=', $accommodation->accommodation_id)->select('equipment_id')->get();
        $address = Address::find($accommodation->address_id);

        // PREPARES FOR CHECKBOXES IN VIEW
        $all_data = array();
        foreach ($equip_checked as $equip){
            $all_data[] = $equip->equipment_id;
        }

        return view('edit_acco', ['equipment' => $equipment, 'accommodation' => $accommodation, 'address' => $address, 'equip_checked' => $equip_checked, 'equip_array' => $equip_array, 'all_data' => $all_data] );
    }

    // ACTION EDIT ACCOMMODATION
    public function editAcco(Request $request)
    {
        // MESSAGES
        $messages = [
            'accommodation_name.required' => 'Vyplňte název ubytování',
            'accommodation_description.required' => 'Vyplňte popis ubytování',
            'town.required' => 'Zadejte název města nebo vesnice',
            'street_name.required' => 'Zadejte název ulice',
            'street_number.required' => 'Zadejte číslo domu',
            'street_number.integer' => 'Neplatné znaky, zadejte číslice',
            'website.unique' => 'Na tuto stránku se již odkazuje jiné ubytování',
            'website.max' => 'Adresa je příliš dlouhá',
            'website.regex' => 'Adresa nesplňuje formu',
            'website.required' => 'Zadejte webovou adresu',
            'image.max' => 'Zadejte obrázek s maximální velikostí 1 MB',
            'image.mimes' => 'Zadejte pouze obrázky ve formátu PNG nebo JPEG',
            'accommodation_phone_number.required' => 'Zadejte kontaktní telefonní číslo na ubytovní',
            'accommodation_phone_number.regex' => 'Telefonní číslo není ve správném formátu: (+ 420) XXX XXX XXX',
            'accommodation_email.unique' => 'Zadaný e-mail již existuje v systému',
            'accommodation_email.required' => 'Zadejte kontaktní e-mail na ubytování',
            'accommodation_email.email' => 'Zadejte e-mail ve správném tvaru'
        ];

        // GET ACCOMMODATION
        $accommodation = Accommodation::find($request->accommodation_id);

        // VALIDATION
        $validator = Validator::make($request->all(), [
            'accommodation_name' => 'required|max:100',
            'accommodation_description' => 'required|max:255',
            'town' => 'required|max:45',
            'street_name' => 'required|max:45',
            'street_number' => 'required|integer|max:100000',
            'image' => 'max:1000|mimes:jpeg,jpg,png',
            'website' => 'unique:accommodations,website,'.$accommodation->accommodation_id.',accommodation_id|required|max:100|regex:/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/',Rule::unique('accommodations')->ignore($accommodation->accommodation_id, 'accommodation_id'),
            'accommodation_email' => 'required|email|max:255|unique:accommodations,accommodation_email,'.$accommodation->accommodation_id.',accommodation_id',
            'accommodation_phone_number' => 'required|regex:/^(\+420)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/',
        ], $messages);

        // IN CASE OF WRONG INPUT
        if ($validator->fails()) {
            return redirect('edit_acco')->withErrors($validator)->withInput();
        }

        // DELETE IMAGE
        if($request->delete_img == 1){
            $image = Image::find($accommodation->image_id);

            $accommodation->image_id = null;
            $accommodation->save();

            // DELETE IF IMAGE EXISTS
//echo dd($image);
            if($image <> null){ //echo dd($image->image_id);
                $image->delete();
            }
            // ELSE SAVE IMAGE
        }elseif($request->image <> null){
            $image = Image::find($accommodation->image_id);
            // SAVE NEW IMAGE
            if($image == null){
                $new_image = new Image([
                    'image' => file_get_contents($request->file('image'))

                ]);
                $new_image->save();
                $accommodation->image_id = $new_image->image_id;
                // UPDATE IMAGE
            }else{
                $image->image = file_get_contents($request->file('image'));
                $image->save();
            }
        }

        // CREATE ADDRESS TO ACCOMMODATION
        $address = Address::find($accommodation->address_id);
        $address->town = $request->town;
        $address->street_name = $request->street_name;
        $address->street_number = $request->street_number;
        $address->save();

        // UPDATE  ACCOMMODATION
        $accommodation->accommodation_name = $request->accommodation_name;
        $accommodation->accommodation_description = $request->accommodation_description;
        $accommodation->website = $request->website;
        $accommodation->accommodation_email = $request->accommodation_email;
        $accommodation->accommodation_phone_number = $request->accommodation_phone_number;
        $accommodation->save();

        // DELETE OLD SELECTED EQUIPMENT IN ACCOMMODATION
        AccommodationEquipment::where('accommodation_id', '=', $request->accommodation_id)->delete();

        // GET AND SAVE NEW EQUIPMENT IN ACCOMMODATION
        $equip = Input::get('equip');

        if($equip != null){
            foreach ($equip as $item) {
                $accoequip = new AccommodationEquipment([
                    'accommodation_id' => $accommodation->accommodation_id,
                    'equipment_id' => $item
                ]);
                $accoequip->save();
            }
        }

        flash('Ubytování bylo aktualizováno', 'success');
        return redirect('edit_acco');
    }

    // SHOW ALL ROOMS IN ACCOMMODATION
    public function showEditRooms()
    {
        $accommodation_id = User::where('user_id', '=', Auth::user()->user_id)->pluck('accommodation_id')->first();
        $accommodation = Accommodation::find($accommodation_id);

        // ACCO NOT EXISTS
        if($accommodation == null){
            flash('Prvně vytvořte ubytování', 'danger');
            return redirect('new_acco');
        }

        $rooms = Room::where('accommodation_id', '=', $accommodation->accommodation_id)->orderBy('room_name')->get();

        foreach ($rooms as $room) {
            $room->room_type = RoomType::where('room_type_id', '=', $room->room_type_id)->pluck('room_type_name')->first();
        }

        /* IF ACCO HAS NOT ROOMS, INFORM USER */
        $acco_rooms = Room::where('accommodation_id', '=', $accommodation->accommodation_id)->first();
        if ($acco_rooms == null) {
            flash('Vaše ubytování neobsahuje žádné pokoje! Vytvořte je nyní', 'danger');
        }
        return view('edit_rooms', ['rooms' => $rooms]);
    }

    // SHOW EDIT ROOM FORM */
    public function showEditRoom($room_id)
    {
        $room = Room::where('room_id', '=', $room_id)->first();
        return view('edit_room', ['room' => $room]);
    }

    // EDIT ROOM FORM
    public function editRoom(Request $request)
    {
        $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(url('edit_room/' . $request->room_id))->withErrors($validator)->withInput();
        }

        // GET ID's
        $room_type_id = RoomType::where('room_type_name', $request->select)->pluck('room_type_id');
        $room = Room::find($request->room_id);

        if($request->delete_img == 1){
            $image = Image::find($room->image_id);

            $room->image_id = null;
            $room->save();

            if($image != null){
                $image->delete();
            }
        }elseif($request->image != null){
            $image = Image::find($room->image_id);
            if($image == null){
                $new_image = new Image([
                    'image' => file_get_contents($request->file('image'))
                ]);
                $new_image->save();
                $room->image_id = $new_image->image_id;
            }else{
                $image->image = file_get_contents($request->file('image'));
                $image->save();
            }
        }

        // UPDATE ROOM
        $room->room_name = $request->room_name;
        $room->beds = $request->beds;
        $room->price = $request->price;
        $room->room_type_id = $room_type_id[0];
        $room->save();

        flash('Pokoj byl upraven', 'success');
        return redirect('edit_rooms');
    }

    // DELETE ROOM
    public function deleteRoom(Request $request)
    {
        $room = Room::find($request->room_id);
        $acco_id = $room->accommodation_id;

        $booked = Booked::where('room_id','=',$room->room_id)->get();
        // DELETE BOOKED
        foreach ($booked as $item) {
            $item->delete();
        }

        $reservations = Reservation::where('room_id','=',$room->room_id)->get();
        foreach ($reservations as $reservation) {
            $customer = Customer::where('customer_id','=',$reservation->customer_id)->get();
            $reservation->delete();
            $customer->delete();
        }

        $image = Image::find($room->image_id);
        if($image != null){
            $image->delete();
        }

        $room->delete();

        flash('Místnost byla úspěšně smazána', 'success');
        $acco_rooms = Room::where('accommmodation_id', '=', $acco_id);

        if ($acco_rooms == null) {
            flash('Vaše ubytování neobsahuje žádné pokoje! Vytvořte je nyní');
        }
        return redirect('edit_rooms');
    }
}