<?php
declare(strict_types=1);

namespace App\Modules\Inventory\Services;

use App\Core\App;

final class CreditLimitService
{
    public static function getCustomerCreditStatus(int $memberId): array
    {
        $db = App::getInstance()->db();

        $member = $db->selectOne(
            "SELECT credit_limit, credit_balance FROM members WHERE id = ?",
            [$memberId]
        );

        if (!$member) {
            return ['limit' => '0.00', 'used' => '0.00', 'available' => '0.00', 'exceeded' => false];
        }

        $limit = (string) ($member['credit_limit'] ?? '0.00');
        $used = (string) ($member['credit_balance'] ?? '0.00');
        $available = bcsub($limit, $used, 2);
        $exceeded = bccomp($used, $limit, 2) > 0;

        return [
            'limit' => $limit,
            'used' => $used,
            'available' => $available,
            'exceeded' => $exceeded,
        ];
    }

    public static function getSupplierCreditStatus(int $supplierId): array
    {
        $db = App::getInstance()->db();

        $supplier = $db->selectOne(
            "SELECT credit_limit, credit_balance FROM suppliers WHERE id = ?",
            [$supplierId]
        );

        if (!$supplier) {
            return ['limit' => '0.00', 'used' => '0.00', 'available' => '0.00', 'exceeded' => false];
        }

        $limit = (string) ($supplier['credit_limit'] ?? '0.00');
        $used = (string) ($supplier['credit_balance'] ?? '0.00');
        $available = bcsub($limit, $used, 2);
        $exceeded = bccomp($used, $limit, 2) > 0;

        return [
            'limit' => $limit,
            'used' => $used,
            'available' => $available,
            'exceeded' => $exceeded,
        ];
    }

    public static function checkCustomerCanTransact(int $memberId, string $amount): array
    {
        $status = self::getCustomerCreditStatus($memberId);

        if (bccomp($status['limit'], '0', 2) === 0) {
            return ['allowed' => true, 'message' => ''];
        }

        $newBalance = bcadd($status['used'], $amount, 2);
        if (bccomp($newBalance, $status['limit'], 2) > 0) {
            return [
                'allowed' => false,
                'message' => 'تجاوز الحد الائتماني — الحد: ' . $status['limit'] . ' | المستخدم: ' . $status['used'] . ' | المتاح: ' . $status['available'],
            ];
        }

        return ['allowed' => true, 'message' => ''];
    }

    public static function checkSupplierCanTransact(int $supplierId, string $amount): array
    {
        $status = self::getSupplierCreditStatus($supplierId);

        if (bccomp($status['limit'], '0', 2) === 0) {
            return ['allowed' => true, 'message' => ''];
        }

        $newBalance = bcadd($status['used'], $amount, 2);
        if (bccomp($newBalance, $status['limit'], 2) > 0) {
            return [
                'allowed' => false,
                'message' => 'تجاوز الحد الائتماني للمورد — الحد: ' . $status['limit'] . ' | المستخدم: ' . $status['used'] . ' | المتاح: ' . $status['available'],
            ];
        }

        return ['allowed' => true, 'message' => ''];
    }

    public static function updateCustomerBalance(int $memberId, string $amount, string $direction): void
    {
        $db = App::getInstance()->db();

        if ($direction === 'increase') {
            $db->query(
                "UPDATE members SET credit_balance = credit_balance + ? WHERE id = ?",
                [$amount, $memberId]
            );
        } else {
            $db->query(
                "UPDATE members SET credit_balance = GREATEST(0, credit_balance - ?) WHERE id = ?",
                [$amount, $memberId]
            );
        }
    }

    public static function updateSupplierBalance(int $supplierId, string $amount, string $direction): void
    {
        $db = App::getInstance()->db();

        if ($direction === 'increase') {
            $db->query(
                "UPDATE suppliers SET credit_balance = credit_balance + ? WHERE id = ?",
                [$amount, $supplierId]
            );
        } else {
            $db->query(
                "UPDATE suppliers SET credit_balance = GREATEST(0, credit_balance - ?) WHERE id = ?",
                [$amount, $supplierId]
            );
        }
    }

    public static function recalculateCustomerBalance(int $memberId): string
    {
        $db = App::getInstance()->db();

        $row = $db->selectOne(
            "SELECT COALESCE(SUM(debit) - SUM(credit), 0) as balance
             FROM customer_transactions WHERE member_id = ?",
            [$memberId]
        );

        $balance = (string) ($row['balance'] ?? '0.00');
        $db->update('members', ['credit_balance' => $balance], 'id = ?', [$memberId]);

        return $balance;
    }

    public static function recalculateSupplierBalance(int $supplierId): string
    {
        $db = App::getInstance()->db();

        $row = $db->selectOne(
            "SELECT COALESCE(SUM(credit) - SUM(debit), 0) as balance
             FROM supplier_transactions WHERE supplier_id = ?",
            [$supplierId]
        );

        $balance = (string) ($row['balance'] ?? '0.00');
        $db->update('suppliers', ['credit_balance' => $balance], 'id = ?', [$supplierId]);

        return $balance;
    }
}
