<?php

namespace App\Http\Controllers;

use App\Models\Property;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class PropertyController extends Controller
{
    public function index()
    {
        $properties = Auth::user()->properties()->orderBy('name')->get();
        return response()->json($properties);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name'       => 'required|string',
            'address'    => 'required|string',
            'lat'        => 'required|numeric',
            'lng'        => 'required|numeric',
            'int_number' => 'nullable|string',
            'icon'       => 'nullable|in:casa,oficina',
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        $property = new Property();
        $property->user_id    = Auth::id();
        $property->name       = strip_tags($request->name);
        $property->address    = strip_tags($request->address);
        $property->lat        = $request->lat;
        $property->lng        = $request->lng;
        $property->int_number = $request->int_number ? strip_tags($request->int_number) : null;
        $property->icon       = $request->icon ?? 'casa';
        $property->save();

        return response()->json($property, 201);
    }

    public function destroy($id)
    {
        $property = Property::find($id);

        if (!$property || $property->user_id !== Auth::id()) {
            return response()->json(['message' => 'No autorizado'], 403);
        }

        $property->delete();
        return response()->json(['message' => 'Propiedad eliminada']);
    }
}
