<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Property;
// use App\Models\PropertyPhoto;
use App\Models\Property_Types;
use App\Models\Rooms;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;

class PropertyController extends Controller
{
   
    public function index()
    {
        try {
            $prop = Property::with(['category', 'types', 'facilities', 'landmarks', 'rooms.user'])
            ->latest()
                ->paginate(10);
                

            return response()->json([
                'status' => 'success',
                'property' => $prop
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve properties.',
                'error' => $e->getMessage()
            ], 500);
        }
    }
    public function search(Request $request)
    {
        try {
            $query = Property::with(['category', 'types', 'facilities', 'landmarks', 'photos'])
                ->where('status', 'on')->latest();

            // Filter by category
            if ($request->has('id_categ') && $request->id_categ) {
                $query->where('id_categ', $request->id_categ);
            }
            if ($request->has('kota') && $request->kota) {
                $query->where('kota', $request->kota);
            }

            // Filter by budget range
            if ($request->has('min_budget') && $request->min_budget) {
                $query->where('base_price', '>=', $request->min_budget);
            }

            if ($request->has('max_budget') && $request->max_budget) {
                $query->where('base_price', '<=', $request->max_budget);
            }


            $properties = $query->paginate(6);

            return response()->json([
                'status' => 'success',
                'property' => $properties
            ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to search properties.',
                'error' => $e->getMessage()
            ], 500);
        }
    }
    public function index2()
    {
        try {
            $prop = Property::with(['category', 'types', 'facilities', 'landmarks', 'rooms'])
                ->where('status', 'on')
                ->paginate(6)
                ->latest();

            return response()->json([
                'status' => 'success',
                'property' => $prop
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve properties.',
                'error' => $e->getMessage()
            ], 500);
        }
    }
    
    public function display3()
    {
        try {
            $prop = Cache::remember('latest_3_properties', 1800, function () {
                return Property::with(['category', 'types', 'facilities', 'photos'])
                    ->where('status', 'on')
                    ->latest()
                    ->take(3)
                    ->get();
            });

            return response()->json([
                'status' => 'success',
                'property' => $prop
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve properties.',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function store(Request $request)
{
    // Validasi tetap di luar transaction, ini praktik yang baik
    $validator = Validator::make($request->all(), [
        'prop_name'       => 'required|string|max:255|unique:properties',
        'slug'            => 'required|string|unique:properties,slug', // ✅
        'id_categ'        => 'required|exists:categories,id',
        'description'     => 'nullable|string',
        'kota'            => 'required|string',
        'kecamatan'       => 'required|string',
        'maps_iframe'     => 'nullable',
        'address'         => 'nullable|string',
        'base_price'      => 'required|integer',
        'promo_price'     => 'nullable|integer',
        'total_floor'     => 'nullable|numeric',
        'total_rooms'     => 'nullable|numeric',
        'status'          => 'nullable|string',
        'maps_iframe'     => 'nullable',

        'seo_title'       => 'nullable|string|max:70',
        'seo_description' => 'nullable|string|max:160',
        'seo_og_image'    => 'nullable|string',
        'seo_canonical'   => 'nullable|string',
        'seo_robots'      => 'nullable|string',

        // Untuk relasi
        'types'           => 'sometimes|array', // `sometimes` lebih cocok jika array boleh tidak ada
        'types.*.type_name' => 'required_with:types|string',
        'types.*.status'  => 'nullable|string',
        'facilities'      => 'sometimes|array',
        'facilities.*'    => 'exists:facilities,id',
    ]);

    if ($validator->fails()) {
        return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
    }

    try {
        
        $property = DB::transaction(function () use ($request) {
             // ✅ Generate slug otomatis jika tidak diisi
            $slug = $request->slug ?? \Illuminate\Support\Str::slug($request->prop_name);

            $property = Property::create($request->only([
                'prop_name', 'slug', 'id_categ', 'description', 'address', 'maps_iframe',
                'kota', 'kecamatan', 'total_floor', 'base_price', 'promo_price', 'total_rooms', 'status',
                'seo_title', 'seo_description', 'seo_og_image', 'seo_canonical', 'seo_robots'
            ]) + ['slug' => $slug]);

            // 2. Tambahkan tipe (jika ada) - createMany lebih efisien dari foreach
            // Set promo_price jika kosong (40% lebih mahal dari base_price)
            if (is_null($request->promo_price)) {
                $request->merge([
                    'promo_price' => $request->base_price + ($request->base_price * 0.4)
                ]);
            }

            if ($request->filled('types')) {
                foreach ($request->types as $typeData) {
                    // Cari tipe berdasarkan nama, jika sudah ada gunakan, jika belum buat baru
                    $type = Property_Types::firstOrCreate(
                        ['type_name' => $typeData['type_name']],
                        ['status' => $typeData['status'] ?? 'on']
                    );
                    // Attach ke property melalui pivot, bisa tambahkan data pivot jika perlu
                    $property->types()->attach($type->id, [
                        'harga'         => $typeData['harga'] ?? 0,
                        'jumlah_kamar'  => $typeData['jumlah_kamar'] ?? 0,
                        'lantai'        => $typeData['lantai'] ?? 1,
                    ]);
                }
            }

            // 3. Tambahkan fasilitas (jika ada)
            if ($request->filled('facilities')) {
                $property->facilities()->sync($request->facilities);
            }

            // Kembalikan objek property agar bisa digunakan di luar closure
            return $property;
        });


        Cache::forget('latest_3_properties');

        return response()->json([
            'success' => true,
            'message' => 'Properti berhasil dibuat beserta relasinya',
            'data' => $property->load('category', 'types', 'facilities')
        ], 201);

    } catch (\Throwable $th) {
       
        return response()->json([
            'success' => false,
            'message' => 'Terjadi kesalahan saat membuat properti',
            'error' => $th->getMessage()
        ], 500);
    }
}


// $type = Property::findOrFail($id);
    public function show(string $id)
    {
        try {
            $property = Property::with(['category', 'types', 'facilities', 'rooms'])->findOrFail($id);
            return response()->json([
                'success' => true,
                'data' => $property
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve Property',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    
    // public function getBySlug($slug)
    // {
    //     try {
    //         $property = Property::with(['category', 'types', 'facilities', 'rooms', 'landmarks', 'photos'])
    //             ->whereRaw('LOWER(REPLACE(prop_name, " ", "-")) = ?', [$slug])
    //             ->firstOrFail();

    //         return response()->json([
    //             'success' => true,
    //             'data' => $property
    //         ], 200);
    //     } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
    //         return response()->json([
    //             'success' => false,
    //             'message' => 'Property tidak ditemukan'
    //         ], 404);
    //     } catch (\Exception $e) {
    //         return response()->json([
    //             'success' => false,
    //             'message' => 'Failed to retrieve Property',
    //             'error' => $e->getMessage()
    //         ], 500);
    //     }
    // }

    public function getBySlug($slug)
    {
        try {

            $property = Cache::remember(
                "property_detail_$slug",
                1800, // 30 menit
                function () use ($slug) {

                    return Property::with([
                            'category',
                            'types',
                            'facilities',
                            'rooms',
                            'landmarks',
                            'photos'
                        ])
                        ->where('slug', $slug)
                        ->first();
                }
            );

            if (!$property) {
                return response()->json([
                    'success' => false,
                    'message' => 'Property tidak ditemukan'
                ], 404);
            }

            return response()->json([
                'success' => true,
                'data' => $property
            ], 200);

        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve Property',
                'error'   => $e->getMessage()
            ], 500);
        }
    }

    
    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'prop_name'   => 'required|string|max:255|unique:properties,prop_name,' . $id,
            'slug'        => 'nullable|string|unique:properties,slug,' . $id,
            'id_categ'    => 'required|exists:categories,id',
            'description' => 'nullable|string',
            'kota'        => 'required|string',
            'kecamatan'   => 'required|string',
            'maps_iframe' => 'nullable',
            'address'     => 'nullable|string',
            'base_price'  => 'sometimes|numeric',
            'promo_price' => 'nullable|sometimes|numeric',
            'status'      => 'nullable|in:on,off',

            // ✅ SEO Fields (validation)
            'seo_title'       => 'nullable|string|max:255',
            'seo_description' => 'nullable|string',
            'seo_og_image'    => 'nullable|string',
            'seo_canonical'   => 'nullable|string',
            'seo_robots'      => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
        }

        try {
            $property = Property::findOrFail($id);

            // ✅ PERBAIKAN: Tambahkan field SEO ke dalam $request->only()
            $dataToUpdate = $request->only([
                'prop_name', 'id_categ', 'description', 'address', 'maps_iframe',
                'kota', 'kecamatan', 'base_price', 'promo_price', 'status',
                // 👇 FIELD SEO DITAMBAHKAN DI SINI
                'seo_title', 'seo_description', 'seo_og_image', 'seo_canonical', 'seo_robots'
            ]);

            // ✅ Handle slug (jika diisi manual, gunakan; jika tidak, generate otomatis)
            $dataToUpdate['slug'] = $request->slug 
                ? $request->slug 
                : \Illuminate\Support\Str::slug($request->prop_name);

            // ✅ Set promo_price default jika kosong
            if (empty($request->promo_price)) {
                $dataToUpdate['promo_price'] = $request->base_price + ($request->base_price * 0.4);
            }
            $slug = $property->slug;

            $property->update($dataToUpdate);

            Cache::forget("property_detail_$slug");
            
            return response()->json([
                'success' => true,
                'message' => 'Properti berhasil diperbarui',
                'data' => $property->load('category')
            ]);

        } catch (\Throwable $th) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal memperbarui properti',
                'error'   => $th->getMessage()
            ], 500);
        }
    }


    public function destroy(string $id)
    {
        try {
            $type = Property::findOrFail($id);
            $slug = $type->slug;
            $type->delete();

            Cache::forget("property_detail_$slug");

            return response()->json([
                'success' => true,
                'message' => 'Property soft deleted successfully.'
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to soft delete kategori type.',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function trashed()
    {
        try {
            $trashedTypes = Property::onlyTrashed()->get();
            
            if ($trashedTypes->isEmpty()) {
                return response()->json([
                    'success' => true,
                    'message' => 'Tidak ada data property yang dihapus.',
                    'data' => []
                ], 200);
            }

            return response()->json([
                'success' => true,
                'message' => 'Data property yang dihapus berhasil diambil.',
                'data' => $trashedTypes
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengambil data property yang dihapus.',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function restore(string $id)
    {
        try {
            $type = Property::onlyTrashed()->findOrFail($id);
            $slug = $type->slug;
            $type->restore();

            Cache::forget("property_detail_$slug");

            return response()->json([
                'success' => true,
                'message' => 'property data restored successfully.',
                'data' => $type
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to restore property data.',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function forceDestroy($id)
    {
        try {
            $property = Property::withTrashed()->findOrFail($id);

            // ❗ Cek apakah property masih digunakan pada property_x_types
            $usedInPivot = DB::table('property_x_types')
                ->where('id_proper', $id)
                ->exists();

            if ($usedInPivot) {
                return response()->json([
                    'success' => false,
                    'message' => 'Properti tidak dapat dihapus karena masih memiliki relasi tipe kamar.'
                ], 422);
            }

            $roomIds = $property->rooms()->pluck('rooms.id');

            $usedInBooking = \App\Models\Booking::whereIn('id_room', $roomIds)->exists();

            if ($usedInBooking) {
                return response()->json([
                    'success' => false,
                    'message' => 'Properti tidak dapat dihapus karena ada kamar yang masih digunakan dalam booking.'
                ], 422);
}

            // Hapus relasi lainnya
            $property->facilities()->detach();
            $property->rooms()->delete();

            // Hapus properti secara permanen
            $slug = $property->slug;
            $property->forceDelete();

            Cache::forget("property_detail_$slug");

            return response()->json([
                'success' => true,
                'message' => 'Properti berhasil dihapus permanen.'
            ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal menghapus properti',
                'error' => $e->getMessage()
            ], 500);
        }
    }



    public function addTypeWithRooms(Request $request, $propertyId)
    {
        $validator = Validator::make($request->all(), [
            'id_type'       => 'required|exists:property__types,id',
            'harga'         => 'required|numeric',
            'jumlah_kamar'  => 'required|integer|min:1',
            'lantai'        => 'required|integer|max:50',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        try {
            DB::beginTransaction();

            $property = Property::findOrFail($propertyId);

            // 1. Tambahkan tipe ke property dengan data pivot
            $property->types()->attach($request->id_type, [
                'harga'         => $request->harga,
                'jumlah_kamar'  => $request->jumlah_kamar,
                'lantai'        => $request->lantai,
            ]);

            // 2. Generate rooms sesuai jumlah_kamar
            $pivot = DB::table('property_x_types')
                ->where('id_proper', $propertyId)
                ->where('id_type', $request->id_type)
                ->orderByDesc('id')
                ->first();

            if (!$pivot) {
                throw new \Exception('Pivot data not found');
            }

            $roomsData = [];
            for ($i = 0; $i < $request->jumlah_kamar; $i++) {
                $roomsData[] = [
                    'id_prop_typ' => $pivot->id,
                    'status'      => 'on', // default status, bisa disesuaikan
                    'lantai'      => $request->lantai,
                    'created_at'  => now(),
                    'updated_at'  => now(),
                ];
            }
            Rooms::insert($roomsData);
            
            // 3. Update total_rooms dan total_floor pada property
            // Hitung total_rooms dari seluruh jumlah_kamar di property_x_types untuk property ini
            $totalRooms = DB::table('property_x_types')
                ->where('id_proper', $propertyId)
                ->sum('jumlah_kamar');
            // Hitung total lantai unik dari property_x_types untuk property ini
            $totalFloor = DB::table('property_x_types')
                ->where('id_proper', $propertyId)
                ->distinct('lantai')
                ->count('lantai');
            // Update property
            $property->update([
                'total_rooms' => $totalRooms,
                'total_floor' => $totalFloor,
            ]);

            DB::commit();

            Cache::forget("property_detail_{$property->slug}");
            Cache::forget('latest_3_properties');

            return response()->json([
                'success' => true,
                'message' => 'Tipe dan rooms berhasil ditambahkan ke property',
            ], 201);

        } catch (\Throwable $th) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Gagal menambahkan tipe dan rooms',
                'error'   => $th->getMessage()
            ], 500);
        }
    }

    // Tambah fasilitas ke property
    public function addFacilities(Request $request, $propertyId)
    {
        $validator = Validator::make($request->all(), [
            'facilities'   => 'nullable|array',
            'facilities.*' => 'exists:facilities,id',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
        }

        try {
            $property = Property::findOrFail($propertyId);
            $property->facilities()->sync($request->facilities);

            Cache::forget("property_detail_{$property->slug}");
            Cache::forget('latest_3_properties');

            return response()->json([
                'success' => true,
                'message' => 'Facilities added to property',
                'data'    => $property->load('facilities')
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to add facilities to property.',
                'error'   => $e->getMessage()
            ], 500);
        }
    }

    // Tambah tipe ke property
    public function addType(Request $request, $propertyId)
    {
        $validator = Validator::make($request->all(), [
            'type_name'     => 'required|string',
            'status'        => 'nullable|string',
            'harga'         => 'required|numeric',
            'jumlah_kamar'  => 'nullable|integer|min:1',
            'lantai'        => 'required|integer|max:50',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
        }

        try {
            $property = Property::findOrFail($propertyId);

            // Cari atau buat tipe
            $type = Property_Types::firstOrCreate(
                ['type_name' => $request->type_name],
                ['status' => $request->status ?? 'on']
            );

            // Attach ke property melalui pivot
            $property->types()->attach($type->id, [
                'harga'         => $request->harga,
                'jumlah_kamar'  => $request->jumlah_kamar??0,
                'lantai'        => $request->lantai,
            ]);

            Cache::forget("property_detail_{$property->slug}");
            Cache::forget('latest_3_properties');

            return response()->json([
                'success' => true,
                'message' => 'Type added to property',
                'data'    => $type
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to add type to property.',
                'error'   => $e->getMessage()
            ], 500);
        }
    }

    // Tambah rooms ke tipe (pivot)
    public function addRoomsToType(Request $request, $pivotId)
    {
        $validator = Validator::make($request->all(), [
            'jumlah_kamar'  => 'required|integer|min:1',
            'kode_awal'     => 'required|string|max:10',
            // 'status'        => 'nullable|string',
            'lantai'        => 'nullable|integer|max:50',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
        }

        try {
            // Pastikan pivot ada
            $pivot = DB::table('property_x_types')->where('id', $pivotId)->first();
            if (!$pivot) {
                return response()->json(['success' => false, 'message' => 'Pivot not found'], 404);
            }

            // Ekstrak prefix dan base number dari kode_awal
            $kodeAwal = strtoupper(trim($request->kode_awal));
    
            // Cocokkan pola: huruf + angka di akhir, misal REG-1 atau STN3 atau A3
            if (!preg_match('/^(.*?)(\d+)$/', $kodeAwal, $matches)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Format kode_awal harus mengandung angka di akhir, contoh: REG-1, STN3'
                ], 422);
            }
    
            $prefix = $matches[1];         // Misal: "REG-", "STN"
            $baseNumber = (int)$matches[2]; // Misal: 1 → jadi 100, 3 → jadi 300
            $startFrom = $baseNumber * 100; // 1 → 100, 3 → 300
    
            // Cari kamar terakhir yang sudah dibuat dengan pola ini
            $lastRoom = DB::table('rooms')
                ->where('kode_kamar', 'like', $prefix . $baseNumber . '%') // e.g. REG-1%, STN3%
                ->orderByRaw("CAST(SUBSTRING(kode_kamar, LENGTH(?) + 1) AS UNSIGNED) DESC", [$prefix . $baseNumber])
                ->first();
    
            $nextNumber = $startFrom + 1; // Default: mulai dari 101, 301, dll
    
            if ($lastRoom && preg_match('/\d+$/', $lastRoom->kode_kamar, $match)) {
                $lastSeq = (int)$match[0];
                if ($lastSeq >= $startFrom) {
                    $nextNumber = $lastSeq + 1;
                }
            }
    
            // Buat data kamar
            $roomsData = [];
            for ($i = 0; $i < $request->jumlah_kamar; $i++) {
                $roomNumber = $nextNumber + $i;
                $roomsData[] = [
                    'id_prop_typ' => $pivotId,
                    'kode_kamar'  => $prefix . $roomNumber, // e.g. REG-101, STN-302
                    'status'      => $request->status ?? 'available',
                    'lantai'      => $request->lantai,
                    'created_at'  => now(),
                    'updated_at'  => now(),
                ];
            }
            Rooms::insert($roomsData);

            // Update jumlah_kamar di pivot (property_x_types)
            $jumlahKamar = DB::table('rooms')->where('id_prop_typ', $pivotId)->count();
            DB::table('property_x_types')->where('id', $pivotId)->update(['jumlah_kamar' => $jumlahKamar]);

            // Hitung jumlah lantai unik untuk pivot ini (rooms dengan id_prop_typ = $pivotId)
            $lantaiUnikPivot = DB::table('rooms')->where('id_prop_typ', $pivotId)->distinct('lantai')->count('lantai');
            DB::table('property_x_types')->where('id', $pivotId)->update(['lantai' => $lantaiUnikPivot]);

            // Update total_floor pada properties (jumlah lantai unik dari semua rooms di property terkait)
            $propertyId = $pivot->id_proper;
            $totalFloor = DB::table('rooms')
                ->join('property_x_types', 'rooms.id_prop_typ', '=', 'property_x_types.id')
                ->where('property_x_types.id_proper', $propertyId)
                ->distinct('rooms.lantai')
                ->count('rooms.lantai');
            DB::table('properties')->where('id', $propertyId)->update(['total_floor' => $totalFloor]);

            // Update total_rooms pada properties (jumlah seluruh rooms di property terkait)
            $totalRooms = DB::table('rooms')
                ->join('property_x_types', 'rooms.id_prop_typ', '=', 'property_x_types.id')
                ->where('property_x_types.id_proper', $propertyId)
                ->count();
            DB::table('properties')->where('id', $propertyId)->update(['total_rooms' => $totalRooms]);

            $property = Property::find($propertyId);
            if ($property) {
                Cache::forget("property_detail_{$property->slug}");
                Cache::forget('latest_3_properties');
            }

            return response()->json([
                'success' => true,
                'message' => 'Rooms created for type',
                'data'    => $roomsData
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create rooms for type.',
                'error'   => $e->getMessage()
            ], 500);
        }
    }
    // Tambahkan di dalam class PropertyController

    // Detach all types from property
    public function detachTypes($propertyId)
    {
        try {
            $property = Property::findOrFail($propertyId);

            // 1. Ambil semua ID pivot type yang terhubung ke property
            $pivotIds = DB::table('property_x_types')
                ->where('id_proper', $propertyId)
                ->pluck('id');

            // 2. Ambil semua ID tipe (property__types) dari pivot ini
            $typeIds = DB::table('property_x_types')
                ->where('id_proper', $propertyId)
                ->pluck('id_type');

            // 3. Cek apakah ada kamar yang sedang dihuni (id_user != null)
            $roomsInUse = DB::table('rooms')
                ->whereIn('id_prop_typ', $pivotIds)
                ->whereNotNull('id_user')
                ->exists();

            if ($roomsInUse) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tidak dapat menghapus tipe karena ada kamar yang sedang dihuni.'
                ], 422);
            }

            // ❗ Tambahan cek apakah ada booking yang pernah menggunakan room ini
            $roomsUsedInBooking = DB::table('bookings')
            ->whereIn('id_room', function ($query) use ($pivotIds) {
                $query->select('id')->from('rooms')->whereIn('id_prop_typ', $pivotIds);
            })
            ->exists();

            if ($roomsUsedInBooking) {
            return response()->json([
                'success' => false,
                'message' => 'Tidak dapat menghapus tipe karena ada kamar yang memiliki riwayat booking.'
            ], 422);
            }


            // 4. Hapus semua rooms yang terhubung ke pivot
            DB::table('rooms')->whereIn('id_prop_typ', $pivotIds)->delete();
            
            // 5. Detach semua relasi tipe dari property (hapus dari pivot)
            $property->types()->detach();

            // 6. Coba hapus tipe, tetapi hanya jika tidak dipakai di properti lain
            foreach ($typeIds as $typeId) {
                $count = DB::table('property_x_types')
                    ->where('id_type', $typeId)
                    ->count();

                if ($count === 0) {
                    // Tidak dipakai properti lain, aman untuk dihapus
                    \App\Models\Property_Types::where('id', $typeId)->delete();
                }
            }

            // 7. Update properti total_rooms & total_floor ke 0
            $property->update([
                'total_rooms' => 0,
                'total_floor' => 0,
            ]);

            Cache::forget("property_detail_{$property->slug}");
            Cache::forget('latest_3_properties');

            return response()->json([
                'success' => true,
                'message' => 'Semua tipe berhasil dihapus dari properti, termasuk tipe yang tidak digunakan oleh properti lain.',
                'data' => $property->load('types')
            ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal menghapus tipe dari properti.',
                'error' => $e->getMessage()
            ], 500);
        }
    }



    // Detach all landmarks from property
    public function detachLandmarks($propertyId)
    {
        try {
            $property = Property::findOrFail($propertyId);

            // Detach all landmarks from property
            $property->landmarks()->detach();

            Cache::forget("property_detail_{$property->slug}");
            Cache::forget('latest_3_properties');

            return response()->json([
                'status' => 'success',
                'message' => 'All landmarks have been cleared from property',
                'data' => $property->load('landmarks')
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to clear landmarks from property.',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}