<?php

namespace App\Http\Controllers;

use App\Models\Booking;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\Mail;
use App\Mail\BookingNotification;
use App\Services\BeemService;

class BookingController extends Controller
{
    public function create()
    {
        return view('booking.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'customer_name' => 'required|string|max:255',
            'customer_phone' => 'required|string|max:20',
            'customer_address' => 'required|string',
            'preferred_date' => 'required|date|after_or_equal:today',
            'services' => 'required|array|min:1',
        ]);

        $date = Carbon::parse($request->preferred_date);
        if (!($date->isWeekend() || $this->isHoliday($date))) {
            return back()->withErrors(['preferred_date' => 'Services are only available on weekends and holidays.']);
        }

        $booking = Booking::create([
            'customer_name' => $request->customer_name,
            'customer_phone' => $request->customer_phone,
            'customer_address' => $request->customer_address,
            'preferred_date' => $request->preferred_date,
            'services' => json_encode($request->services),
        ]);

        // Send email
        Mail::to('alexchambika85@gmail.com')->send(new BookingNotification($booking));

        // Send SMS
        $sms = new BeemService();
        $sms->sendSms('255683222640', "Booking received from {$booking->customer_name} on {$booking->preferred_date}. Phone: {$booking->customer_phone}");

        return redirect()->back()->with('success', 'Booking submitted successfully!');
    }

    private function isHoliday($date)
    {
        $holidays = ['2025-01-01', '2025-12-25'];
        return in_array($date->toDateString(), $holidays);
    }
}
