<?php 

namespace App\Http\Controllers;

use App\Models\Property;
use App\Models\Address;
use App\Models\Detail;
use App\Models\Amenity;
use App\Models\GalleryImage;
use App\Models\FloorPlan;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

use Illuminate\Http\Request;

class PropertyController extends Controller
{
    public function index()
    {
        $properties = Property::with(['address', 'detail', 'amenities'])->get();
        return view('backend.admin.properties.index', compact('properties'));
    }
    public function allProperties()
    {
        $properties = Property::with(['address', 'detail', 'amenities'])->get();
        return view('backend.admin.properties.allProperties_user', compact('properties'));
    }
    public function create()
    {
        return view('backend.admin.properties.create');
    }

    public function store(Request $request)
    {

        // Validate inputs
        $request->validate([
            'property_name' => 'required|string',
            'price' => 'required|numeric',
            'security_deposit' => 'nullable|numeric',
            'youtube_url' => 'nullable|url',
            'description' => 'nullable|string',
            'meta_title' => 'nullable|string',
            'meta_description' => 'nullable|string',
            'category_name' => 'required|string',
            'banner_img' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        // Check user permissions before allowing post
        $user = auth()->user();

        if (!$user->can_sell && !$user->can_lease && !$user->can_rent) {
            return back()->with('error', 'You do not have permission to post property.');
        }

        // Handle banner image upload
        // $bannerPath = null;
        // if ($request->hasFile('banner_img')) {
        //     $bannerPath = $request->file('banner_img')->store('banners', 'public');
        // }

        $bannerPath = null;
        if ($request->hasFile('banner_img')) {
            $image = $request->file('banner_img');
            $imageName = time() . '.' . $image->getClientOriginalExtension();
            $image->move(public_path('storage/banners'), $imageName);
            $bannerPath = 'storage/banners/' . $imageName;
        }

        // Create Property
        $property = Property::create([
            'property_name' => $request->property_name,
            'price' => $request->price,
            'security_deposit' => $request->security_deposit,
            'youtube_url' => $request->youtube_url,
            'description' => $request->description,
            'meta_title' => $request->meta_title,
            'meta_description' => $request->meta_description,
            'banner_img' => $bannerPath,
            'category_name' => $request->category_name,
            'user_id' => $user->id, // optional if needed
        ]);
        // Save Address
        if ($request->has('address')) {
            $property->address()->create($request->address);
        }

        // Save Details
        if ($request->has('details')) {
            $property->detail()->create($request->details);
        }

        // Save Amenities
        if ($request->has('amenities')) {
            $property->amenities()->create($request->amenities);
        }
        // ✅ Save Gallery Images here
        // if ($request->hasFile('gallery_images')) {
        //     foreach ($request->file('gallery_images') as $image) {
        //         $path = $image->store('gallery', 'public');
        //         $property->galleryImages()->create([
        //             'image_path' => $path
        //         ]);
        //     }
        // }
        $bannerPath = null;
        if ($request->hasFile('gallery_images')) {
            foreach ($request->file('gallery_images') as $image) {
                $imageName = time() . '_' . uniqid() . '.' . $image->getClientOriginalExtension();
                $image->move(public_path('storage/gallery'), $imageName);
                $galleryPath = 'storage/gallery/' . $imageName;
                $property->galleryImages()->create([
                    'image_path' => $galleryPath
                ]);
            }
        }

        if ($request->hasFile('floor_plans')) {
            foreach ($request->file('floor_plans') as $plan) {
                $planName = time() . '_' . uniqid() . '.' . $plan->getClientOriginalExtension();
                $plan->move(public_path('storage/floor_plans'), $planName);
                $floorPlanPath = 'storage/floor_plans/' . $planName;

                // Save to database
                $property->floorPlans()->create([
                    'image_path' => $floorPlanPath
                ]);
            }
        }

         //dd($property);
       
        return redirect('/properties');
    }

    public function edit(Property $property)
    {
        
        $property->load(['address', 'detail', 'amenities', 'galleryImages']);
        return view('backend.admin.properties.edit', compact('property'));
    }

    public function update(Request $request, Property $property)
    {
        $request->validate([
            'property_name' => 'required|string',
            'price' => 'required|numeric',
            'security_deposit' => 'nullable|numeric',
            'youtube_url' => 'nullable|url',
            'description' => 'nullable|string',
            'meta_title' => 'nullable|string',
            'meta_description' => 'nullable|string',
            'category_name' => 'required|string',
            'banner_img' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'gallery_images.*' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'floor_plans.*' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048'
        ]);

        DB::beginTransaction();

        try {
            // Update banner
            // $bannerPath = $property->banner_img;
            // if ($request->hasFile('banner_img')) {
            //     if ($bannerPath) {
            //         Storage::disk('public')->delete($bannerPath);
            //     }
            //     $bannerPath = $request->file('banner_img')->store('banners', 'public');
            // }
            
            $bannerPath = $property->banner_img; 
            if ($request->hasFile('banner_img')) {
                if ($bannerPath) {
                    $existingImagePath = public_path('storage/' . $bannerPath);
                    if (file_exists($existingImagePath)) {
                        unlink($existingImagePath); 
                    }
                }
                $image = $request->file('banner_img');
                $imageName = time() . '_' . uniqid() . '.' . $image->getClientOriginalExtension();
                $image->move(public_path('storage/banners'), $imageName);
                $bannerPath = 'storage/banners/' . $imageName;
            }
            $property->update([
                'banner_img' => $bannerPath
            ]);


            $inputSlug = $request->input('slug');
            $slugBase = $inputSlug ? Str::slug($inputSlug) : Str::slug($request->property_name);
            $slug = $slugBase;
            $count = 2;

            while (
                Property::where('slug', $slug)
                    ->where('id', '!=', $property->id)
                    ->exists()
            ) {
                $slug = $slugBase . '-' . $count;
                $count++;
            }

            // Update main property table
            $property->update([
                'property_name' => $request->property_name,
                'slug' => $slug,
                'price' => $request->price,
                'security_deposit' => $request->security_deposit,
                'youtube_url' => $request->youtube_url,
                'description' => $request->description,
                'meta_title' => $request->meta_title,
                'meta_description' => $request->meta_description,
                'banner_img' => $bannerPath,
                'category_name' => $request->category_name,
            ]);

            // Update or create address
            $property->address()->updateOrCreate([], [
                'street' => $request->input('address.street'),
                'city' => $request->input('address.city'),
                'state' => $request->input('address.state'),
                'zip_or_postal_code' => $request->input('address.zip_or_postal_code'),
                'area' => $request->input('address.area'),
                'country' => $request->input('address.country'),
            ]);

            // Update or create detail
            $property->detail()->updateOrCreate([], [
                'property_size' => $request->input('details.property_size'),
                'bedrooms' => $request->input('details.bedrooms'),
                'bathroom' => $request->input('details.bathroom'),
                'balkani' => $request->input('details.balkani'),
                'kitchen' => $request->input('details.kitchen'),
                'furnishing' => $request->input('details.furnishing'),
                'floor_no' => $request->input('details.floor_no'),
                'total_floors' => $request->input('details.total_floors'),
                'maintenance_monthly' => $request->input('details.maintenance_monthly'),
                'car_parking' => $request->input('details.car_parking'),
                'project_name' => $request->input('details.project_name'),
                'property_type' => $request->input('details.property_type'),
                'facing' => $request->input('details.facing'),
                'dining_area' => $request->input('details.dining_area'),
                'property_status' => $request->input('details.property_status'),
                'year_built' => $request->input('details.year_built'),
                'garage' => $request->input('details.garage'),
                'garage_size' => $request->input('details.garage_size'),
            ]);

            // Update or create amenities
            $property->amenities()->updateOrCreate([], $request->input('amenities', []));

            // Handle new gallery images
            // if ($request->hasFile('gallery_images')) {
            //     foreach ($request->file('gallery_images') as $image) {
            //         $path = $image->store('gallery', 'public');
            //         $property->galleryImages()->create([
            //             'image_path' => $path
            //         ]);
            //     }
            // }

            if ($request->hasFile('gallery_images')) {
                foreach ($property->galleryImages as $oldImage) {
                    $existingImagePath = public_path('storage/' . $oldImage->image_path);
                    if (file_exists($existingImagePath)) {
                        unlink($existingImagePath);
                    }
                    $oldImage->delete();
                }
                foreach ($request->file('gallery_images') as $image) {
                    $imageName = time() . '_' . uniqid() . '.' . $image->getClientOriginalExtension();
                    $image->move(public_path('storage/gallery'), $imageName);
                    $property->galleryImages()->create([
                        'image_path' => 'storage/gallery/' . $imageName
                    ]);
                }
            }

            //Floors plans
            if ($request->has('deleted_floor_plans')) {
                foreach ($request->deleted_floor_plans as $imageUrl) {
                    $relativePath = str_replace(asset('/'), '', $imageUrl);
                    $floorPlan = $property->floorPlans()->where('image_path', $relativePath)->first();

                    if ($floorPlan) {
                        $filePath = public_path($floorPlan->image_path);
                        if (file_exists($filePath)) {
                            unlink($filePath);
                        }
                        $floorPlan->delete();
                    }
                }
            }
            if ($request->hasFile('floor_plans')) {
                foreach ($request->file('floor_plans') as $plan) {
                    $imageName = time() . '_' . uniqid() . '.' . $plan->getClientOriginalExtension();
                    $plan->move(public_path('storage/floor_plans'), $imageName);
                    $property->floorPlans()->create([
                        'image_path' => 'storage/floor_plans/' . $imageName,
                    ]);
                }
            }

            DB::commit();

            return redirect()->route('properties.index')->with('success', 'Property updated successfully!');
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', 'Something went wrong: ' . $e->getMessage());
        }
    }
 
    public function destroy(Property $property)
    {
        if ($property->banner_img) {
            Storage::disk('public')->delete($property->banner_img);
        }

        // Delete gallery images
        foreach ($property->galleryImages as $image) {
            Storage::disk('public')->delete($image->image_path);
            $image->delete();
        }

        $property->delete();

        return redirect()->route('properties.index')->with('success', 'Property deleted successfully!');
    }
    
}
