<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/helpers.php';

$pdo = getConnection();

try {
    $cuenta_id = isset($_GET['cuenta_pagar_id']) ? (int)$_GET['cuenta_pagar_id'] : 0;
    $compra_id = isset($_GET['compra_id']) ? (int)$_GET['compra_id'] : 0;

    $where = ["1=1"];
    $params = [];

    if ($cuenta_id > 0) {
        $where[] = "ap.cuenta_pagar_id = ?";
        $params[] = $cuenta_id;
    }
    if ($compra_id > 0) {
        $where[] = "ap.compra_id = ?";
        $params[] = $compra_id;
    }

    $sql = "SELECT ap.*, l.nombre as proveedor_nombre
            FROM abonos_proveedores ap
            INNER JOIN lugarcompra l ON ap.proveedor_id = l.id
            WHERE " . implode(' AND ', $where) . "
            ORDER BY ap.fecha_pago DESC, ap.created_at DESC";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $abonos = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $total_abonado = 0;
    foreach ($abonos as $a) {
        $total_abonado += (float)$a['monto_abono'];
    }

    json_success([
        'abonos' => $abonos,
        'total_abonado' => round($total_abonado, 2)
    ]);
} catch (Exception $e) {
    json_error('Error al obtener historial: ' . $e->getMessage());
}
