<?php
/**
 * SAC 2026 - CREDIT BALANCES ENGINE v1.0
 * Kernel V4.1.45 BNC
 * Obtiene las unidades inmobiliarias con saldo a favor (excedentes).
 */
require_once 'config.php';

if (!isset($_SESSION['user_id'])) {
    response(["error" => "No autorizado"], 401);
}

try {
    // 1. Obtener la tasa de cambio más reciente
    $stmtRate = $pdo->query("SELECT pm_value FROM exchange_rates ORDER BY date DESC LIMIT 1");
    $latestRate = (float)$stmtRate->fetchColumn() ?: 1.0;

    // 2. Obtener propiedades con saldo a favor > 0
    // Se asume que credit_balance está en USD
    $stmt = $pdo->query("SELECT 
                            p.id, 
                            p.code, 
                            p.number, 
                            p.type, 
                            p.credit_balance as amountUsd,
                            (SELECT u.full_name FROM residents r JOIN users u ON r.user_id = u.id WHERE r.property_id = p.id AND r.is_owner = 1 LIMIT 1) as ownerName,
                            (SELECT MAX(created_at) FROM credit_movements WHERE property_id = p.id) as lastUpdate
                         FROM properties p 
                         WHERE p.credit_balance > 0 
                         ORDER BY p.number ASC");
    
    $balances = $stmt->fetchAll();
    
    $results = [];
    foreach ($balances as $row) {
        $results[] = [
            "id" => $row['id'], // ID del registro (en este caso es el mismo propertyId)
            "propertyId" => (int)$row['id'],
            "propertyCode" => $row['code'],
            "propertyNumber" => $row['number'],
            "propertyType" => $row['type'],
            "ownerName" => $row['ownerName'] ?? 'PROPIETARIO NO ASIGNADO',
            "amountUsd" => (float)$row['amountUsd'],
            "amountBs" => round((float)$row['amountUsd'] * $latestRate, 2),
            "lastUpdate" => $row['lastUpdate'] ?? 'Sin movimientos registrados',
            "observations" => "Excedente acumulado para el próximo mes."
        ];
    }

    response([
        "success" => true,
        "data" => $results,
        "exchangeRate" => $latestRate
    ]);

} catch (PDOException $e) {
    response(["error" => "Error de Kernel: " . $e->getMessage()], 500);
}
?>
?>