<?php
require_once 'config.php';

checkAccess(['admin', 'programmer', 'board']);

$data = $REQUEST_DATA;

if (!$data || !isset($data['amountBs']) || !isset($data['description'])) {
    response(["error" => "Datos incompletos"], 400);
}

try {
    $pdo->beginTransaction();

    $stmt = $pdo->prepare("INSERT INTO bank_transactions 
        (date, description, amount_usd, amount_bs, type, category, reference) 
        VALUES (?, ?, ?, ?, ?, ?, ?)");
    
    $stmt->execute([
        $data['date'],
        $data['description'],
        $data['amount'] ?? 0,
        $data['amountBs'],
        $data['type'],
        $data['category'],
        $data['reference'] ?? null
    ]);

    // Lógica de Saldo a Favor (Si se especifica propertyId e isCredit)
    if (isset($data['propertyId']) && isset($data['isCredit']) && $data['isCredit'] === true && $data['type'] === 'Ingreso') {
        $propertyId = (int)$data['propertyId'];
        $amountUsd = (float)($data['amount'] ?? 0);
        $reference = $data['reference'] ?? 'S/R';
        $method = $data['method'] ?? 'Transferencia';

        // Actualizar saldo en la propiedad
        $pdo->prepare("UPDATE properties SET credit_balance = credit_balance + ? WHERE id = ?")
            ->execute([$amountUsd, $propertyId]);

        // Registrar movimiento de crédito
        $pdo->prepare("INSERT INTO credit_movements (property_id, amount_usd, source_reference, method_origin, type, description) VALUES (?, ?, ?, ?, 'Generado', 'Abono directo desde Banco')")
            ->execute([$propertyId, $amountUsd, $reference, $method]);
        
        logSystemAction("ABONÓ SALDO A FAVOR: Unidad ID $propertyId por $$amountUsd Ref: $reference", "BANCO");
    }

    // Registro de Auditoría Detallado
    $msg = "REGISTRÓ movimiento: " . $data['description'] . " (" . $data['type'] . ") por Bs." . number_format($data['amountBs'], 2, ',', '.') . " Ref:" . ($data['reference'] ?? 'S/R');
    logSystemAction($msg, "BANCO");

    // Lógica de Comisión Automática (Mantenida intacta)
    if ($data['category'] !== 'Apertura' && !empty($data['reference']) && isset($data['commissionsConfig'])) {
        $commConfig = $data['commissionsConfig'];
        $pct = ($data['type'] === 'Ingreso') ? ($commConfig['income'] ?? 0) : ($commConfig['expense'] ?? 0);
        $commissionBs = ((float)$data['amountBs'] * (float)$pct) / 100;
        
        if ($commissionBs > 0) {
            $tasa = ($data['amount'] > 0) ? ($data['amountBs'] / $data['amount']) : 1;
            $stmtComm = $pdo->prepare("INSERT INTO bank_transactions 
                (date, description, amount_usd, amount_bs, type, category, reference) 
                VALUES (?, ?, ?, ?, 'Egreso', 'Comisiones', ?)");
            $stmtComm->execute([
                $data['date'],
                "COMISIÓN BANCARIA REF: " . $data['reference'],
                round($commissionBs / $tasa, 2),
                round($commissionBs, 2),
                $data['reference']
            ]);
            logSystemAction("GENERÓ comisión automática por Bs." . number_format($commissionBs, 2, ',', '.'), "BANCO");
        }
    }

    $pdo->commit();
    response(["success" => true]);

} catch (PDOException $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    response(["error" => $e->getMessage()], 500);
}
?>