<?php
/**
 * Properties API Endpoints
 */

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../classes/Database.php';
require_once __DIR__ . '/../classes/Property.php';
require_once __DIR__ . '/middleware.php';

$method = $_SERVER['REQUEST_METHOD'];
$user = authenticateRequest();
$propertyModel = new Property();

switch ($method) {
    case 'GET':
        // Get property by ID or list all properties
        $id = $_GET['id'] ?? null;
        $ownerId = $_GET['owner_id'] ?? $user['user_id'];
        
        if ($id) {
            $property = $propertyModel->getPropertyDetails($id, $ownerId);
            if ($property) {
                sendResponse($property);
            } else {
                sendError('Property not found', 404);
            }
        } else {
            // Get all properties for owner
            $filters = [];
            if (isset($_GET['type'])) {
                $filters['type'] = $_GET['type'];
            }
            
            $properties = $propertyModel->getPropertiesByOwner($ownerId, $filters);
            sendResponse(['properties' => $properties]);
        }
        break;
        
    case 'POST':
        // Create new property
        requirePermission('property.create');
        
        $data = getJsonBody();
        $data['owner_id'] = $user['user_id']; // Ensure owner is the authenticated user
        
        try {
            $propertyId = $propertyModel->createProperty($data);
            sendResponse(['property_id' => $propertyId, 'message' => 'Property created successfully'], 201);
        } catch (Exception $e) {
            sendError($e->getMessage(), 400);
        }
        break;
        
    case 'PUT':
        // Update property
        requirePermission('property.update');
        
        $id = $_GET['id'] ?? null;
        if (!$id) {
            sendError('Property ID required', 400);
        }
        
        $data = getJsonBody();
        
        try {
            $propertyModel->updateProperty($id, $data, $user['user_id']);
            sendResponse(['message' => 'Property updated successfully']);
        } catch (Exception $e) {
            sendError($e->getMessage(), 400);
        }
        break;
        
    case 'DELETE':
        // Delete property
        requirePermission('property.delete');
        
        $id = $_GET['id'] ?? null;
        if (!$id) {
            sendError('Property ID required', 400);
        }
        
        try {
            $propertyModel->delete($id, $user['user_id']);
            sendResponse(['message' => 'Property deleted successfully']);
        } catch (Exception $e) {
            sendError($e->getMessage(), 400);
        }
        break;
        
    default:
        sendError('Method not allowed', 405);
        break;
}
?>
