
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<style>
    .profile-img {
        width: 150px;
        height: 150px;
        object-fit: cover;
        transition: transform 0.3s ease-in-out;
        cursor: pointer;
    }
    .fullscreen-img {
        position: fixed;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        background: rgba(0, 0, 0, 0.8);
        display: flex;
        justify-content: center;
        align-items: center;
        opacity: 0;
        visibility: hidden;
        transition: opacity 0.3s ease-in-out;
        z-index: 1000;
    }
    .fullscreen-img img {
        max-width: 90%;
        max-height: 90%;
        border-radius: 10px;
        box-shadow: 0 0 15px rgba(255, 255, 255, 0.3);
    }
    .fullscreen-img.show {
        opacity: 1;
        visibility: visible;
    }
    .profile-card {
        width: 340px;
        overflow: hidden;
        background: rgb(224, 255, 253);
        transition: all 0.3s ease-in-out;
    }.extra-info {
        max-height: 0;
        opacity: 0;
        overflow: hidden;
        transition: max-height 0.4s ease-in-out, opacity 0.3s ease-in-out;
    }
    .profile-card:hover .extra-info {
        max-height: 500px;
        /* Large enough to reveal content */
        opacity: 1;
    }
    .profile-card:hover {
        background: rgb(247, 247, 247);
    }
    .form-group {
        margin-bottom: 1rem;
    }
    .form-select {
        width: 100%;
    }
    .card-body {
        padding: 1rem;
    }
    .chart-container {
        position: relative;
        width: 100%;
        height: 400px;
    }
</style>

<script>var baseUrl = "<?php echo base_url(); ?>";</script>
<?php
$level = $this->session->userdata('level');
$anmselected = $this->session->userdata('anmregionId');
$ashaselected = $this->session->userdata('asharegionId');
$start_date = $this->session->userdata('start_date');
$end_date = $this->session->userdata('end_date');
?>
<div class="text-center m-2 p-2 bg-primary">
    <h3 class="text-white"><strong>Mira wise Data Graphically</strong></h3>
</div>

<div class="row" >
    <div class="col-md-4 col-md-push-4">
        <div class="form-group">
            <div class="input-group">
                <span class="input-group-addon"><i aria-hidden="true"></i>Select ANM</span>
                <select id="anm_region_code" name="anm_region_code" required class="form-control">
                    <option value="0" disabled="true" selected> Select ANM</option>
                    <?php foreach ($anmList as $anm) { ?>
                        <option value="<?= $anm['region_code'] ?>"><?= $anm['user_name'] ?></option>
                    <?php } ?>

                </select>

            </div>                    
        </div> 
    </div>

</div>      
<hr>

<div class="card mx-5" >
    <div class="card-body">

        <div class="container" style="margin-top: 20px;">
            <div class="row" id="mira_card_container"></div>
        </div>
        <!-- Full-screen Image Container -->
        <div id="fullscreenContainer" class="fullscreen-img" style="display: none;">
            <img id="fullscreenImage" src="" alt="Fullscreen Profile">
        </div>
    </div>
    <div id="asha_list_update_spinner" style="display:none;">Loading...</div>
    <!-- Bootstrap Modal for Graph -->
    <div class="modal fade" id="graphModal" tabindex="-1" role="dialog" aria-labelledby="graphModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="graphModalLabel">Graphical Representation of Data</h5>
                    <h6 id="total"></h6>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div>
                        <label for="graph-type" class="control-label"><strong>Select Graph Type</strong></label>
                        <select name="graph-type" id="graph-type" class="form-control">
                            <option value="" selected>Select Graph</option>
                            <option value="0">Immunization Graphs</option>
                            <option value="1">Total Children, Complete Doses, Missed Doses</option>
                            <option value="2">Get Pregnancy Data</option>
                        </select>
                    </div>
                    <div class="container">
                        <div class="chart-container" style="width: 70%; text-align: center; max-width: 800px;">
                            <canvas id="myChart" style="max-height: 350px ;"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {
        let selectedAshaCode = 0;
        let vaccineChart = null;

        $('#anm_region_code').change(function () {
            let region_code = parseInt($(this).val());
            console.log("Region Code ", region_code);
            if (region_code) {
                $('#asha_list_update_spinner').show();
                $.post('<?= base_url('getAshaDeatilByANMId') ?>', {region_code: region_code}, function(response) {
                    if (response.status && response.miraList.length > 0) {
                        console.log(response.miraList);
                        generateMiraCards(response.miraList);
                    } else {
                        $('#mira_card_container').html('<p class="text-danger">No Mira data available.</p>');
                    }
                }, 'json').fail(function (xhr, status, errorThrown) {
                    console.error('Error:', errorThrown, xhr.responseText);
                }).always(function () {
                    $('#asha_list_update_spinner').hide();
                });
            }
        });

        $(document).on('click', '.view-details', function () {
            selectedAshaCode = $(this).data('region_code');
            console.log(selectedAshaCode);
            resetChart();
            $('#graphModal').modal('show');
        });

        $('#graph-type').change(function () {
            resetChart();
            let anmCode = $('#anm_region_code').val();
            let ashaCode = selectedAshaCode;
            let requestUrl = '';

            if ($(this).val() === '0') {
                requestUrl = 'get_vaccination_data';
            } else if ($(this).val() === '1') {
                requestUrl = 'getDoseCompletionData';
            } else if ($(this).val() === '2') {
                requestUrl = 'get_women_pregnancy_info';
            }

            $.ajax({
                url: requestUrl,
                type: 'POST',
                data: {anmCode: anmCode, ashaCode: ashaCode},
                dataType: 'json',
                success: function (response) {
                    
                    if (response.status === 'success' && response.data) {
                        console.log("Inside ajax success!")
                        if (requestUrl === 'get_vaccination_data') {
                            updateGraph(response.data);
                        } else {
                            resetChart();
                            console.log(response.data)
                            renderPieChart(response.data);
                        }
                    } else {
                        console.error('Error fetching graph data:', response.message);
                    }
                },
                error: function (xhr, status, error) {
                    console.error('AJAX Error checking:', error);
                }
            });
        });

        function renderPieChart(data) {
            resetChart(); // Reset existing chart
            let ctx = document.getElementById("myChart").getContext("2d");

            if (!data || data.length === 0) {
                console.error("No data available for the pie chart.");
                return;
            }

            let total = data.reduce((sum, item) => sum + item.value, 0);
            let labels = data.map(item => item.label);
            let values = data.map(item => item.value);
            let backgroundColors = ["#36A2EB", "#FF6384", "#FFCE56", "#4BC0C0", "#9966FF", "#FF9F40"];
            document.getElementById('total').innerText= `Total Immunization Children ${total}`;

            while (backgroundColors.length < data.length) {
                backgroundColors.push(`#${Math.floor(Math.random() * 16777215).toString(16)}`);
            }

            vaccineChart = new Chart(ctx, {
                type: "pie",
                data: {
                    labels: labels,
                    datasets: [{
                        data: values,
                        backgroundColor: backgroundColors.slice(0, data.length),
                        hoverBackgroundColor: backgroundColors.map(color => color + "CC")
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio:false,
                    plugins: {
                        legend: {position: "top"},
                        title: {display: true, text: `Total: ${total}`}
                    }
                }
            });
        }

        function updateGraph(data) {
            resetChart();
            let ctx = document.getElementById("myChart").getContext("2d");
            let totalChildren = data.total_children || 0; // Ensure totalChildren exists
            let labels = data.vaccination_data ? data.vaccination_data.map(item => item.vaccine_code) : [];
            let values = data.vaccination_data ? data.vaccination_data.map(item => parseInt(item.count)) : [];
            document.getElementById('total').innerText= `Total Children ${totalChildren}`;
            vaccineChart = new Chart(ctx, {
                type: "bar",
                data: {
                    labels: labels,
                    datasets: [{
                        label: "Number of Children Vaccinated",
                        data: values,
                        backgroundColor: "rgba(54, 162, 235, 0.6)",
                        borderColor: "rgba(54, 162, 235, 1)",
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        title: {
                            display: true,
                            text: `Total Children: ${totalChildren}`,
                            font: {size: 16},
                            padding: {top: 10, bottom: 10}
                        }
                    },
                    scales: {
                        y: {beginAtZero: true}
                    }
                }
            });
        }

        function resetChart() {
            if (vaccineChart) {
                vaccineChart.destroy();
            }
            $("#myChart").html('<canvas id="myChart"></canvas>');
        }

        function generateMiraCards(miraList) {
            let cardsHtml = '<div class="row">';
            miraList.forEach((mira) => {
                let profilePic = mira.profile_pic != '' ? mira.profile_pic : 'resources/upload/profile/2.png';
                cardsHtml += `
                    <div class="col-md-4 bg-light">
                        <div class="text-center" style="margin-top: 20px;">
                            <div class="card profile-card" style="box-shadow: 0px 4px 6px rgba(0,0,0,0.1);">
                                <div class="card-body text-center">
                                    <img src="${profilePic}" alt="User Profile" class="img-circle profile-img my-3">
                                    <h3 class="card-title mb-0">${mira.user_name}</h3>
                                    <p class="text-muted">Region Name: ${mira.region_name},<br/> Region Code: ${mira.region_code}</p>
                                    <div class="extra-info">
                                        <hr>
                                        <h5>Basic Info</h5>
                                        <div class="row">
                                            <div class="col-xs-6">
                                                <p class="card-text"><strong class="text-secondary">Houses:</strong>
                                                    <span class="text-dark">${mira.house_count}</span></p>
                                            </div>
                                            <div class="col-xs-6">
                                                <p class="card-text"><strong class="text-secondary">Women:</strong>
                                                    <span class="text-dark">${mira.woman_count}</span></p>
                                            </div>
                                        </div>
                                        <div>
                                            <p class="card-text"><strong class="text-secondary">Children:</strong>
                                                <span class="text-dark">${mira.child_count}</span></p>
                                            <p class="card-text">
                                                <span class="label label-danger">
                                                    Pregnant Women: ${mira.pregnant_woman_count}
                                                </span>
                                            </p>
                                            <button class="btn btn-primary btn-lg view-details" data-region_code="${mira.region_code}" 
                                                    data-toggle="modal" data-target="#graphModal" 
                                                    style="transition: transform 0.2s;">
                                                View Graphical Info
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            });
            cardsHtml += '</div>';
            $('#mira_card_container').html(cardsHtml);
        }
    });
</script>

