<?php

namespace App\Http\Controllers;

use App\Models\Property;
use App\Models\Agent;
use App\Models\Inquiry;
use App\Models\ViewingAppointment;
use Illuminate\Http\Request;

class PropertyController extends Controller
{
    public function index(Request $request)
    {
        $query = Property::with('agent');

        if ($request->filled('keyword')) {
            $keyword = $request->keyword;
            $query->where(function($q) use ($keyword) {
                $q->where('title', 'like', "%{$keyword}%")
                  ->orWhere('address', 'like', "%{$keyword}%")
                  ->orWhere('city', 'like', "%{$keyword}%")
                  ->orWhere('state', 'like', "%{$keyword}%");
            });
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('property_type')) {
            $query->where('property_type', $request->property_type);
        }

        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('bedrooms')) {
            $query->where('bedrooms', '>=', $request->bedrooms);
        }

        // Sorting
        $sort = $request->get('sort', 'latest');
        if ($sort === 'price_asc') {
            $query->orderBy('price', 'asc');
        } elseif ($sort === 'price_desc') {
            $query->orderBy('price', 'desc');
        } else {
            $query->latest();
        }

        $properties = $query->paginate(9)->withQueryString();

        $propertyTypes = ['House', 'Villa', 'Land', 'Apartment', 'Commercial'];
        $cities = Property::distinct()->pluck('city')->filter();

        return view('pages.properties.index', compact('properties', 'propertyTypes', 'cities'));
    }

    public function lands(Request $request)
    {
        $query = Property::with('agent')->where('property_type', 'Land');

        if ($request->filled('keyword')) {
            $keyword = $request->keyword;
            $query->where(function($q) use ($keyword) {
                $q->where('title', 'like', "%{$keyword}%")
                  ->orWhere('address', 'like', "%{$keyword}%")
                  ->orWhere('city', 'like', "%{$keyword}%");
            });
        }

        if ($request->filled('min_price')) {
            $query->where('price', '>=', $request->min_price);
        }

        if ($request->filled('max_price')) {
            $query->where('price', '<=', $request->max_price);
        }

        $lands = $query->latest()->paginate(9)->withQueryString();

        return view('pages.lands.index', compact('lands'));
    }

    public function show($slug)
    {
        $property = Property::with('agent')->where('slug', $slug)->firstOrFail();
        $similarProperties = Property::where('id', '!=', $property->id)
            ->where(function($q) use ($property) {
                $q->where('property_type', $property->property_type)
                  ->orWhere('status', $property->status);
            })->take(3)->get();

        return view('pages.properties.show', compact('property', 'similarProperties'));
    }

    public function submitInquiry(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'required|string|max:20',
            'message' => 'required|string',
        ]);

        Inquiry::create([
            'property_id' => $id,
            'name' => $request->name,
            'email' => $request->email,
            'phone' => $request->phone,
            'subject' => 'Inquiry for Property #' . $id,
            'message' => $request->message,
        ]);

        return back()->with('success', 'Your inquiry has been submitted successfully! One of our advisors will contact you shortly.');
    }

    public function bookViewing(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'required|string|max:20',
            'preferred_date' => 'required|date|after_or_equal:today',
            'preferred_time' => 'required|string',
            'notes' => 'nullable|string',
        ]);

        ViewingAppointment::create([
            'property_id' => $id,
            'name' => $request->name,
            'email' => $request->email,
            'phone' => $request->phone,
            'preferred_date' => $request->preferred_date,
            'preferred_time' => $request->preferred_time,
            'notes' => $request->notes,
        ]);

        return back()->with('success', 'Viewing appointment requested! We will confirm your inspection schedule via WhatsApp / Phone call.');
    }
}
