<?php

namespace App\Http\Controllers;

use App\Models\Property;
use App\Models\TypeProperty;
use App\Models\City;
use App\Models\Neighborhood;
use Illuminate\Http\Request;

class PropertySaleController extends Controller
{
    public function index(Request $request)
    {
        $query = Property::where('offer_id', 2)->where('state', 'Activo');

        if ($request->filled('type'))         $query->where('type_property_id', $request->type);
        if ($request->filled('rooms'))        $query->where('rooms', $request->rooms);
        if ($request->filled('bathrooms'))    $query->where('bathrooms', $request->bathrooms);
        if ($request->filled('min_price'))    $query->where('price', '>=', $request->min_price);
        if ($request->filled('max_price'))    $query->where('price', '<=', $request->max_price);
        if ($request->filled('min_area'))     $query->where('area', '>=', $request->min_area);
        if ($request->filled('max_area'))     $query->where('area', '<=', $request->max_area);
        if ($request->filled('city'))         $query->where('city_id', $request->city);
        if ($request->filled('neighborhood')) $query->where('neighborhood_id', $request->neighborhood);

        $sales  = $query->paginate(8)->withQueryString();
        $types  = TypeProperty::all();
        $cities = City::orderBy('name')->get();

        $neighborhoods = collect();
        if ($request->filled('city')) {
            $neighborhoods = Neighborhood::where('city_id', $request->city)->orderBy('name')->get();
        }

        return view('propertySales', compact('sales', 'types', 'cities', 'neighborhoods'));
    }
}