<?php
$host = 'localhost';
$username = 'SYSDBA';
$database = 'C:\Program Files (x86)\Common Files\Aspel\Sistemas Aspel\BAN6.00\Ejemplos\EJEMPLOS.FDB';
$password = 'masterkey';

header('Content-Type: application/json');

if (!isset($_GET['tabla'])) {
    echo json_encode(['success' => false, 'error' => 'No se especificó la tabla']);
    exit;
}

$tabla = $_GET['tabla'];
$formapago = isset($_GET['formapago']) ? $_GET['formapago'] : 'all';

try {
    $dbh = new PDO("firebird:host=$host;dbname=$database;charset=UTF8", $username, $password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "SELECT * FROM $tabla";
    $stmt = $dbh->query($sql);

    $totalMontoTot = 0;
    $totalMontoExt = 0;
    $totalRegistros = 0;

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $status = trim($row['STATUS']);
        if ($status !== 'R' && $status !== 'T') {
            continue; // Solo contar registros con STATUS = 'R' o 'T'
        }

        $factor = $row['FACTOR'];
        $forma_pago = $row['FORMAPAGO'];

        if ($formapago !== 'all' && $formapago != $forma_pago) {
            continue;
        }

        // Limpiar formato si tiene comas
        $monto_ext = floatval(str_replace(',', '', $row['MONTO_EXT']));
        $monto_tot = floatval(str_replace(',', '', $row['MONTO_TOT']));

        if ($factor == 1) {
            $abono = ($monto_ext == 0 && $monto_tot > 0) ? $monto_tot : $monto_ext;
            $totalMontoExt += $abono;
        } elseif ($factor == -1) {
            $totalMontoTot += $monto_tot;
        }

        $totalRegistros++;
    }


    echo json_encode([
        'success' => true,
        'totalMontoTot' => number_format($totalMontoTot, 2, '.', ','),
        'totalMontoExt' => number_format($totalMontoExt, 2, '.', ','),
        'total_registros' => $totalRegistros
    ]);
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
