<?php
/**
 * Unit Sales API Endpoints
 */

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

$method = $_SERVER['REQUEST_METHOD'];
$user = authenticateRequest();
$saleModel = new UnitSale();

switch ($method) {
    case 'GET':
        $id = $_GET['id'] ?? null;
        $buyerId = $_GET['buyer_id'] ?? null;
        $propertyId = $_GET['property_id'] ?? null;
        
        if ($id) {
            $sale = $saleModel->getSaleDetails($id);
            if ($sale) {
                sendResponse($sale);
            } else {
                sendError('Sale not found', 404);
            }
        } elseif ($buyerId) {
            $sales = $saleModel->getSalesByBuyer($buyerId);
            sendResponse(['sales' => $sales]);
        } elseif ($propertyId) {
            $sales = $saleModel->getSalesByProperty($propertyId);
            sendResponse(['sales' => $sales]);
        } else {
            sendError('Invalid request', 400);
        }
        break;
        
    case 'POST':
        $action = $_GET['action'] ?? 'create';
        
        if ($action === 'create') {
            requirePermission('sale.create');
            
            $data = getJsonBody();
            $data['buyer_id'] = $user['user_id']; // Set buyer to authenticated user if not specified
            
            try {
                $saleId = $saleModel->createSale($data);
                sendResponse(['sale_id' => $saleId, 'message' => 'Sale created successfully'], 201);
            } catch (Exception $e) {
                sendError($e->getMessage(), 400);
            }
        } elseif ($action === 'installment_payment') {
            $data = getJsonBody();
            validateRequired($data, ['installment_id', 'payer_id', 'payment_method', 'transaction_reference']);
            
            try {
                $paymentId = $saleModel->recordInstallmentPayment($data['installment_id'], $data);
                sendResponse(['payment_id' => $paymentId, 'message' => 'Installment payment recorded successfully'], 201);
            } catch (Exception $e) {
                sendError($e->getMessage(), 400);
            }
        } else {
            sendError('Invalid action', 400);
        }
        break;
        
    case 'PUT':
        $id = $_GET['id'] ?? null;
        if (!$id) {
            sendError('Sale ID required', 400);
        }
        
        $action = $_GET['action'] ?? 'update';
        
        if ($action === 'complete') {
            requirePermission('sale.complete');
            
            try {
                $saleModel->completeSale($id);
                sendResponse(['message' => 'Sale completed successfully']);
            } catch (Exception $e) {
                sendError($e->getMessage(), 400);
            }
        } else {
            requirePermission('sale.update');
            
            $data = getJsonBody();
            
            try {
                $saleModel->updateSale($id, $data);
                sendResponse(['message' => 'Sale updated successfully']);
            } catch (Exception $e) {
                sendError($e->getMessage(), 400);
            }
        }
        break;
        
    default:
        sendError('Method not allowed', 405);
        break;
}
?>
