<?php

namespace App\Http\Controllers;

use App\Models\Meja;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use Carbon\Carbon;

class MejaController extends Controller
{
    public function index()
    {
        $mejas = Meja::where('status', 'tersedia')->get();
        return view('meja', compact('mejas'));
    }

    public function selectMeja(Request $request)
    {
        try {
            $request->validate([
                'meja_id' => 'required|exists:meja,id'
            ], [
                'meja_id.required' => 'Silakan pilih meja terlebih dahulu',
                'meja_id.exists' => 'Meja yang dipilih tidak valid'
            ]);
            
            $meja = Meja::findOrFail($request->meja_id);
            
            // Check if table is available
            if ($meja->status !== 'tersedia') {
                return back()->with('error', 'Meja tidak tersedia.');
            }
            
            // Store selected meja in session
            session(['selected_meja' => $meja->id]);
            
            return redirect()->route('reservasi.index');

        } catch (\Exception $e) {
            Log::error('Error in MejaController@selectMeja: ' . $e->getMessage());
            return back()->with('error', 'Terjadi kesalahan. Silakan coba lagi.');
        }
    }

    public function checkAvailability(Request $request, $id)
    {
        try {
            $request->validate([
                'date' => 'required|date|after_or_equal:today'
            ]);

            $meja = Meja::findOrFail($id);
            $date = $request->date;

            // Get available time slots for the date
            $slots = $meja->getAvailableTimeSlots($date);
            
            // Filter out past slots if date is today
            if ($date === date('Y-m-d')) {
                $currentTime = Carbon::now();
                $slots = array_filter($slots, function($slot) use ($currentTime) {
                    return Carbon::parse($slot)->gt($currentTime);
                });
            }

            if (empty($slots)) {
                return response()->json([
                    'available' => false,
                    'slots' => [],
                    'message' => 'Tidak ada slot waktu tersedia untuk tanggal ini'
                ]);
            }

            return response()->json([
                'available' => true,
                'slots' => $slots,
                'message' => 'Slot waktu tersedia'
            ]);

        } catch (\Exception $e) {
            Log::error('Error checking meja availability: ' . $e->getMessage());
            return response()->json([
                'error' => 'Terjadi kesalahan saat memeriksa ketersediaan meja.'
            ], 500);
        }
    }

    public function getNextAvailableDates(Request $request)
    {
        try {
            $request->validate([
                'current_date' => 'required|date'
            ]);

            $currentDate = Carbon::parse($request->current_date);
            $availableDates = [];
            $daysToCheck = 30; // Check next 30 days
            
            // Get all mejas
            $mejas = Meja::all();
            
            // Check each day for the next 30 days
            for ($i = 1; $i <= $daysToCheck; $i++) {
                $checkDate = $currentDate->copy()->addDays($i);
                
                // Check if any meja has available slots on this date
                foreach ($mejas as $meja) {
                    if ($meja->hasAvailableSlotsForDate($checkDate->format('Y-m-d'))) {
                        $availableDates[] = $checkDate->format('Y-m-d');
                        break; // Found an available meja for this date, move to next date
                    }
                }
                
                // Limit to first 5 available dates
                if (count($availableDates) >= 5) {
                    break;
                }
            }

            return response()->json([
                'dates' => $availableDates
            ]);

        } catch (\Exception $e) {
            Log::error('Error getting next available dates: ' . $e->getMessage());
            return response()->json([
                'error' => 'Terjadi kesalahan saat mencari tanggal tersedia.'
            ], 500);
        }
    }

    public function updateStatus(Request $request, $id)
    {
        $request->validate([
            'status' => ['required', Rule::in(['tersedia', 'tidak_tersedia'])]
        ]);

        $meja = Meja::findOrFail($id);
        $meja->status = $request->status;
        $meja->save();

        return response()->json([
            'message' => 'Status meja berhasil diperbarui'
        ]);
    }
}
