<?php

declare(strict_types=1);

namespace App\Shared\Parties;

use App\Core\Auth;
use App\Shared\Schema\PartySchemaSupport;
use PDO;

final class PartyLedgerSupport
{
    public static function autoCode(PDO $pdo, int $partyId): void
    {
        if ($partyId <= 0) {
            return;
        }

        $auto = 'P' . str_pad((string) $partyId, 5, '0', STR_PAD_LEFT);
        $pdo->prepare("UPDATE parties SET code=? WHERE id=? AND (code IS NULL OR code='')")
            ->execute([$auto, $partyId]);
    }

    public static function addLedger(PDO $pdo, int $partyId, string $docType, int $docId, ?string $docNo, string $docDate, float $debit, float $credit, ?string $notes): void
    {
        PartySchemaSupport::ensurePartyLedgerSchema($pdo);
        $pdo->prepare("INSERT INTO party_ledger (party_id, doc_type, doc_id, doc_no, doc_date, debit, credit, notes, created_by)
                       VALUES (?,?,?,?,?,?,?,?,?)")
            ->execute([
                $partyId,
                $docType,
                $docId,
                $docNo,
                $docDate,
                $debit,
                $credit,
                $notes,
                Auth::id(),
            ]);
    }

    public static function balance(PDO $pdo, int $partyId, string $beforeDate): float
    {
        PartySchemaSupport::ensurePartyLedgerSchema($pdo);
        $st = $pdo->prepare("SELECT COALESCE(SUM(debit-credit),0) bal FROM party_ledger WHERE party_id=? AND doc_date < ?");
        $st->execute([$partyId, $beforeDate]);
        $row = $st->fetch();

        return (float) ($row['bal'] ?? 0);
    }
}
