<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="jakarta.tags.core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Admin Dashboard</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
/* Define CSS Variables for theming */
:root {
    --primary-color: #2563eb;       /* Blue-600 */
    --secondary-color: #1e40af;      /* Blue-800 */
    --background-color: #f8fafc;    /* Cool Gray-50 */
    --card-background: #ffffff;    /* White */
    --text-primary: #1e293b;        /* Cool Gray-900 - Very dark grey, almost black */
    --text-secondary: #64748b;      /* Cool Gray-500 */
    --border-radius: 12px;
    --transition: all 0.3s ease;
}

/* Base Body Styles */
body {
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    background-color: var(--background-color);
    margin: 0;
    padding: 0;
    color: var(--text-primary);
    line-height: 1.6;
}

/* Header Styles */
.header {
    background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
    color: white;
    padding: 1.5rem 2rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    position: relative;
    z-index: 20; /* Ensure header is above most content */
}

.header h1 {
    margin: 0;
    font-size: 1.75rem;
    font-weight: 600;
}

/* --- Header Navigation & Dropdown Specific Styles (CLICK-BASED) --- */

/* Main header nav ul */
.header nav ul {
    list-style: none;
    margin: 0;
    padding: 0;
    display: flex;
    align-items: center;
    gap: 1.5rem; /* Space between main menu items */
}

/* Individual list item in main nav */
.header nav ul li {
    position: relative; /* Crucial for positioning the dropdown content relative to this li */
}

/* Main navigation link - target direct 'a' only for the main nav items */
.header nav ul li > a {
    color: white;
    text-decoration: none;
    font-weight: 500;
    padding: 0.75rem 1rem;
    border-radius: 6px;
    transition: var(--transition);
    display: block;
    white-space: nowrap;
    cursor: pointer; /* Indicate it's clickable */
}

.header nav ul li > a:hover {
    background-color: rgba(255, 255, 255, 0.15);
}

/* Visual indicator for dropdowns (the down arrow) */
.header nav ul li.has-dropdown > a::after {
    content: ' \25BC'; /* Unicode for a down arrow */
    font-size: 0.8em;
    vertical-align: middle;
    margin-left: 5px;
    transition: transform 0.3s ease;
}

/* Rotate arrow when dropdown is open */
.header nav ul li.has-dropdown.open > a::after {
    transform: rotate(180deg);
}

/* Dropdown Content Container (Initial state - Hidden by default for desktop) */
.dropdown-content {
    position: absolute;
    min-width: 220px;
    box-shadow: 0 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 100;
    border-radius: var(--border-radius);
    padding: 0.5rem 0;
    top: 100%;
    left: 0;
    background-color: var(--card-background); /* White background */

    /* Hidden properties for desktop */
    visibility: hidden;
    opacity: 0;
    transform: translateY(10px); /* Starts slightly below for slide-up effect */

    /* Transition for smooth hiding: opacity/transform fade out, then visibility changes */
    transition: opacity 0.3s ease-out, transform 0.3s ease-out, visibility 0s linear 0.3s;
    pointer-events: none; /* Prevents interaction when hidden */
}

/* Nested UL inside dropdown (for list items) */
.dropdown-content ul {
    list-style: none;
    padding: 0;
    margin: 0;
    display: block;
    flex-direction: column; /* Ensure the UL is displayed */
}

/* Individual links within the dropdown */
.dropdown-content a {
    color: var(--text-primary); /* Use primary text color (dark) */
    padding: 12px 16px;
    text-decoration: none;
    display: block; /* Make entire area clickable */
    text-align: left;
    transition: background-color 0.2s ease, color 0.2s ease;
    border-radius: 0;
    white-space: nowrap;
}

.dropdown-content a:hover {
    background-color: var(--primary-color); /* Highlight with primary color */
    color: #0000ff; /* White text on primary color background for contrast */
}

/* STATE FOR WHEN THE DROPDOWN IS OPEN (DESKTOP) */
.header nav ul li.open .dropdown-content {
    visibility: visible; /* Make visible instantly (0s delay) */
    opacity: 1; /* Fade in over 0.3s */
    transform: translateY(0); /* Slide up to final position over 0.3s */
    /* Transition for showing: visibility changes instantly, then opacity/transform animate */
    transition: opacity 0.3s ease-out, transform 0.3s ease-out, visibility 0s linear 0s;
    pointer-events: auto; /* Allow interaction */
    background-color: #ffffff; /* Reverted from !important */
}

/* Force text color when dropdown is open on desktop - Reverted from !important */
.header nav ul li.open .dropdown-content a {
    color: #0000ff; /* Black text on white background */
}


/* --- Container and General Layout --- */
.container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 2rem;
}

.welcome-message {
    background-color: var(--card-background);
    padding: 1.5rem;
    border-radius: var(--border-radius);
    margin-bottom: 2rem;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    font-size: 1.1rem;
    color: var(--text-primary);
}

.reports-overview-section {
    background-color: var(--card-background);
    padding: 2rem;
    border-radius: var(--border-radius);
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    margin-bottom: 2rem;
}

.reports-overview-section h3 {
    color: var(--primary-color);
    text-align: center;
    margin-bottom: 2rem;
    font-size: 1.5rem;
    font-weight: 600;
}

.chart-container {
    width: 45%; /* Adjusted for flexbox */
    min-width: 300px; /* Minimum width before wrapping */
    background-color: var(--card-background);
    padding: 1.5rem;
    border-radius: var(--border-radius);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.chart-container h4 {
    text-align: center;
    color: var(--text-primary);
    margin: 0 0 1.5rem 0;
    font-size: 1.2rem;
    font-weight: 500;
}

/* --- Scheduler controls moved inside the Reports dropdown --- */
.scheduler-controls {
    margin-top: 15px; /* Adjusted margin */
    padding-top: 10px;
    border-top: 1px solid #e2e8f0; /* Separator line */
    text-align: center;
    padding-bottom: 10px; /* Add some padding at the bottom */
}

.scheduler-controls button {
    padding: 8px 15px; /* Smaller padding for buttons inside dropdown */
    margin: 5px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 0.9rem; /* Smaller font size */
    font-weight: 600;
    transition: background-color 0.3s ease;
}

.scheduler-controls button.start {
    background-color: #28a745; /* Green */
    color: white;
}

.scheduler-controls button.start:hover {
    background-color: #218838;
}

.scheduler-controls button.stop {
    background-color: #dc3545; /* Red */
    color: white;
}

.scheduler-controls button.stop:hover {
    background-color: #c82333;
}

.scheduler-status {
    margin-top: 10px; /* Adjusted margin */
    padding: 8px; /* Smaller padding */
    border-radius: 5px;
    font-weight: 500;
    font-size: 0.85rem; /* Smaller font size */
    text-align: center;
}

.scheduler-status.success {
    background-color: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.scheduler-status.error {
    background-color: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

.scheduler-status.info {
    background-color: #d1ecf1;
    color: #0c5460;
    border: 1px solid #bee5eb;
}

/* --- Media Queries for Mobile Responsiveness --- */
@media (max-width: 768px) {
    .container {
        padding: 1rem;
    }

    .header {
        padding: 1rem;
        flex-direction: column;
        text-align: center;
        gap: 1rem;
        align-items: stretch;
    }

    .header h1 {
        margin-bottom: 1rem;
    }

    .header nav ul {
        flex-direction: column;
        gap: 0;
        width: 100%;
        align-items: stretch;
    }

    .header nav ul li {
        width: 100%;
        margin-bottom: 5px;
        position: static; /* Dropdowns will stack normally */
        padding-bottom: 0;
    }

    .header nav ul li > a { /* Target direct child 'a' */
        background-color: rgba(255, 255, 255, 0.08);
        margin-bottom: 5px;
        text-align: center;
    }

    /* Adjust dropdown for smaller screens (stacked layout on mobile) */
    .header nav ul li .dropdown-content {
        position: static; /* Stacks normally within the header */
        box-shadow: none;
        background-color: rgba(0, 0, 0, 0.1); /* Darker background for nested links */
        padding: 0;
        min-width: unset;
        width: 100%;
        border-radius: 0;
        transform: none; /* No transform needed for stacked items */
        opacity: 1; /* Always fully visible (mobile hides with max-height) */
        visibility: visible; /* Always visible (mobile hides with max-height) */
        max-height: 0; /* Initially collapsed for mobile */
        overflow: hidden; /* Hide overflow during collapse */
        transition: max-height 0.3s ease-out; /* Smooth slide transition for collapse/expand */
        pointer-events: none; /* Prevents interaction when collapsed */
    }

    /* To visually remove the gap caused by padding-top in .dropdown-content */
    .dropdown-content ul {
        margin-top: 0;
    }

    /* Expand dropdown on click/tap (for mobile, when `open` class is present) */
    .header nav ul li.open .dropdown-content {
        max-height: 500px; /* Sufficient height to show content */
        pointer-events: auto; /* Allow interaction */
    }

    .dropdown-content a {
        color: white; /* Match header link color for mobile */
        padding-left: 2.5rem; /* Indent for sub-items */
        background-color: transparent;
        border-radius: 0;
        margin-top: 0;
        padding-top: 8px;
        padding-bottom: 8px;
        text-align: left;
    }
    .dropdown-content a:hover {
        background-color: rgba(255, 255, 255, 0.2);
    }

    .scheduler-controls {
        border-top: none;
        padding-top: 10px;
    }
}
</style>
</head>
<body>
    <div class="header">
        <h1>Admin Dashboard</h1>
        <nav>
            <ul>
                <%-- Added 'has-dropdown' class to li elements for JavaScript targeting --%>
                <li class="has-dropdown">
                    <a href="#">Insurance Management</a>
                    <div class="dropdown-content">
                        <ul>
                            <li><a href="${pageContext.request.contextPath}/admin/insurance/viewAll">View All Insurance</a></li>
                            <li><a href="${pageContext.request.contextPath}/admin/insurance/add">Add New Insurance</a></li>
                            <li><a href="${pageContext.request.contextPath}/admin/insurance/manageClaims">Manage Claimed Insurance</a></li>
                            <li><a href="${pageContext.request.contextPath}/viewEnquiries">View All Enquiries</a></li>
                        </ul>
                    </div>
                </li>
                <li class="has-dropdown">
                    <a href="#">Payments</a>
                    <div class="dropdown-content">
                        <ul>
                            <li><a href="${pageContext.request.contextPath}/admin/payments/viewAll">View All Payments</a></li>
                            <li><a href="${pageContext.request.contextPath}/admin/payments/settle">Settle Received Payments</a></li>
                        </ul>
                    </div>
                </li>
                <li class="has-dropdown">
                    <a href="#">Agents</a>
                    <div class="dropdown-content">
                        <ul>
                            <li><a href="${pageContext.request.contextPath}/admin/agents/manage">Manage Agents</a></li>
                            <li><a href="${pageContext.request.contextPath}/admin/agents/details">Agent Details</a></li>
                        </ul>
                    </div>
                </li>
                <li class="has-dropdown">
                    <a href="#">Reports</a>
                    <div class="dropdown-content">
                        <ul>
                            <li><a href="${pageContext.request.contextPath}/admin/allBoughtInsurances">View All Bought Insurances</a></li>
                            <li><a href="${pageContext.request.contextPath}/admin/reports/agent">Agent Reports</a></li>
                            <li><a href="${pageContext.request.contextPath}/admin/reports/user">User Reports</a></li>
                            <li><a href="${pageContext.request.contextPath}/admin/reports/claim">Claim Reports</a></li>
                        </ul>
                        <div class="scheduler-controls">
                            <button id="scheduleReportButton" class="start">Schedule Daily Report</button>
                            <button id="stopReportButton" class="stop">Stop Daily Report</button>
                            <div id="schedulerStatus" class="scheduler-status"></div>
                        </div>
                    </div>
                </li>
                <li>Welcome, <c:out value="${loggedInAdmin.name}" />!
                </li>
                <li><a href="${pageContext.request.contextPath}/homepage">Logout</a></li>
            </ul>
        </nav>
    </div>

    <div class="container">
        <p class="welcome-message">
            Hello,
            <c:out value="${loggedInAdmin.name}" />
            ! Welcome to your Admin Portal.
        </p>

        <div class="reports-overview-section">
            <h3>Insurance Reports Overview</h3>
            <div
                style="display: flex; flex-wrap: wrap; justify-content: space-around; gap: 20px;">
                <div class="chart-container">
                    <h4>Insurance Type Distribution</h4>
                    <canvas id="insuranceTypeChart"></canvas>
                </div>
                <div class="chart-container">
                    <h4>Monthly New Policies Sold</h4>
                    <canvas id="monthlyPoliciesChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Data for Insurance Type Distribution (Pie Chart)
        const insuranceTypeData = {
            labels : [ 'Life Insurance', 'Health Insurance', 'Auto Insurance',
                    'Home Insurance', 'Travel Insurance' ],
            datasets : [ {
                label : 'Number of Policies',
                data : [ 450, 300, 200, 150, 80 ], // Example data
                backgroundColor : [ 'rgba(255, 99, 132, 0.7)',
                        'rgba(54, 162, 235, 0.7)', 'rgba(255, 206, 86, 0.7)',
                        'rgba(75, 192, 192, 0.7)', 'rgba(153, 102, 255, 0.7)' ],
                borderColor : [ 'rgba(255, 99, 132, 1)',
                        'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)',
                        'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)' ],
                borderWidth : 1
            } ]
        };

        // Configuration for Insurance Type Distribution Chart
        const insuranceTypeConfig = {
            type : 'pie',
            data : insuranceTypeData,
            options : {
                responsive : true,
                plugins : {
                    legend : {
                        position : 'top',
                    },
                    title : {
                        display : false,
                        text : 'Insurance Type Distribution'
                    }
                }
            },
        };

        // Render Insurance Type Distribution Chart
        const insuranceTypeChart = new Chart(document
                .getElementById('insuranceTypeChart'), insuranceTypeConfig);

        // Data for Monthly New Policies Sold (Line Chart)
        const monthlyPoliciesData = {
            labels : [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
                    'Sep', 'Oct', 'Nov', 'Dec' ],
            datasets : [ {
                label : 'New Policies Sold',
                data : [ 120, 150, 180, 160, 200, 230, 210, 250, 280, 270, 300,
                        320 ], // Example data
                backgroundColor : 'rgba(75, 192, 192, 0.6)',
                borderColor : 'rgba(75, 192, 192, 1)',
                borderWidth : 2,
                tension : 0.4, // Smooth line
                fill : false
            } ]
        };

        // Configuration for Monthly New Policies Sold Chart
        const monthlyPoliciesConfig = {
            type : 'line',
            data : monthlyPoliciesData,
            options : {
                responsive : true,
                plugins : {
                    legend : {
                        position : 'top',
                    },
                    title : {
                        display : false,
                        text : 'Monthly New Policies Sold'
                    }
                },
                scales : {
                    y : {
                        beginAtZero : true,
                        title : {
                            display : true,
                            text : 'Number of Policies'
                        }
                    },
                    x : {
                        title : {
                            display : true,
                            text : 'Month'
                        }
                    }
                }
            },
        };

        // Render Monthly New Policies Sold Chart
        const monthlyPoliciesChart = new Chart(document
                .getElementById('monthlyPoliciesChart'), monthlyPoliciesConfig);

        // --- Dropdown Click Logic ---
        $(document).ready(function() {
            // Toggle dropdown on click of the main nav item's link
            $('.header nav ul li.has-dropdown > a').on('click', function(event) {
                event.preventDefault(); // Prevent default link behavior
                event.stopPropagation(); // Stop click from propagating to document body

                var $parentLi = $(this).parent('li.has-dropdown');

                // Close any other open dropdowns
                $('.header nav ul li.has-dropdown').not($parentLi).removeClass('open');

                // Toggle the 'open' class on the clicked parent li
                $parentLi.toggleClass('open');
            });

            // Close dropdowns when clicking anywhere outside the dropdown
            $(document).on('click', function(event) {
                // If the click is NOT inside any dropdown or its trigger
                if (!$(event.target).closest('.header nav ul li.has-dropdown').length) {
                    $('.header nav ul li.has-dropdown').removeClass('open');
                }
            });

            // Prevent closing the dropdown when clicking inside the dropdown content itself
            $('.dropdown-content').on('click', function(event) {
                event.stopPropagation();
            });

            // --- Scheduler Buttons Logic ---
            function updateStatus(message, type) {
                $('#schedulerStatus').text(message)
                .removeClass('success error info') // Remove all previous classes
                .addClass(type); // Add the new type class
            }

            $('#scheduleReportButton').click(function(event) {
                event.stopPropagation(); // Prevent dropdown from closing if this button is clicked
                updateStatus('Scheduling report...', 'info');
                $.ajax({
                    url: '${pageContext.request.contextPath}/admin/scheduleDailyReport',
                    type: 'POST',
                    success: function(response) {
                        if (response.success) {
                            updateStatus(response.message, 'success');
                        } else {
                            updateStatus('Error: ' + response.message, 'error');
                        }
                    },
                    error: function(xhr, status, error) {
                        updateStatus('An AJAX error occurred: ' + error, 'error');
                        console.error("AJAX Error:", status, error, xhr.responseText);
                    }
                });
            });

            $('#stopReportButton').click(function(event) {
                event.stopPropagation(); // Prevent dropdown from closing if this button is clicked
                updateStatus('Stopping scheduler...', 'info');
                $.ajax({
                    url: '${pageContext.request.contextPath}/admin/stopDailyReport',
                    type: 'POST',
                    success: function(response) {
                        if (response.success) {
                            updateStatus(response.message, 'success');
                        } else {
                            updateStatus('Error: ' + response.message, 'error');
                        }
                    },
                    error: function(xhr, status, error) {
                        updateStatus('An AJAX error occurred: ' + error, 'error');
                        console.error("AJAX Error:", status, error, xhr.responseText);
                    }
                });
            });
        });
    </script>
</body>
</html>