<?php
/**
 * Invoices API Endpoints
 */

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

$method = $_SERVER['REQUEST_METHOD'];
$user = authenticateRequest();
$invoiceModel = new Invoice();

switch ($method) {
    case 'GET':
        $id = $_GET['id'] ?? null;
        $tenantId = $_GET['tenant_id'] ?? null;
        $propertyId = $_GET['property_id'] ?? null;
        $leaseId = $_GET['lease_id'] ?? null;
        $status = $_GET['status'] ?? null;
        
        if ($id) {
            $invoice = $invoiceModel->getInvoiceDetails($id);
            if ($invoice) {
                sendResponse($invoice);
            } else {
                sendError('Invoice not found', 404);
            }
        } elseif ($tenantId) {
            $invoices = $invoiceModel->getInvoicesByTenant($tenantId, $status);
            sendResponse(['invoices' => $invoices]);
        } elseif ($propertyId) {
            $invoices = $invoiceModel->getInvoicesByProperty($propertyId, $status);
            sendResponse(['invoices' => $invoices]);
        } elseif ($leaseId) {
            $invoices = $invoiceModel->getInvoicesByLease($leaseId);
            sendResponse(['invoices' => $invoices]);
        } elseif (isset($_GET['overdue'])) {
            $invoices = $invoiceModel->getOverdueInvoices($propertyId);
            sendResponse(['invoices' => $invoices]);
        } elseif (isset($_GET['generate_monthly'])) {
            // Generate monthly rent invoices
            requirePermission('invoice.generate');
            $count = $invoiceModel->generateMonthlyRentInvoices();
            sendResponse(['generated' => $count, 'message' => "Generated {$count} invoices"]);
        } else {
            sendError('Invalid request', 400);
        }
        break;
        
    case 'POST':
        requirePermission('invoice.create');
        
        $data = getJsonBody();
        
        try {
            $invoiceId = $invoiceModel->createInvoice($data);
            sendResponse(['invoice_id' => $invoiceId, 'message' => 'Invoice created successfully'], 201);
        } catch (Exception $e) {
            sendError($e->getMessage(), 400);
        }
        break;
        
    case 'PUT':
        requirePermission('invoice.update');
        
        $id = $_GET['id'] ?? null;
        if (!$id) {
            sendError('Invoice ID required', 400);
        }
        
        $data = getJsonBody();
        
        try {
            $invoiceModel->updateInvoice($id, $data);
            sendResponse(['message' => 'Invoice updated successfully']);
        } catch (Exception $e) {
            sendError($e->getMessage(), 400);
        }
        break;
        
    default:
        sendError('Method not allowed', 405);
        break;
}
?>
