<?php
declare(strict_types=1);


// Database connection
include '../Members/short.php';

// Authentication check
if (!isset($_SESSION['Mid'])) {
    echo "<p>Please login to view this page.</p>";
    exit;
}
$message = "";
final class LoanRecommender {
    private const WEIGHTS = [
        'timeliness' => 0.35,
        'stability' => 0.25,
        'financial_health' => 0.25,
        'risk' => 0.15
    ];

    private const TIME_DECAY_RATE = 0.5;
    private const SAVINGS_FACTOR = 0.5;
    private const BALANCE_FACTOR = 0.3;
    private const LOAN_HISTORY_FACTOR = 1.5;
    private const MAX_SAVINGS_MULTIPLIER = 1.5;
    private const MAX_BALANCE_MULTIPLIER = 1.0;

    public static function calculate(
        float $saving,
        float $balance,
        array $loans,
        ?string $currency = null
    ): array {
        $metrics = !empty($loans) ? self::analyzeLoans($loans) : [
            'total_loans' => 0,
            'avg_loan' => 0
        ];

        $scores = [
            'timeliness' => empty($loans) ? 5.0 : self::calculateTimelinessScore($metrics),
            'stability' => empty($loans) ? 5.0 : self::calculateStabilityScore($metrics),
            'financial_health' => self::calculateFinancialHealthScore($saving, $balance),
            'risk' => empty($loans) ? 5.0 : self::calculateRiskScore($metrics)
        ];

        $composite_score = self::calculateCompositeScore($scores);
        $absolute_max = self::calculateAbsoluteMax($saving, $balance);
        $recommended = self::calculateRecommendedAmount(
            $saving,
            $balance,
            $metrics['avg_loan'],
            $composite_score,
            $absolute_max
        );

        return [
            'amount' => round($recommended, 2),
            'score' => round($composite_score, 2),
            'max_allowed' => round($recommended, 2),
            'currency' => $currency,
            'breakdown' => array_merge($scores, [
                'weights' => self::WEIGHTS,
                'absolute_max' => round($absolute_max, 2)
            ])
        ];
    }

    private static function calculateAbsoluteMax(float $saving, float $balance): float {
        return min(
            $saving * self::MAX_SAVINGS_MULTIPLIER,
            $balance * self::MAX_BALANCE_MULTIPLIER
        );
    }

    private static function calculateRecommendedAmount(
        float $saving,
        float $balance,
        float $avg_loan,
        float $score,
        float $absolute_max
    ): float {
        $base_amount = max(
            $saving * self::SAVINGS_FACTOR,
            $balance * self::BALANCE_FACTOR,
            $avg_loan * self::LOAN_HISTORY_FACTOR
        );
        return min($base_amount * ($score / 10), $absolute_max);
    }

    private static function analyzeLoans(array $loans): array {
        $metrics = [
            'total_loans' => count($loans),
            'timely_payments' => 0,
            'defaulted_loans' => 0,
            'late_payments' => 0,
            'total_loan_amount' => 0.0,
            'total_tenure_months' => 0,
            'recent_defaults' => 0.0,
            'recent_loans' => 0
        ];

        $now = new DateTime();

        foreach ($loans as $loan) {
            $metrics['total_loan_amount'] += (float)$loan['LAmount'];

            $start = new DateTime($loan['LDate']);
            $end = new DateTime($loan['LoanDate']);
            $interval = $end->diff($start);
            $months = $interval->y * 12 + $interval->m + ($interval->d > 0 ? 1 : 0);
            $metrics['total_tenure_months'] += $months;

            $loan_age_years = $now->diff($start)->y;
            $time_weight = exp(-self::TIME_DECAY_RATE * $loan_age_years);

            switch ($loan['LoanStatus']) {
                case 'Paid':
                    $metrics['timely_payments']++;
                    break;
                case 'Default':
                    $metrics['defaulted_loans']++;
                    if ($loan_age_years < 2) {
                        $metrics['recent_defaults'] += $time_weight;
                        $metrics['recent_loans']++;
                    }
                    break;
                case 'Delayed':
                    $metrics['late_payments']++;
                    break;
            }
        }

        $metrics['avg_loan'] = $metrics['total_loan_amount'] / max(1, $metrics['total_loans']);
        return $metrics;
    }

    private static function calculateTimelinessScore(array $metrics): float {
        $payment_ratio = $metrics['timely_payments'] / max(1, $metrics['total_loans']);
        $payment_score = 10 * $payment_ratio;
        $default_penalty = 10 * (1 - exp(-3 * $metrics['defaulted_loans'] / max(1, $metrics['total_loans'])));
        $late_penalty = 5 * ($metrics['late_payments'] / max(1, $metrics['total_loans']));
        return max(0, min(10, $payment_score - $default_penalty - $late_penalty));
    }

    private static function calculateStabilityScore(array $metrics): float {
        $avg_tenure = $metrics['total_tenure_months'] / max(1, $metrics['total_loans']);
        return min(10, ($avg_tenure / 36) * 10);
    }

    private static function calculateFinancialHealthScore(float $saving, float $balance): float {
        $savings_ratio = ($balance > 0) ? $saving / $balance : 0;
        return min(10, $savings_ratio * (10 / 1.5));
    }

    private static function calculateRiskScore(array $metrics): float {
        $recent_risk = ($metrics['recent_loans'] > 0)
            ? 10 * (1 - exp(-5 * ($metrics['recent_defaults'] / $metrics['recent_loans'])))
            : 0;
        return max(0, 10 - $recent_risk);
    }

    private static function calculateCompositeScore(array $scores): float {
        $weighted_sum = 0;
        foreach (self::WEIGHTS as $factor => $weight) {
            $weighted_sum += $weight * $scores[$factor];
        }
        return max(0, min(10, $weighted_sum));
    }
}

function fetchUserFinancialData(mysqli $conn, int $mid): array {
    $data = ['saving' => 0, 'balance' => 0, 'loans' => []];

    $stmt = $conn->prepare("SELECT SUM(Amount) AS total_saving FROM saving WHERE Mid = ?");
    if ($stmt) {
        $stmt->bind_param("i", $mid);
        $stmt->execute();
        $result = $stmt->get_result();
        $data['saving'] = (float)($result->fetch_assoc()['total_saving'] ?? 0);
        $stmt->close();
    }

    $stmt = $conn->prepare("SELECT Amount FROM balance WHERE Mid = ?");
    if ($stmt) {
        $stmt->bind_param("i", $mid);
        $stmt->execute();
        $result = $stmt->get_result();
        $data['balance'] = (float)($result->fetch_assoc()['Amount'] ?? 0);
        $stmt->close();
    }

    $stmt = $conn->prepare("SELECT LAmount, LoanStatus, LDate, LoanDate FROM loan_amount WHERE Mid = ?");
    if ($stmt) {
        $stmt->bind_param("i", $mid);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $data['loans'][] = $row;
        }
        $stmt->close();
    }

    return $data;
}

$mid = (int)$_SESSION['Mid'];
$data = fetchUserFinancialData($conn, $mid);
$result = LoanRecommender::calculate($data['saving'], $data['balance'], $data['loans'], 'Rs.');
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['pay_loan_id'])) {
    $amount = $_POST['amount'];
    $reason = $_POST['reason'];
    $date = date('Y-m-d');

    if (!empty($amount) && !empty($reason)) {
        $stmt = $conn->prepare("INSERT INTO loan_amount (LAmount, LDate, Mid, LoanStatus, LoanReason) VALUES (?, ?, ?, 'Pending', ?)");
        $stmt->bind_param("dsis", $amount, $date, $mid, $reason);
        if ($stmt->execute()) {
            $_SESSION['message'] = "Loan request submitted!";
            header("Location: loan.php");
            exit;

        } else {
            $message = "Error: " . $stmt->error;
        }
    } else {
        $message = "Please fill in all fields.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Recommended Loan</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 min-h-screen flex flex-col">
    <?php include '../includes/navbar.php'; ?>

    <div class="flex justify-center items-center flex-grow">
        <div class="bg-white shadow-md p-8 rounded-lg w-full max-w-xl">
            <h1 class="text-2xl font-bold text-center text-gray-800 mb-6">Your Predicted Amount</h1>

            <div class="text-center mb-6">
                <div class="inline-block bg-blue-50 px-4 py-2 rounded-full">
                    <span class="font-semibold">Credit Score:</span>
                    <span class="text-blue-600 font-bold ml-1">
                        <?= number_format($result['score'], 2) ?>/10
                    </span>
                </div>
            </div>

            <?php if ($result['amount'] > 0): ?>
                <div class="bg-green-50 border-l-4 border-green-500 text-green-800 p-4 rounded mb-6">
                    <p class="font-semibold text-lg">Approved Loan Amount</p>
                    <p class="text-3xl font-bold mt-2">
                        <?= $result['currency'] ?> <?= number_format($result['amount'], 2) ?>
                    </p>
                    <p class="text-sm mt-2 text-green-600">
                        Maximum allowed: <?= $result['currency'] ?> <?= number_format($result['max_allowed'], 2) ?>
                    </p>
                </div>
                <!-- Add this right after the score breakdown section in your HTML -->
<div class="flex justify-center mb-6">
    <button id="requestLoanBtn" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-6 rounded-lg transition duration-200">
        Request This Loan
    </button>
</div>

<!-- Loan Request Modal -->
<div id="loanModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
    <div class="bg-white rounded-lg p-6 w-full max-w-md">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-xl font-bold text-gray-800">Loan Request Form</h3>
            <button id="closeModal" class="text-gray-500 hover:text-gray-700">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
            </button>
        </div>
        
        <form method="POST" action="rloan.php" id="loanForm" class="space-y-4">
            <input type="hidden" name="max_allowed" value="<?= $result['max_allowed'] ?>">
            
            <div>
                <label for="amount" class="block text-sm font-medium text-gray-700">
                    Loan Amount (<?= $result['currency'] ?>)
                    <span class="text-xs text-gray-500">Max: <?= number_format($result['max_allowed'], 2) ?></span>
                </label>
                <input type="number" step="0.01" name="amount" id="amount" required
                       class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                       value="<?= number_format($result['amount'], 2) ?>"
                       max="<?= number_format($result['max_allowed'], 2) ?>">
                <p id="amountError" class="text-red-500 text-xs mt-1 hidden">
                    Amount cannot exceed <?= $result['currency'] ?> <?= number_format($result['max_allowed'], 2) ?>
                </p>
            </div>
            
            <div>
                <label for="reason" class="block text-sm font-medium text-gray-700">Loan Reason</label>
                <textarea name="reason" id="reason" rows="3" required
                          class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                          placeholder="Briefly explain the purpose of this loan"></textarea>
            </div>
            
            <div class="bg-yellow-50 p-3 rounded-md">
                <p class="text-sm text-yellow-700">
                    <span class="font-semibold">Note:</span> 3% monthly interest rate. 
                    After 3 months, rate increases to 6% monthly until paid.
                </p>
            </div>
            
            <button type="submit" 
                    class="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 transition duration-200">
                Submit Loan Request
            </button>
        </form>
    </div>
</div>

<script>
    // Modal handling
    const modal = document.getElementById('loanModal');
    const openBtn = document.getElementById('requestLoanBtn');
    const closeBtn = document.getElementById('closeModal');
    const form = document.getElementById('loanForm');
    const amountInput = document.getElementById('amount');
    const errorMsg = document.getElementById('amountError');
    const maxAllowed = parseFloat("<?= $result['max_allowed'] ?>");

    openBtn.addEventListener('click', () => modal.classList.remove('hidden'));
    closeBtn.addEventListener('click', () => modal.classList.add('hidden'));
    window.addEventListener('click', (e) => e.target === modal && modal.classList.add('hidden'));

    // Real-time validation
    amountInput.addEventListener('input', () => {
        const value = parseFloat(amountInput.value) || 0;
        
        if (value > maxAllowed) {
            amountInput.classList.add('border-red-500');
            errorMsg.classList.remove('hidden');
        } else {
            amountInput.classList.remove('border-red-500');
            errorMsg.classList.add('hidden');
        }
    });

    // Form submission validation
    form.addEventListener('submit', (e) => {
        const value = parseFloat(amountInput.value) || 0;
        
        if (value > maxAllowed) {
            e.preventDefault();
            amountInput.classList.add('border-red-500');
            errorMsg.classList.remove('hidden');
            amountInput.focus();
        }
    });
</script>

                <!-- [Rest of your HTML remains the same] -->
            <?php else: ?>
                <div class="bg-yellow-50 border-l-4 border-yellow-500 text-yellow-800 p-4 rounded">
                    <p class="font-semibold">Recommendation Unavailable</p>
                    <p class="mt-1">We couldn't calculate a loan recommendation at this time.</p>
                    <p class="text-sm mt-2">Please improve your financial profile or contact support.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>