<?php
class LoanGuarantorship {
    private $pdo;

    public function __construct($pdo) {
        $this->pdo = $pdo;
    }

    // Fetch Loan Features
    private function getLoanFeatures($loanTypeCode) {
        $query = "SELECT basis_savings_account_type, max_loan_factor 
                  FROM loan_features WHERE type_code = :loanTypeCode";
        $stmt = $this->pdo->prepare($query);
        $stmt->execute(['loanTypeCode' => $loanTypeCode]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    // Get Member's Available Balance
    private function getMemberBalance($memberId, $accountType) {
        $query = "SELECT available_balance FROM member_accounts 
                  WHERE member_id = :memberId AND account_type = :accountType";
        $stmt = $this->pdo->prepare($query);
        $stmt->execute(['memberId' => $memberId, 'accountType' => $accountType]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result ? $result['available_balance'] : 0;
    }

    // Verify Guarantors' Balances
    private function verifyGuarantors($guarantors, $guaranteeAccountType, $requiredAmount) {
        $totalGuarantee = 0;
        foreach ($guarantors as $guarantorId) {
            $balance = $this->getMemberBalance($guarantorId, $guaranteeAccountType);
            $totalGuarantee += $balance;
        }
        return $totalGuarantee >= $requiredAmount;
    }

    // Determine Loan Eligibility & Guarantorship Requirement
    public function processLoanGuarantorship($memberId, $loanTypeCode, $requestedLoanAmount, $guarantors, $guaranteeAccountType) {
        $loanFeatures = $this->getLoanFeatures($loanTypeCode);
        if (!$loanFeatures) {
            return ["status" => false, "message" => "Invalid loan type."];
        }

        $basisSavingsAccount = $loanFeatures['basis_savings_account_type'];
        $maxLoanFactor = $loanFeatures['max_loan_factor'];
        $availableBalance = $this->getMemberBalance($memberId, $basisSavingsAccount);

        // Calculate Max Loan Eligibility
        $maxLoanEligibility = $availableBalance * $maxLoanFactor;
        $loanRequiringGuarantors = max(0, $requestedLoanAmount - $maxLoanEligibility);

        // If guarantors are required, verify their balances
        if ($loanRequiringGuarantors > 0) {
            $isGuarantorshipValid = $this->verifyGuarantors($guarantors, $guaranteeAccountType, $loanRequiringGuarantors);
            if (!$isGuarantorshipValid) {
                return ["status" => false, "message" => "Guarantors do not have sufficient balance."];
            }
        }

        return [
            "status" => true,
            "message" => "Loan eligibility verified.",
            "max_loan_eligibility" => $maxLoanEligibility,
            "loan_requiring_guarantors" => $loanRequiringGuarantors
        ];
    }
}
