<?php
class CuentaCliente
{
    public $codempresa;
    public $codcliente;
    public $nombre_cliente;
    public $total;
    public $abono;
    public $saldo;
    public $de_01_a_30;
    public $de_31_a_60;
    public $de_61_a_90;
    public $mas_90;

    public function __construct()
    {
        !empty($this->total) && $this->total = '$' . number_format($this->total, 2, '.', ',');
        !empty($this->saldo) && $this->saldo = '$' . number_format($this->saldo, 2, '.', ',');
        !empty($this->abono) && $this->abono = '$' . number_format($this->abono, 2, '.', ',');
        !empty($this->de_01_a_30) && $this->de_01_a_30 = '$' . number_format($this->de_01_a_30, 2, '.', ',');
        !empty($this->de_31_a_60) && $this->de_31_a_60 = '$' . number_format($this->de_31_a_60, 2, '.', ',');
        !empty($this->de_61_a_90) && $this->de_61_a_90 = '$' . number_format($this->de_61_a_90, 2, '.', ',');
        !empty($this->mas_90) && $this->mas_90 = '$' . number_format($this->mas_90, 2, '.', ',');
    }

    public static function obtenerCXCPendientes(): object
    {
        $db = obtenerConexion();

        $query = "select * from(select cuentas.codempresa,
            cuentas.codcliente,
            (select top(1) old.nomcliente from [" . DB_NET . "].dbo.v_cxc_antiguedadsaldos old where old.codempresa = cuentas.codempresa and old.codcliente = cuentas.codcliente) nombre_cliente,
            sum(cuentas.total) total,
            SUM(cuentas.abono) abono,
            SUM(cuentas.saldo) saldo,
            '0.00' de_01_a_30,
            SUM(cuentas.de31a60) de_31_a_60,
            SUM(cuentas.de61a90) de_61_a_90,
            SUM(cuentas.mas90) mas_90
        from [" . DB_NET . "].dbo.v_cxc_antiguedadsaldos cuentas
        where saldo > 0
        group by cuentas.codcliente,cuentas.codempresa) x
        WHERE x.saldo > 0;";
        $stmt = $db->prepare($query, [PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL, PDO::SQLSRV_ATTR_CURSOR_SCROLL_TYPE => PDO::SQLSRV_CURSOR_BUFFERED]);

        try {
            $stmt->execute();
            $data = $stmt->fetchAll(PDO::FETCH_CLASS, __CLASS__);

            return (object)[
                'status' => 200,
                'message' => 'success',
                'data' => $data
            ];
        } catch (PDOException $e) {
            return (object)[
                'status' => 500,
                'message' => $e->getMessage()
            ];
        }
    }
}
