<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Property;
use App\Models\Address;
use App\Models\Detail;

class PropertyApiController extends Controller
{
    // public function getAllCategories()
    // {
    //     $categories = ['sell', 'rent', 'lease'];

    //     return response()->json([
    //         'status' => true,
    //         'categories' => $categories,
    //     ], 200);
    // }

    public function getAllCategories()
    {
        // Get only unique category_name values from the properties table
        $categories = \App\Models\Property::select('category_name')
                        ->whereNotNull('category_name')  // avoid nulls
                        ->distinct()
                        ->pluck('category_name')
                        ->toArray();

        return response()->json([
            'status' => true,
            'data' => $categories
        ], 200);
    }

    // public function getByCategory($category)
    // {
    //     $allowedCategories = ['sell', 'rent', 'lease'];

    //     if (!in_array(strtolower($category), $allowedCategories)) {
    //         return response()->json([
    //             'status' => false,
    //             'message' => 'Invalid category'
    //         ], 400);
    //     }

    //     $properties = Property::with(['address', 'amenities', 'detail', 'galleryImages'])
    //         ->where('category_name', strtolower($category))
    //         ->get();

    //     return response()->json([
    //         'status' => true,
    //         'data' => $properties
    //     ], 200, [], JSON_UNESCAPED_SLASHES);
    // }

    //all Category api
    public function getByCategory($category)
    {
           $allowedCategories = Property::select('category_name')
            ->distinct()
            ->pluck('category_name')
            ->map(fn($c) => strtolower($c))
            ->toArray();

        if (!in_array(strtolower($category), $allowedCategories)) {
            return response()->json([
                'status' => false,
                'message' => 'Invalid category'
            ], 400);
        }

        // ✅ Paginate results (6 per page)
        $properties = Property::with(['address', 'amenities', 'detail', 'galleryImages'])
            ->where('category_name', strtolower($category))
            ->latest()
            ->paginate(6); // <-- Paginate here

        return response()->json([
            'status' => true,
            'data' => $properties->items(), // Only the items
            'pagination' => [
                'total' => $properties->total(),
                'per_page' => $properties->perPage(),
                'current_page' => $properties->currentPage(),
                'last_page' => $properties->lastPage(),
                'next_page_url' => $properties->nextPageUrl(),
                'prev_page_url' => $properties->previousPageUrl(),
            ]
        ], 200, [], JSON_UNESCAPED_SLASHES);
    }

   //all Category with property api
   public function showByCategoryAndSlug($category, $slug)
    {
        $property = Property::with(['address', 'amenities', 'detail', 'galleryImages','floorPlans'])
            ->where('category_name', $category)
            ->where('slug', $slug)
            ->first();

        if (!$property) {
            return response()->json([
                'status' => false,
                'message' => 'Property not found.'
            ], 404);
        }

        return response()->json([
            'status' => true,
            'data' => $property
        ],200, [], JSON_UNESCAPED_SLASHES);
    }
     
  public function summary()
    {
        $categories = Property::select('category_name')->distinct()->pluck('category_name');
        $propertyTypes = Detail::select('property_type')->distinct()->pluck('property_type');
        $states = Address::select('state')->distinct()->pluck('state');

        return response()->json([
            'status' => true,
            'data' => [
                'category_names' => $categories,
                'property_types' => $propertyTypes,
                'states' => $states,
            ]
        ],200, [], JSON_UNESCAPED_SLASHES);
    }

    public function filter(Request $request)
    {
        $query = Property::with(['detail', 'address']);

        // Apply filters only if provided
        if ($request->has('category_name')) {
            $query->where('category_name', $request->category_name);
        }

        if ($request->has('property_type')) {
            $query->whereHas('detail', function ($q) use ($request) {
                $q->where('property_type', $request->property_type);
            });
        }

        if ($request->has('state')) {
            $query->whereHas('address', function ($q) use ($request) {
                $q->where('state', $request->state);
            });
        }

        $results = $query->get();

        return response()->json([
            'status' => true,
            'data' => $results
        ],200, [], JSON_UNESCAPED_SLASHES);
    }
 
    //Similer property 
    public function getSimilarProperties($category, $excludeId = null)
    {
        $query = Property::where('category_name', $category);

        if ($excludeId) {
            $query->where('id', '!=', $excludeId);
        }

        $similar = $query->latest()->take(6)->get();

        return response()->json([
            'data' => $similar
        ]);
    }

}
