<?php

declare(strict_types=1);

namespace App\Shared\Legacy;

use PDO;

final class CustomerSupport
{
    public static function balance(PDO $pdo, int $customerId, ?string $asOf = null): float
    {
        if ($customerId <= 0) {
            return 0.0;
        }

        $asOf = $asOf ? date('Y-m-d', strtotime($asOf)) : null;

        $st = $pdo->prepare('SELECT opening_balance, credit_limit FROM customers WHERE id=? LIMIT 1');
        $st->execute([$customerId]);
        $customer = $st->fetch();
        $opening = $customer ? (float) $customer['opening_balance'] : 0.0;

        if (!table_exists($pdo, 'customer_ledger')) {
            return $opening;
        }

        if ($asOf) {
            $st = $pdo->prepare('SELECT COALESCE(SUM(debit-credit),0) s FROM customer_ledger WHERE customer_id=? AND doc_date<=?');
            $st->execute([$customerId, $asOf]);
        } else {
            $st = $pdo->prepare('SELECT COALESCE(SUM(debit-credit),0) s FROM customer_ledger WHERE customer_id=?');
            $st->execute([$customerId]);
        }

        $sum = (float) ($st->fetchColumn() ?: 0);
        return $opening + $sum;
    }
}
