<?php
/**
 * Maintenance Requests API Endpoints
 */

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

$method = $_SERVER['REQUEST_METHOD'];
$user = authenticateRequest();
$maintenanceModel = new Maintenance();

switch ($method) {
    case 'GET':
        $id = $_GET['id'] ?? null;
        $propertyId = $_GET['property_id'] ?? null;
        $tenantId = $_GET['tenant_id'] ?? null;
        $vendorId = $_GET['vendor_id'] ?? null;
        $status = $_GET['status'] ?? null;
        
        if ($id) {
            $request = $maintenanceModel->getRequestDetails($id);
            if ($request) {
                sendResponse($request);
            } else {
                sendError('Maintenance request not found', 404);
            }
        } elseif ($propertyId) {
            $requests = $maintenanceModel->getRequestsByProperty($propertyId, $status);
            sendResponse(['requests' => $requests]);
        } elseif ($tenantId) {
            $requests = $maintenanceModel->getRequestsByTenant($tenantId);
            sendResponse(['requests' => $requests]);
        } elseif ($vendorId) {
            $requests = $maintenanceModel->getRequestsByVendor($vendorId, $status);
            sendResponse(['requests' => $requests]);
        } else {
            sendError('Invalid request', 400);
        }
        break;
        
    case 'POST':
        $data = getJsonBody();
        $data['requester_id'] = $user['user_id']; // Set requester to authenticated user
        
        try {
            $requestId = $maintenanceModel->createRequest($data);
            sendResponse(['request_id' => $requestId, 'message' => 'Maintenance request created successfully'], 201);
        } catch (Exception $e) {
            sendError($e->getMessage(), 400);
        }
        break;
        
    case 'PUT':
        $id = $_GET['id'] ?? null;
        if (!$id) {
            sendError('Request ID required', 400);
        }
        
        $action = $_GET['action'] ?? 'update';
        $data = getJsonBody();
        
        if ($action === 'assign') {
            requirePermission('maintenance.assign');
            
            $vendorId = $data['vendor_id'] ?? null;
            if (!$vendorId) {
                sendError('Vendor ID required', 400);
            }
            
            try {
                $maintenanceModel->assignVendor(
                    $id, 
                    $vendorId, 
                    $data['scheduled_date'] ?? null, 
                    $data['cost_estimate'] ?? null
                );
                sendResponse(['message' => 'Vendor assigned successfully']);
            } catch (Exception $e) {
                sendError($e->getMessage(), 400);
            }
        } elseif ($action === 'status') {
            requirePermission('maintenance.update');
            
            $status = $data['status'] ?? null;
            if (!$status) {
                sendError('Status required', 400);
            }
            
            try {
                $maintenanceModel->updateStatus(
                    $id, 
                    $status, 
                    $data['admin_notes'] ?? null, 
                    $data['final_cost'] ?? null
                );
                sendResponse(['message' => 'Status updated successfully']);
            } catch (Exception $e) {
                sendError($e->getMessage(), 400);
            }
        } else {
            requirePermission('maintenance.update');
            
            try {
                $maintenanceModel->update($id, $data);
                sendResponse(['message' => 'Request updated successfully']);
            } catch (Exception $e) {
                sendError($e->getMessage(), 400);
            }
        }
        break;
        
    default:
        sendError('Method not allowed', 405);
        break;
}
?>
