<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Models\User; // Import the User model
use App\Models\Order; // Import the Order model
use App\Models\OrderItem; // Import the OrderItem model
use App\Models\Service; // Import the Service model
use App\Models\SchoolService; // Import the SchoolService model
use App\Models\ServiceBookingDetail;
use App\Models\SchoolServiceBookingDetail;
use App\Models\Booking;
use App\Http\Requests\DoctorStoreRequest; // Import the DoctorStoreRequest
use Illuminate\Support\Facades\Hash; // Import Hash for password hashing

class DoctorController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $doctors = User::where('role', 200)
            ->with(['orders.orderItems.item']) // Eager load orders, order items, and their polymorphic items
            ->latest()
            ->paginate(10);

        // Aggregate analytics data for each doctor
        $doctors->getCollection()->transform(function ($doctor) {
            $bookedServicesCount = 0;
            $bookedSchoolServicesCount = 0;

            foreach ($doctor->orders as $order) {
                foreach ($order->orderItems as $orderItem) {
                    if ($orderItem->item_type === Service::class) {
                        $bookedServicesCount++;
                    } elseif ($orderItem->item_type === SchoolService::class) {
                        $bookedSchoolServicesCount++;
                    }
                }
            }

            $doctor->booked_services_count = $bookedServicesCount;
            $doctor->booked_school_services_count = $bookedSchoolServicesCount;

            return $doctor;
        });

        return Inertia::render('Admin/Doctors/Index', [
            'doctors' => $doctors,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return Inertia::render('Admin/Doctors/Create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(DoctorStoreRequest $request)
    {
        $validated = $request->validated();

        User::create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => Hash::make($validated['password']),
            'mobile_number' => $validated['mobile_number'] ?? null,
            'role' => 200, // Set role to 200 for doctors
        ]);

        return redirect()->route('admin.doctors.index')->with('success', 'Doctor created successfully.');
    }

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

    public function assignedBookings()
    {
        $doctor = auth()->user();

        // Fetch ServiceBookingDetail records
        $serviceBookingDetails = ServiceBookingDetail::where('doctor_id', $doctor->id)
            ->with(['booking.user', 'service'])
            ->get();

        // Fetch SchoolServiceBookingDetail records
        $schoolServiceBookingDetails = SchoolServiceBookingDetail::where('doctor_id', $doctor->id)
            ->with(['booking.user', 'schoolService'])
            ->get();

        // Fetch Booking records directly assigned to the doctor
        $directBookings = Booking::where('doctor_id', $doctor->id)
            ->with(['user', 'bookable'])
            ->get();

        // Combine all booking types into a single collection
        // We need to transform direct bookings to match the structure of booking details for consistent display
        $transformedDirectBookings = $directBookings->map(function ($booking) {
            return (object) [
                'id' => $booking->id,
                'booking_id' => $booking->id,
                'doctor_id' => $booking->doctor_id,
                'doctor_approval_status' => $booking->status, // Assuming direct bookings status can be used here
                'booking' => $booking,
                'service' => $booking->bookable_type === 'App\\Models\\Service' ? $booking->bookable : null,
                'school_service' => $booking->bookable_type === 'App\\Models\\SchoolService' ? $booking->bookable : null,
                'created_at' => $booking->created_at,
                'updated_at' => $booking->updated_at,
            ];
        });

        $allBookings = $serviceBookingDetails
            ->concat($schoolServiceBookingDetails)
            ->concat($transformedDirectBookings)
            ->sortByDesc(function ($booking) {
                return $booking->created_at;
            });

        $perPage = 10;
        $page = request()->get('page', 1);
        $paginatedBookings = new \Illuminate\Pagination\LengthAwarePaginator(
            $allBookings->forPage($page, $perPage),
            $allBookings->count(),
            $perPage,
            $page,
            ['path' => request()->url()]
        );

        return Inertia::render('User/Doctors/AssignedBookings', [
            'serviceBookings' => $paginatedBookings,
        ]);
    }

    public function updateApprovalStatus(Request $request, Booking $booking)
    {
        $request->validate([
            'status' => 'required|string|in:approved,declined,completed',
        ]);

        $booking->serviceBookingDetail()->update([
            'doctor_approval_status' => $request->status,
        ]);

        return redirect()->route('user.doctors.assigned-bookings')->with('success', 'Booking status updated successfully.');
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}