<?php
require_once 'config.php';

/**
 * SAC 2025 - GET MY STATUS
 * Este es el endpoint principal para la vista del propietario.
 */

if (!isset($_SESSION['user_id'])) {
    response(["error" => "Inicie sesión"], 401);
}

$userId = $_SESSION['user_id'];

// Consultamos la propiedad vinculada al usuario logueado
$stmt = $pdo->prepare("SELECT 
                        p.id, 
                        p.code, 
                        p.type, 
                        p.number, 
                        p.aliquot, 
                        p.has_uncommon as hasUncommonExpense, 
                        p.credit_balance as creditBalance, 
                        p.initial_debt as initialDebt, 
                        p.status,
                        (SELECT SUM(amount_usd - paid_amount) FROM property_debts WHERE property_id = p.id AND status != 'paid') as debt
                      FROM properties p
                      JOIN residents r ON p.id = r.property_id
                      WHERE r.user_id = ?
                      LIMIT 1");
$stmt->execute([$userId]);
$property = $stmt->fetch();

if (!$property) {
    response(["error" => "No se encontró propiedad vinculada a este usuario"], 404);
}

// Aseguramos tipos de datos correctos para el frontend
$property['id'] = (int)$property['id'];
$property['aliquot'] = (float)$property['aliquot'];
$property['creditBalance'] = (float)$property['creditBalance'];
$property['debt'] = (float)($property['debt'] ?? 0);

response($property);
?>