<?php
/**
 * SAC 2026 - ADD EXTRA CHARGE v1.1
 * Kernel V4.1.68: Permite agregar cargos adicionales a una cuota ya generada con soporte de tasa.
 */
require_once 'config.php';

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

$data = $REQUEST_DATA;
if (!$data || !isset($data['feeId']) || !isset($data['propertyId']) || !isset($data['amount'])) {
    response(["error" => "Parámetros incompletos"], 400);
}

try {
    $pdo->beginTransaction();

    $feeId = $data['feeId'];
    $propertyId = (int)$data['propertyId'];
    $amount = round((float)$data['amount'], 2); // Monto en USD
    $amountBs = isset($data['amount_bs']) ? (float)$data['amount_bs'] : 0;
    $appliedRate = isset($data['exchange_rate']) ? (float)$data['exchange_rate'] : 0;
    $description = $data['description'] ?? 'Cargo Extra';

    // 1. Obtener la deuda actual
    $stmt = $pdo->prepare("SELECT id, amount_usd, paid_amount, status FROM property_debts WHERE fee_id = ? AND property_id = ? FOR UPDATE");
    $stmt->execute([$feeId, $propertyId]);
    $debt = $stmtCheck = $stmt->fetch();

    if (!$debt) {
        // Si no existe la deuda para ese mes, la creamos (caso raro pero posible)
        $pdo->prepare("INSERT INTO property_debts (fee_id, property_id, amount_usd, paid_amount, status) VALUES (?, ?, ?, 0, 'Pendiente')")
            ->execute([$feeId, $propertyId, $amount]);
    } else {
        // Actualizar monto y estatus
        $newAmount = round((float)$debt['amount_usd'] + $amount, 2);
        $paid = (float)$debt['paid_amount'];
        $newStatus = ($paid >= ($newAmount - 0.01)) ? 'Pagado' : ($paid > 0 ? 'Parcial' : 'Pendiente');
        
        $pdo->prepare("UPDATE property_debts SET amount_usd = ?, status = ? WHERE id = ?")
            ->execute([$newAmount, $newStatus, $debt['id']]);
    }

    // Obtener código de propiedad para el log
    $stmtProp = $pdo->prepare("SELECT code FROM properties WHERE id = ?");
    $stmtProp->execute([$propertyId]);
    $propCode = $stmtProp->fetchColumn();

    $logMsg = "AGREGÓ CARGO EXTRA: Unidad $propCode por $$amount";
    if ($amountBs > 0) $logMsg .= " (Bs. $amountBs @ $appliedRate)";
    $logMsg .= " - Motivo: $description";

    // 2. Registrar en auditoría
    logSystemAction($logMsg, "CUOTAS");

    $pdo->commit();
    response(["success" => true]);
} catch (Exception $e) {
    if ($pdo && $pdo->inTransaction()) $pdo->rollBack();
    response(["error" => "Error Nuclear: " . $e->getMessage()], 500);
}
?>