<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Models\SchoolService; // Import the SchoolService model
use App\Http\Requests\SchoolServiceStoreRequest; // Import the SchoolServiceStoreRequest
use App\Http\Requests\SchoolServiceUpdateRequest; // Import the SchoolServiceUpdateRequest
use Illuminate\Support\Str; // Import Str for UUID generation
use Illuminate\Support\Facades\Storage; // Import Storage for image deletion
use App\Models\User; // Import the User model

class SchoolController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $schoolServices = SchoolService::latest()->paginate(10);
        return Inertia::render('Admin/School/Index', [
            'schoolServices' => $schoolServices,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $doctors = User::where('role', 200)->get(); // Fetch users with role 200
        return Inertia::render('Admin/School/Create', [
            'doctors' => $doctors,
        ]);
    }

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

            $schoolService = new SchoolService();
            $schoolService->name = $validated['name'];
            $schoolService->description = $validated['description'] ?? null;
            $schoolService->type = $validated['type'] ?? null;
            $schoolService->price = $validated['price'];
            $schoolService->start_date = $validated['start_date'] ?? null;
            $schoolService->duration = $validated['duration'] ?? null;
            $schoolService->location = $validated['location'] ?? null;
            $schoolService->instructor_id = $validated['instructor_id'] ?? null;

            if ($request->hasFile('images')) {
                $imagePaths = [];
                $imageUrls = [];
                foreach ($request->file('images') as $image) {
                    $imagePath = $image->store('school', 'public');
                    $imagePaths[] = $imagePath;
                    $imageUrls[] = url($imagePath);
                }
                $schoolService->images = $imagePaths;
                $schoolService->image_urls = $imageUrls;
            }

            $schoolService->save();

            return redirect()->route('admin.school-services.index')->with('success', 'School service created successfully.');
        } catch (\Throwable $th) {
            dd($th);
        }
    }

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

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(SchoolService $schoolService)
    {
        $schoolService->load('instructor'); // Eager load the instructor relationship
        $doctors = User::where('role', 200)->get(); // Fetch users with role 200
        return Inertia::render('Admin/School/Edit', [
            'schoolService' => $schoolService,
            'doctors' => $doctors,
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(SchoolServiceUpdateRequest $request, SchoolService $schoolService)
    {
        $validated = $request->validated();
        $schoolService->name = $validated['name'];
                    $schoolService->description = $validated['description'] ?? null;
                    $schoolService->type = $validated['type'];
                    $schoolService->price = $validated['price'];        $schoolService->type = $validated['type'];
        $schoolService->start_date = $validated['start_date'] ?? null;
        $schoolService->duration = $validated['duration'] ?? null;
        $schoolService->location = $validated['location'] ?? null;
        $schoolService->instructor_id = $validated['instructor_id'] ?? null;

        if ($request->hasFile('images')) {
            // Delete old images
            if ($schoolService->images) {
                foreach ($schoolService->images as $oldImagePath) {
                    Storage::disk('public')->delete($oldImagePath);
                }
            }

            $imagePaths = [];
            $imageUrls = [];
            foreach ($request->file('images') as $image) {
                $imagePath = $image->store('school', 'public');
                $imagePaths[] = $imagePath;
                $imageUrls[] = url($imagePath);
            }
            $schoolService->images = $imagePaths;
            $schoolService->image_urls = $imageUrls;
        } elseif ($request->has('images_removed') && count($request->input('images_removed')) > 0) {
            // Handle removal of specific images
            $existingImages = $schoolService->images ?? [];
            $existingImageUrls = $schoolService->image_urls ?? [];
            $imagesToRemove = $request->input('images_removed');

            $newImages = [];
            $newImageUrls = [];

            foreach ($existingImages as $key => $imagePath) {
                if (!in_array($imagePath, $imagesToRemove)) {
                    $newImages[] = $imagePath;
                    $newImageUrls[] = url($existingImageUrls[$key]);
                } else {
                    Storage::disk('public')->delete($imagePath);
                }
            }
            $schoolService->images = $newImages;
            $schoolService->image_urls = $newImageUrls;
        } elseif ($request->has('images') && count($request->input('images')) === 0) {
            // If no new images are uploaded and all existing images are removed
            if ($schoolService->images) {
                foreach ($schoolService->images as $oldImagePath) {
                    Storage::disk('public')->delete($oldImagePath);
                }
            }
            $schoolService->images = [];
            $schoolService->image_urls = [];
        }

        $schoolService->save();

        return redirect()->route('admin.school-services.index')->with('success', 'School service updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(SchoolService $schoolService)
    {
        $schoolService->delete();
        return redirect()->route('admin.school-services.index')->with('success', 'School service deleted successfully.');
    }
}
