<?php
declare(strict_types=1);
session_start();

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

// Authentication check
if (!isset($_SESSION['Mid'])) {
    echo "<p>Please login to view this page.</p>";
    exit;
}

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;

    public static function calculate(
        float $saving,
        float $balance,
        array $loans,
        ?string $currency = null
    ): array {
        if (empty($loans)) {
            $base_limit = min($saving * 0.5, $balance * 0.3);
            return [
                'amount' => round($base_limit, 2),
                'score' => 0,
                'currency' => $currency,
                'breakdown' => ['message' => 'No loan history available']
            ];
        }

        $metrics = self::analyzeLoans($loans);

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

        $composite_score = self::calculateCompositeScore($scores);

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

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

    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['Amount'];

            $start = new DateTime($loan['LoanStartDate']);
            $end = new DateTime($loan['LoanEndDate']);
            $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'] / $metrics['total_loans'];
        return $metrics;
    }

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

    private static function calculateStabilityScore(array $metrics): float {
        $avg_tenure = $metrics['total_tenure_months'] / $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 {
        return (
            self::WEIGHTS['timeliness'] * $scores['timeliness'] +
            self::WEIGHTS['stability'] * $scores['stability'] +
            self::WEIGHTS['financial_health'] * $scores['financial_health'] +
            self::WEIGHTS['risk'] * $scores['risk']
        );
    }

    private static function calculateRecommendedAmount(
        float $saving,
        float $balance,
        float $avg_loan,
        float $score
    ): float {
        $max_base = max($saving * 1.2, $balance * 0.8, $avg_loan * 3);
        return round($max_base * ($score / 10), 2);
    }
}

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 Amount, LoanStatus, LoanStartDate, LoanEndDate 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.');
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Recommended Loan</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <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">
                        Based on your financial profile and repayment history
                    </p>
                </div>

                <div class="bg-gray-50 p-4 rounded">
                    <h3 class="font-semibold mb-2">Score Breakdown</h3>
                    <div class="grid grid-cols-2 gap-2">
                        <div>
                            <span class="text-sm text-gray-500">Timeliness</span>
                            <div class="h-2 bg-gray-200 rounded-full mt-1">
                                <div class="h-2 bg-blue-500 rounded-full"
                                     style="width: <?= ($result['breakdown']['timeliness'] ?? 0) * 10 ?>%"></div>
                            </div>
                        </div>
                        <div>
                            <span class="text-sm text-gray-500">Stability</span>
                            <div class="h-2 bg-gray-200 rounded-full mt-1">
                                <div class="h-2 bg-green-500 rounded-full"
                                     style="width: <?= ($result['breakdown']['stability'] ?? 0) * 10 ?>%"></div>
                            </div>
                        </div>
                        <div>
                            <span class="text-sm text-gray-500">Financial Health</span>
                            <div class="h-2 bg-gray-200 rounded-full mt-1">
                                <div class="h-2 bg-purple-500 rounded-full"
                                     style="width: <?= ($result['breakdown']['financial_health'] ?? 0) * 10 ?>%"></div>
                            </div>
                        </div>
                        <div>
                            <span class="text-sm text-gray-500">Risk</span>
                            <div class="h-2 bg-gray-200 rounded-full mt-1">
                                <div class="h-2 bg-yellow-500 rounded-full"
                                     style="width: <?= ($result['breakdown']['risk'] ?? 0) * 10 ?>%"></div>
                            </div>
                        </div>
                    </div>
                </div>
            <?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>
