<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="jakarta.tags.core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>User Reports</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
    <style>
        body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; }
        .header { background-color: #333; color: white; padding: 15px 20px; display: flex; justify-content: space-between; align-items: center; }
        .header h1 { margin: 0; font-size: 24px; }
        .header nav ul { list-style: none; margin: 0; padding: 0; display: flex; }
        .header nav ul li { margin-left: 20px; }
        .header nav ul li a { color: white; text-decoration: none; font-weight: bold; }
        .header nav ul li a:hover { text-decoration: underline; }
        .container { padding: 20px; max-width: 1000px; margin: 20px auto; background-color: #fff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); }
        h2 { color: #007bff; margin-bottom: 20px; text-align: center; }
        .user-section { border: 1px solid #ddd; border-radius: 8px; margin-bottom: 25px; padding: 15px; background-color: #f9f9f9; position: relative; }
        .user-header { background-color: #e9ecef; padding: 10px; margin: -15px -15px 15px -15px; border-bottom: 1px solid #ddd; border-top-left-radius: 8px; border-top-right-radius: 8px; display: flex; justify-content: space-between; align-items: center; }
        .user-header h3 { margin: 0; color: #333; }
        .user-details p { margin: 5px 0; color: #555; }
        .insurance-table { width: 100%; border-collapse: collapse; margin-top: 15px; }
        .insurance-table th, .insurance-table td { border: 1px solid #eee; padding: 8px; text-align: left; }
        .insurance-table th { background-color: #f2f2f2; color: #333; font-size: 0.9em; }
        .no-insurance { text-align: center; color: #888; margin-top: 10px; }
        .no-users { text-align: center; color: #888; margin-top: 20px; }
        .back-link { display: block; text-align: center; margin-top: 20px; text-decoration: none; color: #007bff; }
        .back-link:hover { text-decoration: underline; }
        .info-message { text-align: center; color: #555; margin-top: 15px; font-style: italic; }

        /* Styles for PDF download button */
        .user-header .download-pdf-btn {
            background-color: #28a745; /* Green */
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 0.9em;
            white-space: nowrap; /* Prevents text wrap on button */
        }
        .user-header .download-pdf-btn:hover {
            background-color: #218838;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>Admin Panel</h1>
        <nav>
            <ul>
                <li><a href="/admin/dashboard">Dashboard</a></li>
                <li><a href="/logout">Logout</a></li>
            </ul>
        </nav>
    </div>

    <div class="container">
        <h2>User Reports</h2>
        <div class="info-message">
            <p>This report displays all registered users and the insurance policies they have bought.</p>
            <p>Click "Save as PDF" next to each user to download their individual report.</p>
        </div>

        <c:choose>
            <c:when test="${not empty userBoughtInsurances}">
                <c:forEach var="entry" items="${userBoughtInsurances}" varStatus="loop">
                    <c:set var="user" value="${entry.key}"/>
                    <c:set var="boughtInsurances" value="${entry.value}"/>

                    <%-- Assign a unique ID to each user section for PDF generation --%>
                    <div class="user-section" id="userReport-${loop.index}">
                        <div class="user-header">
                            <h3>User: <c:out value="${user.name}"/> (<c:out value="${user.emailId}"/>)</h3>
                            <button class="download-pdf-btn" data-target="userReport-${loop.index}">Save as PDF</button>
                        </div>
                        <div class="user-details">
                            <p><strong>Mobile:</strong> <c:out value="${user.mobileNumber}"/></p>
                            <p><strong>Role:</strong> <c:out value="${user.role}"/></p>
                        </div>

                        <c:choose>
                            <c:when test="${not empty boughtInsurances}">
                                <h4>Bought Insurance Policies:</h4>
                                <table class="insurance-table">
                                    <thead>
                                        <tr>
                                            <th>Transaction ID</th>
                                            <th>Plan Name</th>
                                            <th>Coverage</th>
                                            <th>Amount Per Year</th>
                                            <th>Purchase Date</th>
                                            <th>Expiry Date</th>
                                            <th>Claimed</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <c:forEach var="policy" items="${boughtInsurances}">
                                            <tr>
                                                <td><c:out value="${policy.id}"/></td>
                                                <td><c:out value="${policy.insurance.name}"/></td>
                                                <td><fmt:formatNumber value="${policy.insurance.coverage}" type="currency" currencySymbol="$"/></td>
                                                <td><fmt:formatNumber value="${policy.insurance.amountPerYear}" type="currency" currencySymbol="$"/></td>
                                                <td><fmt:formatDate value="${policy.purchaseDate}" pattern="yyyy-MM-dd"/></td> <%-- CORRECTED LINE --%>
                                                <td><fmt:formatDate value="${policy.expiryDate}" pattern="yyyy-MM-dd"/></td>   <%-- CORRECTED LINE --%>
                                                <td><c:out value="${policy.claimed ? 'Yes' : 'No'}"/></td>
                                            </tr>
                                        </c:forEach>
                                    </tbody>
                                </table>
                            </c:when>
                            <c:otherwise>
                                <p class="no-insurance">No insurance policies bought by this user.</p>
                            </c:otherwise>
                        </c:choose>
                    </div>
                </c:forEach>
            </c:when>
            <c:otherwise>
                <p class="no-users">No users found in the system.</p>
            </c:otherwise>
        </c:choose>

        <a href="/admin/dashboard" class="back-link">Back to Dashboard</a>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const downloadButtons = document.querySelectorAll('.download-pdf-btn');

            downloadButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const targetId = this.dataset.target;
                    const element = document.getElementById(targetId);

                    if (element) {
                        const opt = {
                            margin: 10,
                            filename: `${targetId}.pdf`,
                            image: { type: 'jpeg', quality: 0.98 },
                            html2canvas: { scale: 2 },
                            jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
                        };

                        html2pdf().set(opt).from(element).save();
                    } else {
                        console.error('Element not found for PDF generation:', targetId);
                        alert('Could not generate PDF for this user report.');
                    }
                });
            });
        });
    </script>
</body>
</html>