<?php include('layout/template-top.php'); ?>
<?php include('layout/header.php'); ?>

<style>
    body {
        background-color: #f4f7f6;
    }

    .main-container {
        padding-top: 80px;
    }

    .row {
        width: 100%;
    }

    /* Premium Filter Bar */
    .filter-bar {
        background: rgba(255, 255, 255, 0.9);
        backdrop-filter: blur(10px);
        border-radius: 12px;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.03);
        padding: 20px;
        margin-bottom: 30px;
        border: 1px solid rgba(0, 0, 0, 0.05);
        width: 100%;
    }

    .filter-bar .form-control {
        border-radius: 8px;
        border: 1px solid #e0e6ed;
        box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.02);
        font-size: 14px;
    }

    .filter-bar .btn-primary {
        border-radius: 8px;
        background: linear-gradient(135deg, #1a73e8, #0b51c5);
        border: none;
        box-shadow: 0 4px 10px rgba(26, 115, 232, 0.3);
        transition: transform 0.2s, box-shadow 0.2s;
    }

    .filter-bar .btn-primary:hover {
        transform: translateY(-1px);
        box-shadow: 0 6px 15px rgba(26, 115, 232, 0.4);
    }

    /* KPI Cards Premium Polish */
    .kpi-card {
        background: #fff;
        border-radius: 12px;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.03);
        padding: 25px 20px;
        margin-bottom: 25px;
        text-align: center;
        border: 1px solid rgba(0, 0, 0, 0.03);
        transition: transform 0.3s ease, box-shadow 0.3s ease;
        position: relative;
        overflow: hidden;
    }

    .kpi-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 12px 25px rgba(0, 0, 0, 0.08);
    }

    .kpi-card::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 4px;
        background: linear-gradient(90deg, #1a73e8, #00e396);
        opacity: 0;
        transition: opacity 0.3s;
    }

    .kpi-card:hover::before {
        opacity: 1;
    }

    .kpi-title {
        font-size: 12px;
        color: #888ea8;
        font-weight: 600;
        letter-spacing: 0.5px;
        margin-bottom: 10px;
        text-transform: uppercase;
    }

    .kpi-value {
        font-size: 28px;
        color: #0e1726;
        font-weight: 700;
    }

    .kpi-value.small-text {
        font-size: 16px;
        color: #1a73e8;
    }

    /* Chart Cards Premium Polish */
    .chart-card {
        background: #fff;
        border-radius: 12px;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.03);
        padding: 25px;
        margin-bottom: 25px;
        border: 1px solid rgba(0, 0, 0, 0.03);
        transition: box-shadow 0.3s ease;
    }

    .chart-card:hover {
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.06);
    }

    .chart-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 16px;
        color: #0e1726;
        font-weight: 700;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px dashed #e0e6ed;
    }

    .chart-filter {
        font-size: 12px;
        color: #5f6368;
        border: 1px solid #dadce0;
        border-radius: 4px;
        padding: 4px 8px;
        background: #fff;
        outline: none;
        font-weight: 500;

    }

    /* Vibrant Text Colors */
    .text-primary-gradient {
        background: -webkit-linear-gradient(#1a73e8, #0b51c5);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }

    .text-success-gradient {
        background: -webkit-linear-gradient(#00e396, #00b377);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }

    .text-warning-gradient {
        background: -webkit-linear-gradient(#feb019, #e59700);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }

    .text-danger-gradient {
        background: -webkit-linear-gradient(#ff4560, #d62d45);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }

    .text-info-gradient {
        background: -webkit-linear-gradient(#008ffb, #006ec1);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
</style>

<div class="main-container">
    <!-- <div class="pd-ltr-20 xs-pd-20-10"> -->

        <div class="page-header mb-30">
            <div class="row align-items-center">
                <div class="col-md-6 col-sm-12">
                    <div class="title">
                        <h4>Analytics Overview</h4>
                    </div>
                    <nav aria-label="breadcrumb" role="navigation">
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="<?php echo base_url(); ?>">Home</a></li>
                             <li class="breadcrumb-item active" aria-current="page">Analytics</li>
                        </ol>
                    </nav>
                </div>
            </div>
        </div>
        <!--========== Global Analytics ==========-->
        <div class="page-header mb-30">
            <!-- Part A: Global Analytics -->
            <h4 class="mb-3 text-primary-gradient" style="font-weight: 700;">Global Analytics</h4>
            <div class="row">

                <!-- 5. Monthly Lead Trend -->
                <div class="col-xl-6 col-lg-6 col-md-12">
                    <div class="chart-card">
                        <div class="chart-header">
                            <span>Lead Trends</span>
                            <select class="chart-filter" data-target="monthly_trend">
                                <option value="default">Default</option>
                                <option value="last_week">Last Week</option>
                                <option value="this_month">This Month</option>
                                <option value="3_months">3 Months</option>
                                <option value="6_months">6 Months</option>
                            </select>
                        </div>
                        <div id="chart-monthly-trend"></div>
                    </div>
                </div>

                <!-- 4. Branch-wise Lead Performance -->
                <div class="col-xl-6 col-lg-6 col-md-12">
                    <div class="chart-card">
                        <div class="chart-header">
                            <span>Branch Performance</span>
                            <select class="chart-filter" data-target="branch_perf">
                                <option value="default">Default</option>
                                <option value="last_week">Last Week</option>
                                <option value="this_month">This Month</option>
                                <option value="3_months">3 Months</option>
                                <option value="6_months">6 Months</option>
                            </select>
                        </div>
                        <div id="chart-branch-perf"></div>
                    </div>
                </div>
            </div>
        </div>

        <!--========== Deep Dive Analytics ==========-->
        <div class="page-header mb-30">
            <div class="col-md-6 col-sm-12">
                <div class="title">
                    <h4 class="mb-3 text-info-gradient" style="font-weight: 700; margin-top: 10px;">Deep Dive Analytics</h4>
                </div>
            </div>
            <!-- Global Filter Bar -->
            <div class="filter-bar">
                <form method="GET" action="<?php echo base_url('analytics'); ?>" class="row align-items-end">
                    <div class="col-md-2 mb-2 mb-md-0">
                        <label style="font-size: 12px; font-weight: 600; color: #888ea8;">From Date</label>
                        <input type="date" name="date_from" class="form-control" value="<?php echo $this->input->get('date_from'); ?>">
                    </div>
                    <div class="col-md-2 mb-2 mb-md-0">
                        <label style="font-size: 12px; font-weight: 600; color: #888ea8;">To Date</label>
                        <input type="date" name="date_to" class="form-control" value="<?php echo $this->input->get('date_to'); ?>">
                    </div>

                    <?php if ($this->session->userdata('role') == 'Admin'): ?>
                        <div class="col-md-3 mb-2 mb-md-0">
                            <label style="font-size: 12px; font-weight: 600; color: #888ea8;">Branch</label>
                            <select name="filter_branch_id" class="form-control">
                                <option value="">All Branches</option>
                                <?php foreach ($branches as $b): ?>
                                    <option value="<?php echo $b->branch_id; ?>" <?php echo ($this->input->get('filter_branch_id') == $b->branch_id) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($b->branch_name); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    <?php endif; ?>

                    <div class="col-md-3 mb-2 mb-md-0">
                        <label style="font-size: 12px; font-weight: 600; color: #888ea8;">Product</label>
                        <select name="filter_product_id" class="form-control">
                            <option value="">All Products</option>
                            <?php foreach ($products as $p): ?>
                                <option value="<?php echo $p->product_id; ?>" <?php echo ($this->input->get('filter_product_id') == $p->product_id) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($p->product_name); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-2 d-flex">
                        <button type="submit" class="btn btn-primary flex-grow-1 mr-1" style="padding: 10px;">Apply</button>
                        <a href="<?php echo base_url('analytics'); ?>" class="btn btn-outline-secondary flex-grow-1 ml-1" style="padding: 10px; display: flex; align-items: center; justify-content: center;">Reset</a>
                    </div>
                </form>
            </div>
            <!-- 20. Executive KPI Cards -->
            <div class="row">
                <div class="col-lg-3 col-md-6 col-sm-6">
                    <div class="kpi-card">
                        <div class="kpi-title">Total Leads</div>
                        <div class="kpi-value text-primary-gradient"><?php echo number_format($kpis['total_leads']); ?></div>
                    </div>
                </div>
                <div class="col-lg-3 col-md-6 col-sm-6">
                    <div class="kpi-card">
                        <div class="kpi-title">New Leads Today</div>
                        <div class="kpi-value text-info-gradient"><?php echo number_format($kpis['new_leads_today']); ?></div>
                    </div>
                </div>
                <div class="col-lg-3 col-md-6 col-sm-6">
                    <div class="kpi-card">
                        <div class="kpi-title">Converted Leads</div>
                        <div class="kpi-value text-success-gradient"><?php echo number_format($kpis['converted_leads']); ?></div>
                    </div>
                </div>
                <div class="col-lg-3 col-md-6 col-sm-6">
                    <div class="kpi-card">
                        <div class="kpi-title">Conversion Rate</div>
                        <div class="kpi-value text-warning-gradient"><?php echo $kpis['conversion_rate']; ?>%</div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-lg-2 col-md-4 col-sm-6">
                    <div class="kpi-card">
                        <div class="kpi-title">Upcoming F-Ups</div>
                        <div class="kpi-value text-info-gradient"><?php echo number_format($kpis['upcoming_followups']); ?></div>
                    </div>
                </div>
                <div class="col-lg-2 col-md-4 col-sm-6">
                    <div class="kpi-card">
                        <div class="kpi-title">Overdue F-Ups</div>
                        <div class="kpi-value text-danger-gradient"><?php echo number_format($kpis['overdue_followups']); ?></div>
                    </div>
                </div>
                <div class="col-lg-3 col-md-4 col-sm-12">
                    <div class="kpi-card">
                        <div class="kpi-title">Best Product</div>
                        <div class="kpi-value small-text"><?php echo htmlspecialchars($kpis['best_product']); ?></div>
                    </div>
                </div>
                <div class="col-lg-2 col-md-6 col-sm-12">
                    <div class="kpi-card">
                        <div class="kpi-title">Best Source</div>
                        <div class="kpi-value small-text"><?php echo htmlspecialchars($kpis['best_source']); ?></div>
                    </div>
                </div>
                <div class="col-lg-3 col-md-6 col-sm-12">
                    <div class="kpi-card">
                        <div class="kpi-title">Best Branch</div>
                        <div class="kpi-value small-text"><?php echo htmlspecialchars($kpis['best_branch']); ?></div>
                    </div>
                </div>
            </div>

            <div class="row">
                <!-- 1. Lead Funnel Analysis -->
                <div class="col-xl-6 col-lg-6 col-md-12">
                    <div class="chart-card">
                        <div class="chart-header">
                            <span>Lead Funnel Analysis</span>
                            <select class="chart-filter" data-target="funnel">
                                <option value="default">Default</option>
                                <option value="last_week">Last Week</option>
                                <option value="this_month">This Month</option>
                                <option value="3_months">3 Months</option>
                                <option value="6_months">6 Months</option>
                            </select>
                        </div>
                        <div id="chart-funnel"></div>
                    </div>
                </div>
                <!-- 3. Product-wise Conversion Rate -->
                <div class="col-xl-6 col-lg-6 col-md-12">
                    <div class="chart-card">
                        <div class="chart-header">
                            <span>Product-wise Conversion</span>
                            <select class="chart-filter" data-target="product_conv">
                                <option value="default">Default</option>
                                <option value="last_week">Last Week</option>
                                <option value="this_month">This Month</option>
                                <option value="3_months">3 Months</option>
                                <option value="6_months">6 Months</option>
                            </select>
                        </div>
                        <div id="chart-product-conv"></div>
                    </div>
                </div>
            </div>

            <div class="row">
                <!-- 2. Product-wise Lead Distribution -->
                <div class="col-xl-6 col-lg-6 col-md-12">
                    <div class="chart-card">
                        <div class="chart-header">
                            <span>Product Distribution</span>
                            <select class="chart-filter" data-target="product_dist">
                                <option value="default">Default</option>
                                <option value="last_week">Last Week</option>
                                <option value="this_month">This Month</option>
                                <option value="3_months">3 Months</option>
                                <option value="6_months">6 Months</option>
                            </select>
                        </div>
                        <div id="chart-product-dist"></div>
                    </div>
                </div>

                <!-- 11. Lead Status Distribution -->
                <div class="col-xl-6 col-lg-6 col-md-12">
                    <div class="chart-card">
                        <div class="chart-header">
                            <span>Lead Status Distribution</span>
                            <select class="chart-filter" data-target="status_dist">
                                <option value="default">Default</option>
                                <option value="last_week">Last Week</option>
                                <option value="this_month">This Month</option>
                                <option value="3_months">3 Months</option>
                                <option value="6_months">6 Months</option>
                            </select>
                        </div>
                        <div id="chart-status-dist"></div>
                    </div>
                </div>

                <!-- 9. Upcoming Follow-up Dashboard -->
                <div class="col-xl-12 col-lg-12 col-md-12">
                    <div class="chart-card">
                        <div class="chart-header">
                            <span>Follow-up Dashboard</span>
                            <select class="chart-filter" data-target="followup">
                                <option value="default">Default</option>
                                <option value="last_week">Last Week</option>
                                <option value="this_month">This Month</option>
                                <option value="3_months">3 Months</option>
                                <option value="6_months">6 Months</option>
                            </select>
                        </div>
                        <div id="chart-followup"></div>
                    </div>
                </div>
            </div>

        </div>

        <?php include('layout/footer.php'); ?>
    <!-- </div> -->
</div>

<?php include('layout/template-bottom.php'); ?>

<!-- ApexCharts JS -->
<script src="<?php echo base_url(); ?>assets/src/plugins/apexcharts/apexcharts.min.js"></script>

<script>
    document.addEventListener("DOMContentLoaded", function() {

        // Helper formatter
        const numFormatter = function(val) {
            return val;
        };

        // Premium Color Palette
        const colors = {
            primary: '#1a73e8',
            success: '#00e396',
            warning: '#feb019',
            danger: '#ff4560',
            info: '#008ffb',
            purple: '#775dd0',
            teal: '#00b8d9',
            coral: '#ff7a59'
        };

        const gradientOptions = {
            type: 'gradient',
            gradient: {
                shade: 'light',
                type: "vertical",
                shadeIntensity: 0.5,
                gradientToColors: undefined,
                inverseColors: true,
                opacityFrom: 0.85,
                opacityTo: 0.85,
                stops: [0, 100]
            }
        };

        // --- 1. Lead Funnel Analysis ---
        var funnelData = <?php echo json_encode($funnel_data); ?>;
        var funnelCategories = funnelData.map(f => f.stage);
        var funnelSeries = funnelData.map(f => parseInt(f.count));
        var optionsFunnel = {
            series: [{
                name: "Leads",
                data: funnelSeries
            }],
            chart: {
                type: 'bar',
                height: 350,
                toolbar: {
                    show: false
                }
            },
            plotOptions: {
                bar: {
                    borderRadius: 4,
                    horizontal: true,
                    barHeight: '70%',
                    isFunnel: true
                }
            },
            dataLabels: {
                enabled: true,
                formatter: numFormatter,
                dropShadow: {
                    enabled: true
                }
            },
            colors: [colors.primary],
            fill: gradientOptions,
            xaxis: {
                categories: funnelCategories
            }
        };
        var chartFunnel = new ApexCharts(document.querySelector("#chart-funnel"), optionsFunnel);
        chartFunnel.render();

        // --- 5. Monthly Lead Trend ---
        var monthlyData = <?php echo json_encode($monthly_trend); ?>;
        var optionsMonthly = {
            series: [{
                    name: "Generated",
                    data: monthlyData.map(m => parseInt(m.generated))
                },
                {
                    name: "Converted",
                    data: monthlyData.map(m => parseInt(m.converted))
                },
                {
                    name: "Lost",
                    data: monthlyData.map(m => parseInt(m.lost))
                }
            ],
            chart: {
                height: 350,
                type: 'area',
                toolbar: {
                    show: false
                },
                dropShadow: {
                    enabled: true,
                    top: 10,
                    left: 0,
                    blur: 5,
                    color: '#000',
                    opacity: 0.05
                }
            },
            stroke: {
                curve: 'smooth',
                width: 3
            },
            fill: {
                type: 'gradient',
                gradient: {
                    shadeIntensity: 1,
                    opacityFrom: 0.4,
                    opacityTo: 0.05,
                    stops: [0, 90, 100]
                }
            },
            xaxis: {
                categories: monthlyData.map(m => m.month_year)
            },
            colors: [colors.info, colors.success, colors.danger]
        };
        var chartMonthlyTrend = new ApexCharts(document.querySelector("#chart-monthly-trend"), optionsMonthly);
        chartMonthlyTrend.render();

        // --- 2. Product-wise Lead Distribution ---
        var prodDist = <?php echo json_encode($product_distribution); ?>;
        var optionsProdDist = {
            series: prodDist.map(p => parseInt(p.count)),
            chart: {
                type: 'donut',
                height: 320
            },
            labels: prodDist.map(p => p.product_name || 'Unknown'),
            legend: {
                position: 'bottom',
                fontSize: '13px'
            },
            plotOptions: {
                pie: {
                    donut: {
                        size: '65%'
                    }
                }
            },
            stroke: {
                width: 0
            },
            colors: [colors.primary, colors.success, colors.warning, colors.purple, colors.teal, colors.coral]
        };
        var chartProductDist = new ApexCharts(document.querySelector("#chart-product-dist"), optionsProdDist);
        chartProductDist.render();

        // --- 11. Lead Status Distribution ---
        var statDist = <?php echo json_encode($status_distribution); ?>;
        var optionsStatDist = {
            series: statDist.map(s => parseInt(s.count)),
            chart: {
                type: 'donut',
                height: 320
            },
            labels: statDist.map(s => s.lead_status),
            legend: {
                position: 'bottom',
                fontSize: '13px'
            },
            plotOptions: {
                pie: {
                    donut: {
                        size: '65%'
                    }
                }
            },
            stroke: {
                width: 0
            },
            colors: [colors.info, colors.teal, colors.warning, colors.danger, colors.success, colors.purple, colors.coral]
        };
        var chartStatusDist = new ApexCharts(document.querySelector("#chart-status-dist"), optionsStatDist);
        chartStatusDist.render();

        // --- 9. Upcoming Follow-up Dashboard ---
        var followup = <?php echo json_encode($followup_data); ?>;
        var followCategories = ['Overdue', 'Today', 'Tomorrow', 'Next 3 Days', 'Next 7 Days'];
        var followSeries = [
            parseInt(followup.overdue),
            parseInt(followup.today),
            parseInt(followup.tomorrow),
            parseInt(followup.next_3_days),
            parseInt(followup.next_7_days)
        ];
        var optionsFollowup = {
            series: [{
                name: 'Follow-ups',
                data: followSeries
            }],
            chart: {
                type: 'bar',
                height: 320,
                toolbar: {
                    show: false
                }
            },
            plotOptions: {
                bar: {
                    borderRadius: 6,
                    distributed: true,
                    columnWidth: '50%'
                }
            },
            colors: [colors.danger, colors.success, colors.warning, colors.info, colors.purple],
            fill: gradientOptions,
            xaxis: {
                categories: followCategories,
                labels: {
                    style: {
                        fontSize: '11px'
                    }
                }
            },
            legend: {
                show: false
            }
        };
        var chartFollowup = new ApexCharts(document.querySelector("#chart-followup"), optionsFollowup);
        chartFollowup.render();

        // --- 3. Product-wise Conversion Rate ---
        var prodConv = <?php echo json_encode($product_conversion); ?>;
        var optionsProdConv = {
            series: [{
                    name: "Total Leads",
                    data: prodConv.map(p => parseInt(p.total_leads))
                },
                {
                    name: "Converted",
                    data: prodConv.map(p => parseInt(p.converted_leads))
                }
            ],
            chart: {
                type: 'bar',
                height: 350,
                stacked: false,
                toolbar: {
                    show: false
                }
            },
            plotOptions: {
                bar: {
                    horizontal: true,
                    borderRadius: 4,
                    dataLabels: {
                        position: 'top'
                    }
                }
            },
            colors: [colors.info, colors.success],
            fill: gradientOptions,
            xaxis: {
                categories: prodConv.map(p => p.product_name || 'Unknown')
            }
        };
        var chartProductConv = new ApexCharts(document.querySelector("#chart-product-conv"), optionsProdConv);
        chartProductConv.render();

        // --- 4. Branch-wise Lead Performance ---
        var branchPerf = <?php echo json_encode($branch_performance); ?>;
        var optionsBranchPerf = {
            series: [{
                    name: "Total Leads",
                    data: branchPerf.map(b => parseInt(b.total_leads))
                },
                {
                    name: "Converted",
                    data: branchPerf.map(b => parseInt(b.converted_leads))
                }
            ],
            chart: {
                type: 'bar',
                height: 350,
                toolbar: {
                    show: false
                }
            },
            plotOptions: {
                bar: {
                    borderRadius: 4,
                    dataLabels: {
                        position: 'top'
                    },
                    columnWidth: '40%'
                }
            },
            colors: [colors.purple, colors.success],
            fill: gradientOptions,
            xaxis: {
                categories: branchPerf.map(b => b.branch_name || 'Unknown')
            }
        };
        var chartBranchPerf = new ApexCharts(document.querySelector("#chart-branch-perf"), optionsBranchPerf);
        chartBranchPerf.render();

        // Chart Dictionary for fast lookup
        var chartsMap = {
            'funnel': chartFunnel,
            'monthly_trend': chartMonthlyTrend,
            'product_dist': chartProductDist,
            'status_dist': chartStatusDist,
            'followup': chartFollowup,
            'product_conv': chartProductConv,
            'branch_perf': chartBranchPerf
        };

        // AJAX Filter Logic for individual graphs
        document.querySelectorAll('.chart-filter').forEach(function(select) {
            select.addEventListener('change', function() {
                var target = this.getAttribute('data-target');
                var dateRange = this.value;

                var formData = new FormData();
                formData.append('chart_type', target);
                formData.append('date_range', dateRange);

                fetch('<?php echo base_url("Analyticscontroller/fetch_chart_data"); ?>', {
                        method: 'POST',
                        body: formData
                    })
                    .then(res => res.json())
                    .then(data => {
                        if (data.status === 'error') return;
                        var chartInstance = chartsMap[target];

                        if (chartInstance) {
                            // Update labels/categories if provided
                            if (data.labels) {
                                chartInstance.updateOptions({
                                    xaxis: {
                                        categories: data.labels
                                    },
                                    labels: data.labels
                                });
                            }

                            // Update series depending on chart shape
                            if (target === 'product_dist' || target === 'status_dist') {
                                chartInstance.updateSeries(data.series);
                            } else if (target === 'funnel' || target === 'followup') {
                                chartInstance.updateSeries([{
                                    data: data.series
                                }]);
                            } else if (target === 'monthly_trend') {
                                chartInstance.updateSeries([{
                                        name: 'Generated',
                                        data: data.series[0]
                                    },
                                    {
                                        name: 'Converted',
                                        data: data.series[1]
                                    },
                                    {
                                        name: 'Lost',
                                        data: data.series[2]
                                    }
                                ]);
                            } else {
                                chartInstance.updateSeries([{
                                        name: 'Total Leads',
                                        data: data.series[0]
                                    },
                                    {
                                        name: 'Converted',
                                        data: data.series[1]
                                    }
                                ]);
                            }
                        }
                    })
                    .catch(err => console.error("Error fetching chart data:", err));
            });
        });

    });
</script>