<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Customer;
use App\Models\WaitingQueue;
use App\Models\AppointmentSetting;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use App\Models\ActivityLog;
use Carbon\Carbon;
use App\Events\QueueUpdated;

class AppointmentController extends Controller
{
    public function __construct()
    {
        $this->middleware("auth");
    }

    public function create()
    {
        $settings = AppointmentSetting::getSettings();
        $availableSlots = $settings->getAvailableTimeSlots();


        $customers = Customer::orderBy('created_at', 'desc')->get();


        return view("appointments.create", compact('settings', 'availableSlots','customers'));
    }

    public function store(Request $request)
    {
        $settings = AppointmentSetting::getSettings();

        $validator = Validator::make($request->all(), [
            "name" => "required|string|max:255",
            "phone" => "nullable|string|max:20",
            "appointment_date" => "required|date|after_or_equal:today",
            "appointment_time" => "required|date_format:H:i",
        ], [
            "name.required" => __('appointments.customer_name') . ' ' . __('validation.required'),
            "appointment_date.required" => __('appointments.appointment_date') . ' ' . __('validation.required'),
            "appointment_date.after_or_equal" => __('appointments.no_past_appointments'),
            "appointment_time.required" => __('appointments.appointment_time') . ' ' . __('validation.required'),
            "appointment_time.date_format" => __('appointments.invalid_time_format'),
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        // Check time slot availability
        if (!$settings->isTimeSlotAvailable($request->appointment_date, $request->appointment_time)) {
            return back()->withErrors(['appointment_time' => __('appointments.time_slot_taken')])->withInput();
        }

        if ($request->filled('customer_id')) {
            // تحديث الزبون
            $customer = Customer::find($request->customer_id);
        }
        else
        {
        $customer = Customer::create([
            "name" => $request->name,
            "phone" => $request->phone,
        ]);
        }

        $appointmentDateTime = Carbon::parse($request->appointment_date . ' ' . $request->appointment_time);

        WaitingQueue::create([
            "customer_id" => $customer->id,
            "type" => "appointment",
            "appointment_time" => $appointmentDateTime,
            "status" => "waiting",
            "position" => 0,
            "added_by" => Auth::id(),
        ]);

        ActivityLog::create([
            "user_id" => Auth::id(),
            "action" => "book_appointment",
            "description" => __('activity_log.appointment_booked', [
                'name' => $customer->name,
                'date' => $request->appointment_date,
                'time' => $request->appointment_time
            ]),
            "ip_address" => $request->ip(),
            "user_agent" => $request->userAgent(),
        ]);

         // Broadcast WebSocket update AFTER database changes are committed
        broadcast(new QueueUpdated(auth()->user()->tenant_id));

        return redirect()->route("dashboard")->with("success", __('appointments.appointment_booked'));
    }

    public function getAvailableSlots(Request $request)
    {
        $date = $request->input('date', now()->format('Y-m-d'));
        $settings = AppointmentSetting::getSettings();

        $allSlots = $settings->getAvailableTimeSlots($date);
        $availableSlots = [];

        foreach ($allSlots as $slot) {
            if ($settings->isTimeSlotAvailable($date, $slot)) {
                $availableSlots[] = $slot;
            }
        }

        return response()->json($availableSlots);
    }
}
