<?php
/**
 * Units API Endpoints
 */

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

$method = $_SERVER['REQUEST_METHOD'];
$user = authenticateRequest();
$unitModel = new Unit();

switch ($method) {
    case 'GET':
        $id = $_GET['id'] ?? null;
        $propertyId = $_GET['property_id'] ?? null;
        
        if ($id) {
            $unit = $unitModel->getUnitDetails($id);
            if ($unit) {
                sendResponse($unit);
            } else {
                sendError('Unit not found', 404);
            }
        } elseif ($propertyId) {
            $filters = [];
            if (isset($_GET['status'])) {
                $filters['status'] = $_GET['status'];
            }
            
            $units = $unitModel->getUnitsByProperty($propertyId, $filters);
            sendResponse(['units' => $units]);
        } elseif (isset($_GET['available'])) {
            // Get available units
            $units = $unitModel->getAvailableUnits($propertyId);
            sendResponse(['units' => $units]);
        } elseif (isset($_GET['for_sale'])) {
            // Get units for sale
            $units = $unitModel->getUnitsForSale($propertyId);
            sendResponse(['units' => $units]);
        } else {
            sendError('Invalid request', 400);
        }
        break;
        
    case 'POST':
        requirePermission('unit.create');
        
        $data = getJsonBody();
        
        try {
            $unitId = $unitModel->createUnit($data);
            sendResponse(['unit_id' => $unitId, 'message' => 'Unit created successfully'], 201);
        } catch (Exception $e) {
            sendError($e->getMessage(), 400);
        }
        break;
        
    case 'PUT':
        requirePermission('unit.update');
        
        $id = $_GET['id'] ?? null;
        if (!$id) {
            sendError('Unit ID required', 400);
        }
        
        $data = getJsonBody();
        
        try {
            $unitModel->updateUnit($id, $data);
            sendResponse(['message' => 'Unit updated successfully']);
        } catch (Exception $e) {
            sendError($e->getMessage(), 400);
        }
        break;
        
    case 'DELETE':
        requirePermission('unit.delete');
        
        $id = $_GET['id'] ?? null;
        if (!$id) {
            sendError('Unit ID required', 400);
        }
        
        try {
            $unitModel->delete($id);
            sendResponse(['message' => 'Unit deleted successfully']);
        } catch (Exception $e) {
            sendError($e->getMessage(), 400);
        }
        break;
        
    default:
        sendError('Method not allowed', 405);
        break;
}
?>
