<?php
/**
 * Leases API Endpoints
 */

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

$method = $_SERVER['REQUEST_METHOD'];
$user = authenticateRequest();
$leaseModel = new Lease();

switch ($method) {
    case 'GET':
        $id = $_GET['id'] ?? null;
        $tenantId = $_GET['tenant_id'] ?? null;
        $propertyId = $_GET['property_id'] ?? null;
        
        if ($id) {
            $lease = $leaseModel->getLeaseDetails($id);
            if ($lease) {
                sendResponse($lease);
            } else {
                sendError('Lease not found', 404);
            }
        } elseif ($tenantId) {
            $leases = $leaseModel->getActiveLeasesByTenant($tenantId);
            sendResponse(['leases' => $leases]);
        } elseif ($propertyId) {
            $leases = $leaseModel->getActiveLeasesByProperty($propertyId);
            sendResponse(['leases' => $leases]);
        } elseif (isset($_GET['expiring'])) {
            $days = $_GET['days'] ?? 30;
            $leases = $leaseModel->getExpiringLeases($days);
            sendResponse(['leases' => $leases]);
        } else {
            sendError('Invalid request', 400);
        }
        break;
        
    case 'POST':
        requirePermission('lease.create');
        
        $data = getJsonBody();
        
        try {
            $leaseId = $leaseModel->createLease($data);
            sendResponse(['lease_id' => $leaseId, 'message' => 'Lease created successfully'], 201);
        } catch (Exception $e) {
            sendError($e->getMessage(), 400);
        }
        break;
        
    case 'PUT':
        requirePermission('lease.update');
        
        $id = $_GET['id'] ?? null;
        if (!$id) {
            sendError('Lease ID required', 400);
        }
        
        $data = getJsonBody();
        
        try {
            $leaseModel->updateLease($id, $data);
            sendResponse(['message' => 'Lease updated successfully']);
        } catch (Exception $e) {
            sendError($e->getMessage(), 400);
        }
        break;
        
    case 'DELETE':
        requirePermission('lease.terminate');
        
        $id = $_GET['id'] ?? null;
        if (!$id) {
            sendError('Lease ID required', 400);
        }
        
        $data = getJsonBody();
        $terminationDate = $data['termination_date'] ?? date('Y-m-d');
        $reason = $data['reason'] ?? null;
        
        try {
            $leaseModel->terminateLease($id, $terminationDate, $reason);
            sendResponse(['message' => 'Lease terminated successfully']);
        } catch (Exception $e) {
            sendError($e->getMessage(), 400);
        }
        break;
        
    default:
        sendError('Method not allowed', 405);
        break;
}
?>
