<?php

include '../Members/short.php';
if (isset($_SESSION['message'])) {
    echo "<p>" . $_SESSION['message'] . "</p>";
    unset($_SESSION['message']); // Clear it after displaying
}
$mid = (int)$_SESSION['Mid'];
$message = "";

function calculate_total_loan($original_amount, $loan_date) {
    $loan_start = new DateTime($loan_date);
    $now = new DateTime();
    $interval = $loan_start->diff($now);
    $months_passed = $interval->y * 12 + $interval->m;
    $base_duration = 3;

    if ($months_passed <= 0) return $original_amount;

    if ($months_passed <= $base_duration) {
        return round($original_amount * pow((1 + 0.03), $months_passed), 2);
    } else {
        $total = $original_amount * pow((1 + 0.03), $base_duration);
        $total *= pow((1 + 0.06), $months_passed - $base_duration);
        return round($total, 2);
    }
}

if (isset($_POST['pay_loan_id'])) {
    $loan_id = $_POST['pay_loan_id'];
    $stmt = $conn->prepare("SELECT LAmount, LDate, TotalAmount FROM loan_amount WHERE LoanID = ? AND Mid = ? AND LoanStatus = 'Not_Paid'");
    $stmt->bind_param("ii", $loan_id, $mid);
    $stmt->execute();
    $loan_result = $stmt->get_result();

    if ($loan = $loan_result->fetch_assoc()) {
        $total_loan_amount = $loan['TotalAmount'];
        $balance_stmt = $conn->prepare("SELECT Amount FROM balance WHERE Mid = ?");
        $balance_stmt->bind_param("i", $mid);
        $balance_stmt->execute();
        $balance_result = $balance_stmt->get_result();

        if ($balance = $balance_result->fetch_assoc()) {
            $balance_amount = $balance['Amount'];
            if ($balance_amount >= $total_loan_amount) {
                $conn->begin_transaction();
                try {
                    $new_balance = $balance_amount - $total_loan_amount;
                    $update_balance = $conn->prepare("UPDATE balance SET Amount = ? WHERE Mid = ?");
                    $update_balance->bind_param("di", $new_balance, $mid);
                    $update_balance->execute();

                    $update_loan = $conn->prepare("UPDATE loan_amount SET LoanStatus = 'Paid', ReturnDate = CURDATE() WHERE LoanID = ?");
                    $update_loan->bind_param("i", $loan_id);
                    $update_loan->execute();

                    $conn->commit();
                    $message = "Loan ID $loan_id has been successfully paid!";
                } catch (Exception $e) {
                    $conn->rollback();
                    $message = "Error during payment: " . $e->getMessage();
                }
            } else {
                $message = "Insufficient balance to pay the loan.";
            }
        } else {
            $message = "Balance record not found.";
        }
    } else {
        $message = "Invalid or already paid loan.";
    }
}

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()) {
            $message = "Loan request submitted!";
        } else {
            $message = "Error: " . $stmt->error;
        }
    } else {
        $message = "Please fill in all fields.";
    }
}

$loans = [];
$stmt = $conn->prepare("SELECT * FROM loan_amount WHERE Mid = ? ORDER BY LDate DESC");
$stmt->bind_param("i", $mid);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $loans[] = $row;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Loan Request</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 min-h-screen relative">
<?php include '../includes/navbar.php'; ?>
<div class="flex items-center justify-center p-6">
    <div class="bg-white p-8 rounded-xl shadow-2xl max-w-5xl w-full">
        <?php if ($message): ?>
            <div class="<?php echo (strpos($message, 'Error') || strpos($message, 'Invalid') || strpos($message, 'Insufficient')) !== false ? 'bg-red-100 text-red-700' : 'bg-green-100 text-green-700'; ?> p-4 mb-4 border rounded">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>
        <h2 class="text-3xl font-extrabold text-center text-gray-800 mb-6">📋 Your Existing Loans</h2>
        <div class="overflow-x-auto rounded-lg border border-gray-300">
            <?php if (count($loans) > 0): ?>
                <table class="w-full text-sm text-left">
                    <thead class="bg-gray-100 text-gray-700 font-semibold uppercase text-xs">
                        <tr>
                            <th class="px-4 py-3 border">Loan ID</th>
                            <th class="px-4 py-3 border">Original</th>
                            <th class="px-4 py-3 border">Current Total</th>
                            <th class="px-4 py-3 border">Date</th>
                            <th class="px-4 py-3 border">Status</th>
                            <th class="px-4 py-3 border">Return Date</th>
                            <th class="px-4 py-3 border">Reason</th>
                            <th class="px-4 py-3 border">Action</th>
                        </tr>
                    </thead>
                    <tbody class="text-gray-800">
                        <?php foreach ($loans as $loan): ?>
                            <tr class="hover:bg-gray-50">
                                <td class="px-4 py-2 border"><?php echo $loan['LoanID']; ?></td>
                                <td class="px-4 py-2 border"><?php echo number_format($loan['LAmount'], 2); ?></td>
                                <td class="px-4 py-2 border"><?php echo number_format($loan['TotalAmount'], 2); ?></td>
                                <td class="px-4 py-2 border"><?php echo $loan['LDate']; ?></td>
                                <td class="px-4 py-2 border"><?php echo $loan['LoanStatus']; ?></td>
                                <td class="px-4 py-2 border"><?php echo $loan['ReturnDate'] ?? 'N/A'; ?></td>
                                <td class="px-4 py-2 border"><?php echo htmlspecialchars($loan['LoanReason']); ?></td>
                                <td class="px-4 py-2 border">
                                    <?php if ($loan['LoanStatus'] == 'Not_Paid'): ?>
                                        <form method="POST" action="">
                                            <input type="hidden" name="pay_loan_id" value="<?php echo $loan['LoanID']; ?>" />
                                            <button type="submit" class="bg-green-600 hover:bg-green-700 text-white text-sm px-3 py-1 rounded transition">
                                                Pay Loan
                                            </button>
                                        </form>
                                    <?php elseif ($loan['LoanStatus'] == 'Pending'): ?>
                                        <span class="text-yellow-600 font-semibold">Pending</span>
                                    <?php else: ?>
                                        <span class="text-gray-500">Paid</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p class="text-center text-gray-600 py-4">No loan records found.</p>
            <?php endif; ?>
        </div>
    </div>
</div>
<!-- Floating Button -->
<button onclick="openLoanPage()"
    class="fixed bottom-6 right-6 bg-blue-600 hover:bg-blue-700 text-white px-5 py-3 rounded-full shadow-lg text-sm font-semibold transition duration-200 z-50">
    + Request Loan
</button>

<script>
function openLoanPage() {
    window.location.href = 'rloan.php'; // Redirect to the rloan.php page
}
</script>
</body>
</html>