<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\LogActivityHelper;
use App\Http\Controllers\Controller;
use App\Models\Amenity;
use App\Models\Amenty;
use App\Models\AmentyAccess;
use App\Models\ApartmentType;
use App\Models\Building;
use App\Models\CloseAmenity;
use App\Models\ManageAmenity;
use App\Models\Media;
use App\Models\Setting;
use App\Models\TimeSlotAmenity;
use Carbon\CarbonPeriod;
use DateTime;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;

class AmenitiesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $setting = Setting::first();
        if($setting->amenities == 1){
            $items = Amenty::orderBy('id', 'DESC')->get();
            return view('admin.amenities.index',compact('items'));
        }else{
            return back();
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $setting = Setting::first();
        if($setting->amenities == 1){
            $building = Building::get();
            $apart_type = ApartmentType::get();
            return view('admin.amenities.create',compact('building','apart_type'));
        }
        else{
            return back();
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|min:3',
            'short_description' => 'required|max:70',
            'long_description' => 'required',
            'building_id' => 'required',
            'apartment_type_id' => 'required',
        ]);
        try{
            DB::beginTransaction();
            $amenty = new Amenty();
            $amenty->name = ucfirst($request->name);
            $amenty->short_description = $request->short_description;
            $amenty->long_description = $request->long_description;
            $amenty->image_position = $request->image_position;
            $amenty->booking = $request->booking;
            if($request->hasFile('image')) {
                if (!empty($request->image)) {
                    $qfile = $request->image;
                    $name = $qfile->getClientOriginalName();
                    if (File::exists(public_path('Media/' . $name))) {
                        return redirect()->back()->with('error', 'Media File is already exist');
                    }
                    $type = $qfile->getClientOriginalExtension();
                    $size = $qfile->getSize();
                    $path = $qfile->move(public_path() . '/Media/', $name);
                    $storage = 'Public';
                }
                $media = new Media();
                $media->media_group_id = 2;
                $media->title = 'Image';
                $media->name = $name;
                $media->type = $type;
                $media->size = $size;
                $media->source = $path;
                $storage = $storage;
                $media->save();

                $amenty->media_id = $media->id;
            }
            $amenty->save();

            $building_id = $request->building_id;
            $apartment_type_id = $request->apartment_type_id;
            if(!empty($building_id) > 0 || !empty($apartment_type_id) > 0){
                if(count($building_id) > count($apartment_type_id) || count($building_id) == count($apartment_type_id)){
                    foreach($building_id as $type){
                        foreach($apartment_type_id as $apart_type){
                            $access = new AmentyAccess();
                            $access->amenity_id = $amenty->id;
                            $access->building_id = $type;
                            $access->apartment_type_id = $apart_type;
                            $access->save();
                        }
                    }  
                }
                elseif(count($apartment_type_id) > count($building_id)){
                    foreach($apartment_type_id as $apart_type){
                        foreach($building_id as $type){
                            $access = new AmentyAccess();
                            $access->amenity_id = $amenty->id;
                            $access->apartment_type_id = $apart_type;
                            $access->building_id = $type;
                            $access->save();
                        }
                    }
                }
            }
            DB::commit();
            LogActivityHelper::addToLog('Add Amenity');
            return redirect()->route('amenities.index')->with('success', 'Amenity Created Successfully');
        } catch (\Exception $ex) {
            DB::rollback();
            return redirect()->back()->with('error','Error occured' . $ex->getMessage());
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function manage($id)
    {
        $id = decrypt($id);
        $amenty = Amenty::find($id); 
        $days_array = array('Monday','Tuesday', 'Wednesday','Thursday','Friday','Saturday','Sunday');
        $start = new DateTime('4:00');
        $end = new DateTime('24:00');
        while($start<$end){
            $time[] = $start->format('H:i');
            $start->modify('+5 minutes');
        }
        $close = CloseAmenity::where('amenity_id',$amenty->id)->get(); 
        // dd($amenty->close_amenity);       
        return view('admin.amenities.manage',compact('amenty','days_array','time','close'));
    }
    //manage store opening hours
    public function manage_store(Request $request,$id)
    {
        $id = decrypt($id);
        try{
            DB::beginTransaction();
            $id_exist = ManageAmenity::where('amenity_id',$id)->count();
            if($id_exist > 0){
                $amenty = ManageAmenity::where('amenity_id',$id)->delete();
                $ids = ManageAmenity::where('amenity_id',$id)->pluck('id');
                $add = $request->add;
                if($add != null){
                    foreach ($add as $key => $value) {  
                        if(count($value) > 4 == true){
                            $amenty = new ManageAmenity();
                            $amenty->amenity_id = $id;
                            $amenty->day = $value['day'];
                            $amenty->open = $value['open'];
                            $amenty->close = $value['close'];
                            $amenty->open1 = $value['open1'];
                            $amenty->close1 = $value['close1'];
                            $amenty->save();
                        }
                    }
                }
                if($request->min_booking_length != "" && $request->max_booking_length != "" && $request->max_residents != ""){
                    $time = TimeSlotAmenity::where('amenity_id',$id)->first();
                    $amenty->amenity_id = $id;
                    $time->block_length = $request->block_length;
                    $time->max_booking_time = $request->max_booking_length;
                    $time->min_booking_time = $request->min_booking_length;
                    $time->no_of_residence = $request->max_residents;
                    $time->save();
                }
            }else{
                $add = $request->add;
                if($add != null){
                    foreach ($add as $key => $value) {  
                        if(count($value) > 4 == true){
                            $amenty = new ManageAmenity();
                            $amenty->amenity_id = $id;
                            $amenty->day = $value['day'];
                            $amenty->open = $value['open'];
                            $amenty->close = $value['close'];
                            $amenty->open1 = $value['open1'];
                            $amenty->close1 = $value['close1'];
                            $amenty->save();
                        }
                    }
                }
                if($request->min_booking_length != "" && $request->max_booking_length != "" && $request->max_residents != ""){
                    $time = new TimeSlotAmenity();
                    $time->amenity_id = $id;
                    $time->block_length = $request->block_length;
                    $time->max_booking_time = $request->max_booking_length;
                    $time->min_booking_time = $request->min_booking_length;
                    $time->no_of_residence = $request->max_residents;
                    $time->save();
                }
            }
            DB::commit();
            LogActivityHelper::addToLog('Opening Hours For Amenity');
            return redirect()->back()->with('success', 'Opening Hours For Amenity Successfully Done');
        } catch (\Exception $ex) {
            DB::rollback();
            return redirect()->back()->with('error','Error occured' . $ex->getMessage());
        }
    }
    // manage booking page
    public function manage_booking(Request $request,$id)
    {
        $setting = Setting::first();
        if($setting->amenities == 1){
            $id = decrypt($id);
            $amenty = Amenty::find($id);
            $days_array = array('Monday','Tuesday', 'Wednesday','Thursday','Friday','Saturday','Sunday');
            $start = new DateTime('4:00');
            $end = new DateTime('24:00');
            while($start<$end){
                $time[] = $start->format('H:i');
                $start->modify('+5 minutes');
            }
            
            $count = 20;
            $block_length = 10;
            $startTime = 10;
            $cutTime = 180;
            $counter = 0;
            while($startTime <= $cutTime){

                $counter = $counter + 1;
            
                $hours = floor($startTime / 60);
                $minutes = ($startTime % 60);
                if(intval($hours) >= 1){

                    if($minutes >= 1){

                        $booking_time_slot[$startTime] = intval($hours).' hours '.$minutes.' minutes';

                    }else{

                        $booking_time_slot[$startTime] = intval($hours).' hours ';
                    }
                    
                }else{

                    $booking_time_slot[$startTime] = $minutes.' minutes';
                }
                if($counter == 1){
                    $startTime = $startTime + 5;
                }elseif($counter  >= 5){
                    $startTime = $startTime + 30;
                }else{
                    $startTime = $startTime + 15;
                }
            }

            $min_booking_block_length = 10;
            $min_booking_startTime = 10;
            $min_booking_cutTime = 180;
            $min_booking_counter = 0;
            while($min_booking_startTime <= $min_booking_cutTime){

                $min_booking_counter = $min_booking_counter + 1;
                $min_booking_hours = floor($min_booking_startTime / 60);
                $min_booking_minutes = ($min_booking_startTime % 60);
                if(intval($min_booking_hours) >= 1){

                    if($min_booking_minutes >= 1){

                        $min_booking_time_slot[$min_booking_startTime] = intval($min_booking_hours).' hours '.$min_booking_minutes.' minutes';

                    }else{

                        $min_booking_time_slot[$min_booking_startTime] = intval($min_booking_hours).' hours ';
                    }
                    
                }else{

                    $min_booking_time_slot[$min_booking_startTime] = $min_booking_minutes.' minutes';
                }

                // $min_booking_startTime = $min_booking_startTime + $min_booking_block_length;
                if($min_booking_counter >= 1 && $min_booking_counter <=2){

                    $min_booking_startTime = $min_booking_startTime + 5;

                }elseif( ($min_booking_counter  >= 3 && $min_booking_counter <=5 ) || ($min_booking_counter  >= 7 && $min_booking_counter <=13)){

                    $min_booking_startTime = $min_booking_startTime + 10;

                }else {

                    $min_booking_startTime = $min_booking_startTime + 30;
                }
            }
            $max_booking_block_length = 10;
            $max_booking_startTime = 10;
            $max_booking_cutTime = 600;
          
            while($max_booking_startTime <= $max_booking_cutTime){

            
                $max_booking_hours = floor($max_booking_startTime / 60);
                $max_booking_minutes = ($max_booking_startTime % 60);
                if(intval($max_booking_hours) >= 1){

                    if($max_booking_minutes >= 1){

                        $max_booking_time_slot[$max_booking_startTime] = intval($max_booking_hours).' hours '.$max_booking_minutes.' minutes';

                    }else{

                        $max_booking_time_slot[$max_booking_startTime] = intval($max_booking_hours).' hours ';
                    }
                    
                }else{

                    $max_booking_time_slot[$max_booking_startTime] = $max_booking_minutes.' minutes';
                }
                $max_booking_startTime = $max_booking_startTime + $max_booking_block_length;
            }
            $slot = TimeSlotAmenity::where('amenity_id',$id)->first();
            $closed = CloseAmenity::where('amenity_id',$id)->get();
            // dd($close);
            return view('admin.amenities.manage-booking',compact('amenty','closed','slot','max_booking_time_slot','min_booking_time_slot','booking_time_slot','days_array','time','count'));
        }else{
            return back();
        }
    }
    //close
    public function close_store(Request $request,$id)
    {
        try{
            DB::beginTransaction();
            $id = decrypt($id);
            if($request->datetype == 'datetype_single'){
                $amenty = new CloseAmenity();
                $amenty->amenity_id = $id;
                $amenty->datetype = $request->datetype;
                $amenty->single_date = date('Y-m-d',strtotime($request->closed_date));
                $amenty->save();
            }else if($request->datetype == 'datetype_range'){
                $period = CarbonPeriod::create($request->first_date, $request->last_date);
                foreach ($period as $date){
                    $amenty = new CloseAmenity();
                    $amenty->amenity_id = $id;
                    $amenty->datetype = $request->datetype;
                    $amenty->first_date = $request->first_date;
                    $amenty->last_date = $request->last_date;
                    $amenty->date_range = $date->format('Y-m-d');
                    $amenty->save();
                }
            }
            DB::commit();
            LogActivityHelper::addToLog('Closed Day For Amenity');
            return redirect()->back()->with('success', 'Closed Day For Amenity Successfully Done');
        } catch (\Exception $ex) {
            DB::rollback();
            return redirect()->back()->with('error','Error occured' . $ex->getMessage());
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $setting = Setting::first();
        if($setting->amenities == 1){
            $id = decrypt($id);
            $amenty = Amenty::find($id);
            $building = Building::get();
            $apart_type = ApartmentType::get();
            $access_buil = AmentyAccess::where('amenity_id',$id)->pluck('building_id')->all(); 
            $access_type = AmentyAccess::where('amenity_id',$id)->pluck('apartment_type_id')->all();
            return view('admin.amenities.edit',compact('amenty','building','apart_type','access_buil','access_type'));
        }else{
            return back();
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validated = $request->validate([
            'name' => 'required|min:3',
            'short_description' => 'required|max:70',
            'long_description' => 'required',
            'building_id' => 'required',
            'apartment_type_id' => 'required',
        ]);
        try{
            DB::beginTransaction();
            $amenty = Amenty::find($id);
            $amenty->name = ucfirst($request->name);
            $amenty->short_description = $request->short_description;
            $amenty->long_description = $request->long_description;
            $amenty->image_position = $request->image_position;
            $amenty->booking = $request->booking;
            $media = Media::find($amenty->media_id);
            if($media != null){
                if($request->hasFile('image')) {
                    if (!empty($request->image)) {
                        $qfile = $request->image;
                        $name = $qfile->getClientOriginalName();
                        if (File::exists(public_path('Media/' . $name))) {
                            return redirect()->back()->with('error', 'Media File is already exist');
                        }
                        $file_path = public_path() . '/Media/' . $media->name;
                        unlink($file_path);
                        $type = $qfile->getClientOriginalExtension();
                        $size = $qfile->getSize();
                        $path = $qfile->move(public_path() . '/Media/', $name);
                        $storage = 'Public'; 
                    }
                    $media->media_group_id = 2;
                    $media->title = 'Image';
                    $media->name = $name;
                    $media->type = $type;
                    $media->size = $size;
                    $media->source = $path;
                    $storage = $storage;
                    $media->save();
                }
                $name = $media->name;
                $type = $media->type;
                $size = $media->size;
                $path = $media->path;
                $storage = $media->storage;
                $amenty->media_id = $media->id;
            }
            else{
                if($request->hasFile('image')) {
                    if (!empty($request->image)) {
                        $qfile = $request->image;
                        $name = $qfile->getClientOriginalName();
                        if (File::exists(public_path('Media/' . $name))) {
                            return redirect()->back()->with('error', 'Media File is already exist');
                        }
                        $type = $qfile->getClientOriginalExtension();
                        $size = $qfile->getSize();
                        $path = $qfile->move(public_path() . '/Media/', $name);
                        $storage = 'Public';
                    }
                    $media = new Media();
                    $media->media_group_id = 2;
                    $media->title = 'Image';
                    $media->name = $name;
                    $media->type = $type;
                    $media->size = $size;
                    $media->source = $path;
                    $storage = $storage;
                    $media->save();
    
                    $amenty->media_id = $media->id;
                }
            }
            $amenty->save();

            $building_id = $request->building_id;
            $apartment_type_id = $request->apartment_type_id;
            $exist = AmentyAccess::where('amenity_id',$id)->count();
            if(!empty($building_id) > 0 || !empty($apartment_type_id) > 0){
                if(count($building_id) > count($apartment_type_id) || count($building_id) == count($apartment_type_id)){
                    $remove = AmentyAccess::where('amenity_id',$id)->delete();
                    foreach($building_id as $type){
                        foreach($apartment_type_id as $apart_type){
                            $access = new AmentyAccess();
                            $access->amenity_id = $amenty->id;
                            $access->building_id = $type;
                            $access->apartment_type_id = $apart_type;
                            $access->save();
                        }
                    }
                }
                elseif(count($apartment_type_id) > count($building_id)){
                    $remove = AmentyAccess::where('amenity_id',$id)->delete();
                    foreach($apartment_type_id as $apart_type){
                        foreach($building_id as $type){
                            $access = new AmentyAccess();
                            $access->amenity_id = $amenty->id;
                            $access->apartment_type_id = $apart_type;
                            $access->building_id = $type;
                            $access->save();
                        }
                    }
                }
            }
            DB::commit();
            LogActivityHelper::addToLog('Update Amenity');
            return redirect()->route('amenities.index')->with('success', 'Amenity Updated Successfully');
        } catch (\Exception $ex) {
            DB::rollback();
            return redirect()->back()->with('error','Error occured' . $ex->getMessage());
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        try {
            DB::beginTransaction();
            AmentyAccess::where('amenity_id',$id)->delete();
            $amenty = Amenty::find($id);
            $media = Media::find($amenty->media_id);
            if (File::exists(public_path('Media/' . $media->name))) {
                $file_path = public_path() . '/Media/' . $media->name;
                if ($file_path) {
                    unlink($file_path);
                    $media->delete();
                    $amenty->delete();
                }
            }else{
                $amenty->delete();
            }
            DB::commit();
            LogActivityHelper::addToLog('Delete Amenity');
            return redirect()->route('amenities.index')->with('success', 'Amenity Delete Successfully');;
        } catch (\Exception $ex) {
            DB::rollback();
        }
        return redirect()->back()->with('error','Error occured' . $ex->getMessage());
    }
     /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function close_destroy($id)
    {
        try {
            DB::beginTransaction();
            $amenty = CloseAmenity::find($id);
            $amenty->delete();
            DB::commit();
            LogActivityHelper::addToLog('Delete Close Date');
            return redirect()->route('amenities.index')->with('success', 'Close Date Delete Successfully');;
        } catch (\Exception $ex) {
            DB::rollback();
        }
        return redirect()->back()->with('error','Error occured' . $ex->getMessage());

    }
}
