<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\Property;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class PropertyApiController extends Controller
{
    /**
     * Display a listing of active properties with pagination.
     */
    public function index(Request $request)
    {
        $query = Property::active()->ordered();

        // Filter by type
        if ($request->has('type') && in_array($request->type, array_keys(Property::getTypes()))) {
            $query->ofType($request->type);
        }

        // Filter by bedrooms
        if ($request->has('bedrooms')) {
            $query->where('bedrooms', '>=', $request->bedrooms);
        }

        // Filter by bathrooms
        if ($request->has('bathrooms')) {
            $query->where('bathrooms', '>=', $request->bathrooms);
        }

        // Filter by area range
        if ($request->has('min_area')) {
            $query->where('area', '>=', $request->min_area);
        }
        if ($request->has('max_area')) {
            $query->where('area', '<=', $request->max_area);
        }

        // Search by title or description
        if ($request->has('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                  ->orWhere('short_description', 'like', "%{$search}%");
            });
        }

        $perPage = $request->get('per_page', 12);
        $properties = $query->paginate($perPage);

        // Transform the data for API response
        $properties->getCollection()->transform(function ($property) {
            return $property->toApiArray();
        });

        return response()->json([
            'success' => true,
            'data' => $properties->items(),
            'pagination' => [
                'current_page' => $properties->currentPage(),
                'last_page' => $properties->lastPage(),
                'per_page' => $properties->perPage(),
                'total' => $properties->total(),
                'from' => $properties->firstItem(),
                'to' => $properties->lastItem(),
            ],
            'message' => 'Properties retrieved successfully'
        ]);
    }

    /**
     * Display the specified property.
     */
    public function show($id)
    {
        try {
            $property = Property::findOrFail($id);
            
            // Only return active properties
            if (!$property->isActive()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Property not found or inactive'
                ], 404);
            }

            return response()->json([
                'success' => true,
                'data' => $property->toApiDetailArray(),
                'message' => 'Property retrieved successfully'
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Property not found'
            ], 404);
        }
    }

    /**
     * Get properties for mobile display.
     */
    public function mobileProperties(Request $request)
    {
        $query = Property::active()->mobileDisplay()->homepageDisplay()->ordered();

        // Filter by type if provided
        if ($request->has('type') && in_array($request->type, array_keys(Property::getTypes()))) {
            $query->ofType($request->type);
        }

        $limit = $request->get('limit', 10);
        $properties = $query->limit($limit)->get();

        // Transform the data for API response
        $properties = $properties->map(function ($property) {
            return $property->toApiArray();
        });

        return response()->json([
            'success' => true,
            'data' => $properties,
            'message' => 'Mobile properties retrieved successfully'
        ]);
    }

    /**
     * Get properties for homepage display.
     */
    public function homepageProperties(Request $request)
    {
        $query = Property::active()->homepageDisplay()->ordered();

        // Filter by type if provided
        if ($request->has('type') && in_array($request->type, array_keys(Property::getTypes()))) {
            $query->ofType($request->type);
        }

        $limit = $request->get('limit', 6);
        $properties = $query->limit($limit)->get();

        // Transform the data for API response
        $properties = $properties->map(function ($property) {
            return $property->toApiArray();
        });

        return response()->json([
            'success' => true,
            'data' => $properties,
            'message' => 'Homepage properties retrieved successfully'
        ]);
    }

    /**
     * Get property types.
     */
    public function types()
    {
        return response()->json([
            'success' => true,
            'data' => Property::getTypes(),
            'message' => 'Property types retrieved successfully'
        ]);
    }

    /**
     * Get property statistics.
     */
    public function statistics()
    {
        $stats = [
            'total' => Property::active()->count(),
            'by_type' => [],
            'total_bedrooms' => Property::active()->sum('bedrooms'),
            'total_bathrooms' => Property::active()->sum('bathrooms'),
            'average_area' => Property::active()->avg('area'),
            'mobile_display' => Property::active()->mobileDisplay()->count(),
            'homepage_display' => Property::active()->homepageDisplay()->count(),
        ];

        // Get count by type
        foreach (Property::getTypes() as $type => $name) {
            $stats['by_type'][$type] = [
                'name' => $name,
                'count' => Property::active()->ofType($type)->count()
            ];
        }

        return response()->json([
            'success' => true,
            'data' => $stats,
            'message' => 'Property statistics retrieved successfully'
        ]);
    }

    /**
     * Search properties.
     */
    public function search(Request $request)
    {
        $request->validate([
            'query' => 'required|string|min:2',
        ]);

        $query = Property::active()->ordered();

        $search = $request->query;
        $query->where(function ($q) use ($search) {
            $q->where('title', 'like', "%{$search}%")
              ->orWhere('short_description', 'like', "%{$search}%")
              ->orWhere('full_description', 'like', "%{$search}%");
        });

        $perPage = $request->get('per_page', 12);
        $properties = $query->paginate($perPage);

        // Transform the data for API response
        $properties->getCollection()->transform(function ($property) {
            return $property->toApiArray();
        });

        return response()->json([
            'success' => true,
            'data' => $properties->items(),
            'pagination' => [
                'current_page' => $properties->currentPage(),
                'last_page' => $properties->lastPage(),
                'per_page' => $properties->perPage(),
                'total' => $properties->total(),
                'from' => $properties->firstItem(),
                'to' => $properties->lastItem(),
            ],
            'message' => 'Search results retrieved successfully'
        ]);
    }
} 