<?php

namespace App\Http\Controllers\Masters;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use App\Http\Requests\Master\BookingSlotRequest;
use App\Models\BookingFor;
use App\Models\BookingSlot;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class BookingSlotController extends BaseController
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $services = BookingFor::get();
        // $bookingSlots = BookingSlot::with('bookingFor')->latest()->get()->groupBy('day');
        $datas = BookingSlot::with('bookingFor')
            ->latest()
            ->get()
            ->groupBy(function ($slot) {
                return $slot->booking_for_id;
            })
            ->map(function ($slotsByService) {
                return $slotsByService->groupBy('day');
            });
        // dd($datas);

        return view('admin.masters.booking_slot')->with(['datas' => $datas, 'services' => $services]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(BookingSlotRequest $request)
    {
        try {
            DB::beginTransaction();
            $input          = $request->validated();
            $day            = $input['day'];

            foreach ($input['time'] as $time) {

                BookingSlot::updateOrCreate(
                    [
                        'booking_for_id' => $input['booking_for_id'],
                        'day' => $day,
                        'time' => $time,
                    ],
                    [
                        'booking_for_id' => $input['booking_for_id'],
                        'day' => $day,
                        'time' => $time,
                        'price' => $input['price'],
                    ]
                );
            }

            DB::commit();

            return response()->json(['success' => 'Booking slot created successfully!']);
        } catch (\Exception $e) {
            return $this->respondWithAjax($e, 'creating', 'Booking slot');
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(BookingSlot $booking_slot)
    {
        $slots = BookingSlot::where('booking_for_id', $booking_slot->booking_for_id)
            ->where('day', $booking_slot->day)
            ->get();

        return response()->json([
            'service_id' => $booking_slot->booking_for_id,
            'price' => $booking_slot->price,
            'day' => $booking_slot->day,
            'slots' => $slots,
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(BookingSlotRequest $request, BookingSlot $booking_slot)
    {
        $validator = Validator::make($request->all(), [
            'booking_for_id' => 'required|integer|exists:booking_fors,id',
            'price' => 'required|numeric|min:0',
            'day' => 'required|string',
            'time' => 'required|array|min:1',
            'time.*' => 'string',
        ], [
            'booking_for_id.required' => 'Please select a service',
            'price.required' => 'Please enter a price',
            'day.required' => 'Please select day',
            'time.required' => 'Please select at least one time slot',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 400,
                'errors' => $validator->errors(),
            ]);
        }
        try {
            DB::beginTransaction();
            $input          = $request->validated();

            $input = $request->validated();

            $existingSlots = BookingSlot::where('booking_for_id', $input['booking_for_id'])
                ->where('day', $input['day'])
                ->pluck('time')
                ->toArray();

            $newTimes = $input['time'];

            foreach ($newTimes as $time) {
                $existing = BookingSlot::where('booking_for_id', $input['booking_for_id'])
                    ->where('day', $input['day'])
                    ->where('time', $time)
                    ->first();

                if ($existing) {
                    $existing->update([
                        'price' => $input['price'],
                        'updated_at' => now(),
                    ]);
                } else {
                    BookingSlot::create([
                        'booking_for_id' => $input['booking_for_id'],
                        'day' => $input['day'],
                        'time' => $time,
                        'price' => $input['price'],
                    ]);
                }
            }

            BookingSlot::where('booking_for_id', $input['booking_for_id'])
                ->where('day', $input['day'])
                ->whereNotIn('time', $newTimes)
                ->delete();

            DB::commit();

            return response()->json(['success' => 'Booking slot updated successfully!']);
        } catch (\Exception $e) {
            return $this->respondWithAjax($e, 'updating', 'Booking slot');
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(BookingSlot $booking_slot)
    {
        try {
            DB::beginTransaction();
            $booking_slot->delete();
            DB::commit();

            return response()->json(['success' => 'Booking slot deleted successfully!']);
        } catch (\Exception $e) {
            return $this->respondWithAjax($e, 'deleting', 'Booking slot');
        }
    }
}
