<?php

class SettlementEngine
{
    private PDO $pdo;
    private int $companyId;

    public function __construct(PDO $pdo, int $companyId)
    {
        $this->pdo = $pdo;
        $this->companyId = $companyId;
    }

    /**
     * Get carry forward balance
     */
    public function getBalance(string $departmentCode): float
    {
        $stmt = $this->pdo->prepare("
            SELECT balance
            FROM manual_settlement_balances
            WHERE company_id = ? AND department_code = ?
            LIMIT 1
        ");

        $stmt->execute([$this->companyId, $departmentCode]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        return $row ? (float)$row['balance'] : 0.00;
    }

    /**
     * Update or Insert carry forward balance
     */
    public function setBalance(string $departmentCode, float $amount): void
    {
        $stmt = $this->pdo->prepare("
            INSERT INTO manual_settlement_balances (company_id, department_code, balance)
            VALUES (?, ?, ?)
            ON DUPLICATE KEY UPDATE balance = VALUES(balance)
        ");

        $stmt->execute([
            $this->companyId,
            $departmentCode,
            $amount
        ]);
    }

    /**
     * Main Processing Logic
     */
    public function process(string $departmentCode, float $monthTotal, bool $commit = false): array
    {
        $carry = $this->getBalance($departmentCode);
        $payable = $carry + $monthTotal;

        $status = '';
        $newBalance = 0;

        // Threshold rule
        if ($payable < 100) {
            $status = 'CARRY_FORWARD';
            $newBalance = $payable;
        } else {
            $status = 'READY';
            $newBalance = 0;
        }

        // Save updated balance
        if ($commit) {
    $this->setBalance($departmentCode, $newBalance);
}

        return [
            'department_code' => $departmentCode,
            'month_total'     => $monthTotal,
            'carry_in'        => $carry,
            'payable'         => $payable,
            'status'          => $status,
            'new_balance'     => $newBalance
        ];
    }
}