<?php

namespace App\Http\Controllers;

use App\Models\Property;
use Illuminate\Http\Request;

class PropertyController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = Property::with('block.project');
        
        if ($request->filled('block_id')) {
            $query->where('block_id', $request->block_id);
        }
        
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        
        if ($request->filled('type')) {
            $query->where('property_type', $request->type);
        }

        $properties = $query->latest()->paginate(20);
        $blocks = \App\Models\Block::with('project')->get();
        
        return view('properties.index', compact('properties', 'blocks'));
    }

    public function create(Request $request)
    {
        $blocks = \App\Models\Block::with('project')->get();
        $selectedBlock = $request->query('block_id');
        $types = \App\Models\MasterData::where('type', 'property_type')->where('is_active', true)->get();
        return view('properties.create', compact('blocks', 'selectedBlock', 'types'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'block_id' => 'required|exists:blocks,id',
            'property_type' => 'required|string|max:100',
            'plot_number' => 'required|string|max:100',
            'size' => 'nullable|string|max:100',
            'dimensions' => 'nullable|string|max:100',
            'base_price' => 'nullable|numeric',
            'status' => 'required|string|in:Available,Reserved,Booked,Sold,Transferred,Cancelled,Blocked,Rented',
            'features' => 'nullable|string',
            'latitude' => 'nullable|numeric|between:-90,90',
            'longitude' => 'nullable|numeric|between:-180,180',
            'khasra' => 'nullable|string|max:100',
            'khewat' => 'nullable|string|max:100',
            'khatouni' => 'nullable|string|max:100',
            'mouza' => 'nullable|string|max:100',
            'street' => 'nullable|string|max:100',
            'category' => 'nullable|string|max:100',
            'has_installment_plan' => 'nullable|boolean',
        ]);

        Property::create($validated);
        
        return redirect()->route('properties.index', ['block_id' => $validated['block_id']])
                         ->with('success', 'Property added successfully.');
    }

    public function show(Property $property)
    {
        $property->load('block.project', 'interestedCustomers');
        return view('properties.show', compact('property'));
    }

    public function edit(Property $property)
    {
        $blocks = \App\Models\Block::with('project')->get();
        $types = \App\Models\MasterData::where('type', 'property_type')->where('is_active', true)->get();
        return view('properties.edit', compact('property', 'blocks', 'types'));
    }

    public function update(Request $request, Property $property)
    {
        $validated = $request->validate([
            'block_id' => 'required|exists:blocks,id',
            'property_type' => 'required|string|max:100',
            'plot_number' => 'required|string|max:100',
            'size' => 'nullable|string|max:100',
            'dimensions' => 'nullable|string|max:100',
            'base_price' => 'nullable|numeric',
            'status' => 'required|string|in:Available,Reserved,Booked,Sold,Transferred,Cancelled,Blocked,Rented',
            'features' => 'nullable|string',
            'latitude' => 'nullable|numeric|between:-90,90',
            'longitude' => 'nullable|numeric|between:-180,180',
            'khasra' => 'nullable|string|max:100',
            'khewat' => 'nullable|string|max:100',
            'khatouni' => 'nullable|string|max:100',
            'mouza' => 'nullable|string|max:100',
            'street' => 'nullable|string|max:100',
            'category' => 'nullable|string|max:100',
            'has_installment_plan' => 'nullable|boolean',
        ]);

        $oldPrice = $property->base_price;
        
        $property->update($validated);
        
        if (isset($validated['base_price']) && $validated['base_price'] != $oldPrice) {
            \App\Models\PropertyPriceHistory::create([
                'property_id' => $property->id,
                'old_price' => $oldPrice,
                'new_price' => $validated['base_price'],
                'changed_by' => auth()->id(),
            ]);
        }
        
        return redirect()->route('properties.index', ['block_id' => $validated['block_id']])
                         ->with('success', 'Property updated successfully.');
    }

    public function destroy(Property $property)
    {
        $blockId = $property->block_id;
        $property->delete();
        
        return redirect()->route('properties.index', ['block_id' => $blockId])
                         ->with('success', 'Property deleted successfully.');
    }
}
