<?php
session_start(['gc_maxlifetime' => 14400, 'cookie_httponly' => true]); // Starting Session
include('member_session.php'); // Auth guard: redirects to login if not authenticated
include('../coach/functions.php');
include("../coach/objects/class.member.php");
include '../coach/objects/baseline_bodycomposition.class.php';

$chart_from_date = date('m/d/y', strtotime('-2 weeks'));
$chart_to_date = date('m/d/y');
$pdf_file = isset($_POST['pdf_file']) ? $_POST['pdf_file'] : "";
//defining array
$selected_dates = array('x');
$selected_dates_grid = array();
$height_dates = array();
$weight_dates = array();
$bf_percnt_dates = array();
$lean_mass_dates = array();
$total_fat_dates = array();
$visceral_fat_dates = array();
$muscle_mass_dates = array();
$height = array('Height / Inches');
$weight = array('Weight / LBS');
$bf_percnt = array('Body Fat %');
$lean_mass = array('Lean Mass / LBS');
$total_fat = array('Total FAT / LBS');
$visceral_fat = array('Visceral Fat');
$muscle_mass = array('Muscles Mass / LBS');

$baseline_bodycomposition_data = array();

if ((isset($_POST['submit']) && $_POST['submit']) || $pdf_file == 'pdf_file') {
    $chart_from_date = ($_POST['chart_from_date'] != '' && $_POST['chart_from_date'] != '01/01/70' && $_POST['chart_from_date'] != '00/00/00') ? date('m/d/y', strtotime($_POST['chart_from_date'])) : $chart_from_date;
    $chart_to_date = ($_POST['chart_to_date'] != '' && $_POST['chart_to_date'] != '01/01/70' && $_POST['chart_to_date'] != '00/00/00') ? date('m/d/y', strtotime($_POST['chart_to_date'])) : $chart_to_date;
}
$member_id = $_SESSION['memberid'];
$bodycomposition = new Baseline_bodycomposition();

//getting baseline details
$baseline_bodycomposition_data = $bodycomposition->GetList(array(array('member_id', '=', $member_id), array('date', '>=', date('Y-m-d', strtotime($chart_from_date))), array('date', '<=', date('Y-m-d', strtotime($chart_to_date)))), 'date', true);

$arr = 0;
for ($i = strtotime($chart_from_date); $i <= strtotime($chart_to_date);) {
    $selected_dates[] = date('m/d/y', $i);
    $selected_dates_grid[$arr]['value'] = date('m/d/y', $i);
    $height[] = '';
    $weight[] = '';
    $bf_percnt[] = '';
    $lean_mass[] = '';
    $total_fat[] = '';
    $visceral_fat[] = '';
    $muscle_mass[] = '';
    $i = strtotime('+1 day', $i);
    $arr++;
}

for ($j = 0; $j < count($baseline_bodycomposition_data); $j++) {
    if (in_array(date('m/d/y', strtotime($baseline_bodycomposition_data[$j]->date)), $selected_dates)) {
        $key = array_search(date('m/d/y', strtotime($baseline_bodycomposition_data[$j]->date)), $selected_dates);
        $height[$key] = $baseline_bodycomposition_data[$j]->height;
        $weight[$key] = $baseline_bodycomposition_data[$j]->weight;
        $bf_percnt[$key] = $baseline_bodycomposition_data[$j]->body_fat;
        $lean_mass[$key] = $baseline_bodycomposition_data[$j]->lean_body_mass;
        $total_fat[$key] = $baseline_bodycomposition_data[$j]->fat_weight;
        $visceral_fat[$key] = $baseline_bodycomposition_data[$j]->visceral_fat;
        $muscle_mass[$key] = $baseline_bodycomposition_data[$j]->muscle_mass;
    }
}

//removing empty data
$height_dates = $selected_dates;
$weight_dates = $selected_dates;
$bf_percnt_dates = $selected_dates;
$lean_mass_dates = $selected_dates;
$total_fat_dates = $selected_dates;
$visceral_fat_dates = $selected_dates;
$muscle_mass_dates = $selected_dates;

//to remove the empty values in graph
for ($k = 0; $k < count($selected_dates); $k++) {
    if ($height[$k] == '' || $height[$k] == '0') {
        unset($height[$k]);
        unset($height_dates[$k]);
    }
    if ($weight[$k] == '' || $weight[$k] == '0') {
        unset($weight[$k]);
        unset($weight_dates[$k]);
    }
    if ($bf_percnt[$k] == '' || $bf_percnt[$k] == '0') {
        unset($bf_percnt[$k]);
        unset($bf_percnt_dates[$k]);
    }
    if ($lean_mass[$k] == '' || $lean_mass[$k] == '0') {
        unset($lean_mass[$k]);
        unset($lean_mass_dates[$k]);
    }
    if ($total_fat[$k] == '' || $total_fat[$k] == '0') {
        unset($total_fat[$k]);
        unset($total_fat_dates[$k]);
    }
    if ($visceral_fat[$k] == '' || $visceral_fat[$k] == '0') {
        unset($visceral_fat[$k]);
        unset($visceral_fat_dates[$k]);
    }
    if ($muscle_mass[$k] == '' || $muscle_mass[$k] == '0') {
        unset($muscle_mass[$k]);
        unset($muscle_mass_dates[$k]);
    }
}
$height = array_values($height);
$height_dates = array_values($height_dates);
$weight = array_values($weight);
$weight_dates = array_values($weight_dates);
$bf_percnt = array_values($bf_percnt);
$bf_percnt_dates = array_values($bf_percnt_dates);
$lean_mass = array_values($lean_mass);
$lean_mass_dates = array_values($lean_mass_dates);
$total_fat = array_values($total_fat);
$total_fat_dates = array_values($total_fat_dates);
$visceral_fat = array_values($visceral_fat);
$visceral_fat_dates = array_values($visceral_fat_dates);
$muscle_mass = array_values($muscle_mass);
$muscle_mass_dates = array_values($muscle_mass_dates);

$no_data = 0;
if (count($height_dates) <= 1 && count($weight_dates) <= 1 && count($bf_percnt_dates) <= 1 && count($lean_mass_dates) <= 1 && count($total_fat_dates) <= 1 && count($visceral_fat_dates) <= 1 && count($muscle_mass_dates) <= 1) {
    $no_data = 1;
}

include('member-header.php');
?>
<style type="text/css">
.app-layout {
    width: 100%;
}
.page-header-title, .page-header-subtitle {
padding: 0;
}
.chart-card-title {
padding: 0;
}
.chart-card-unit {
color: inherit;
}[6:22 PM]Food Journal Entry:
.upload-text {
padding: 0;
}
@media (max-width:767px) {
.datetime-row .date-picker-wrapper:first-child {
max-width: 292px;
width: 100%;
min-width: auto;
}
}
    /*#chart1 { width: 100%; min-height: 400px; }*/
    /*#daily_log_id { width: 75%; margin: 5px 0px 52px 0px; }*/
    /*.success { background-color: #4592e0; width: 150px; height: 25px; text-align: center; color: #ffffff;}*/
    /*#accountability_chart_form label.error { color: red; }*/
    /*#thd { text-align: center; font-weight: bold; }*/
    /*td { padding: 10px 15px; }*/
    /*.text-center { text-align: center; }*/
    /*.text-upper { text-transform: uppercase; }*/
    /*.mandatory { color: red; font-size: 14px; }*/
    /*.btn { background-color: #c0c0c0; }*/
    /*@media (max-width: 768px) {*/
    /*    #daily_log_id { width: 90%; margin: 5px 0px 52px 0px; }*/
    /*}*/
    /*.container1 select {*/
    /*    padding: 10px;*/
    /*    background: #ffffff;*/
    /*    border: 1px solid #CCCCCC;*/
    /*    border-radius: 3px;*/
    /*    margin: 0 3px;*/
    /*}*/
    /*.btn-success {*/
    /*    color: #fff;*/
    /*    background-color: #5cb85c;*/
    /*    border-color: #5cb85c;*/
    /*}*/
</style>


    <!-- Mobile Top Bar (logo centered) -->
    <div class="mobile-top-bar">
        <img src="./assets/images/logo.png" alt="Brand Logo">
    </div>

    <div class="app-layout">
        <!-- Desktop Sidebar -->
        <div id="sidebar-placeholder"><?php include('menu.php'); ?></div>

        <!-- Main Content -->
        <main class="main-content">
            <!-- Page Header -->
            <header class="page-header">
                <div class="page-header-meta">
                    <div>
                        <h1 class="page-header-title">Graphs & Charts</h1>
                        <p class="page-header-subtitle">Track your progress over time</p>
                    </div>
                </div>
            </header>

            <div class="body-content">

                <!-- Body Content -->
                <div class="chart-inner-body">

                    <!-- Filter Tabs -->
                    <div class="white-black-filter-tabs" id="graph-chart-filter-tabs">
                        <button type="button" class="white-black-filter-btn" data-range="1W">1W</button>
                        <button type="button" class="white-black-filter-btn" data-range="1M">1M</button>
                        <button type="button" class="white-black-filter-btn active" data-range="3M">3M</button>
                        <button type="button" class="white-black-filter-btn" data-range="6M">6M</button>
                        <!-- Custom Date Range Button -->
                        <div class="calendar-wrapper">
                            <button type="button" class="white-black-filter-btn" id="calendarBtn">
                                <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
                                    <rect width="16" height="16" fill="url(#pattern0_2486_4495)" />
                                    <defs>
                                        <pattern id="pattern0_2486_4495" patternContentUnits="objectBoundingBox" width="1" height="1">
                                            <use xlink:href="#image0_2486_4495" transform="scale(0.0078125)" />
                                        </pattern>
                                        <image id="image0_2486_4495" width="128" height="128" preserveAspectRatio="none" xlink:href="data:image/png;base64, " />
                                </defs>
                            </svg>
                            </button>
                        </div>
                    </div>

                    <!-- Date Range Form (preserves original PHP POST behavior) -->
                    <form method="POST" id="chartFilterForm" style="display: none;">
                        <input type="text" id="start_date" name="chart_from_date" ata-field="date" autocomplete="off" class="form-control" value="<?php echo isset($chart_from_date) && $chart_from_date ? date('Y-m-d', strtotime($chart_from_date)) : date('Y-m-d'); ?>" readonly class="text" style="display: none;">
                        <input type="text" id="end_date" name="chart_to_date" ata-field="date" autocomplete="off" class="form-control" value="<?php echo isset($chart_to_date) && $chart_to_date ? date('Y-m-d', strtotime($chart_to_date)) : date('Y-m-d'); ?>" readonly class="text" style="display: none;">
                        <input type="hidden" name="submit" value="Submit">
                    </form>

                    <!-- Custom Date Range Modal -->
                    <div id="dateRangeModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999; justify-content: center; align-items: center;">
                        <div style="background: #fff; border-radius: 12px; padding: 24px; max-width: 400px; width: 90%;">
                            <h3 style="margin: 0 0 16px 0; font-size: 18px;">Select Date Range</h3>
                            <div style="margin-bottom: 16px;">
                                <label style="display: block; margin-bottom: 4px; font-weight: 600;">Start Date:</label>
                                <div class="container1">
                                    <input type="text" id="modal_start_date" ata-field="date" autocomplete="off" class="form-control" value="<?php echo isset($chart_from_date) && $chart_from_date ? date('Y-m-d', strtotime($chart_from_date)) : date('Y-m-d'); ?>" readonly class="text" style="display: none;">
                                </div>
                            </div>
                            <div style="margin-bottom: 16px;">
                                <label style="display: block; margin-bottom: 4px; font-weight: 600;">End Date:</label>
                                <div class="container1">
                                    <input type="text" id="modal_end_date" ata-field="date" autocomplete="off" class="form-control" value="<?php echo isset($chart_to_date) && $chart_to_date ? date('Y-m-d', strtotime($chart_to_date)) : date('Y-m-d'); ?>" readonly class="text" style="display: none;">
                                </div>
                            </div>
                            <div style="display: flex; gap: 8px;">
                                <button type="button" id="modalSubmit" style="flex: 1; padding: 10px; background: #111827; color: #fff; border: none; border-radius: 8px; cursor: pointer; font-weight: 600;">Apply</button>
                                <button type="button" id="modalCancel" style="flex: 1; padding: 10px; background: #e5e7eb; color: #374151; border: none; border-radius: 8px; cursor: pointer; font-weight: 600;">Cancel</button>
                            </div>
                        </div>
                    </div>

                    <div class="">

                        <?php if ($no_data == 0) { ?>

                            <?php if (count($height_dates) > 1) { ?>
                            <!-- Height / Inches -->
                            <div class="chart-card">
                                <div class="chart-card-header">
                                    <h6 class="chart-card-title">Height <span class="chart-card-unit">/ Inches</span></h6>
                                </div>
                                <div class="chart-wrapper">
                                    <div id="chartHeight"></div>
                                </div>
                            </div>
                            <?php } ?>

                            <?php if (count($weight_dates) > 1) { ?>
                            <!-- Weight / LBS -->
                            <div class="chart-card">
                                <div class="chart-card-header">
                                    <h6 class="chart-card-title">Weight <span class="chart-card-unit">/ LBS</span></h6>
                                </div>
                                <div class="chart-wrapper">
                                    <div id="chartWeight"></div>
                                </div>
                            </div>
                            <?php } ?>

                            <?php if (count($bf_percnt_dates) > 1) { ?>
                            <!-- Body Fat % -->
                            <div class="chart-card">
                                <div class="chart-card-header">
                                    <h6 class="chart-card-title">Body Fat %</h6>
                                </div>
                                <div class="chart-wrapper">
                                    <div id="chartBodyFat"></div>
                                </div>
                            </div>
                            <?php } ?>

                            <?php if (count($lean_mass_dates) > 1) { ?>
                            <!-- Lean Mass / LBS -->
                            <div class="chart-card">
                                <div class="chart-card-header">
                                    <h6 class="chart-card-title">Lean Mass <span class="chart-card-unit">/ LBS</span></h6>
                                </div>
                                <div class="chart-wrapper">
                                    <div id="chartLeanMass"></div>
                                </div>
                            </div>
                            <?php } ?>

                            <?php if (count($total_fat_dates) > 1) { ?>
                            <!-- Total FAT / LBS -->
                            <div class="chart-card">
                                <div class="chart-card-header">
                                    <h6 class="chart-card-title">Total FAT <span class="chart-card-unit">/ LBS</span></h6>
                                </div>
                                <div class="chart-wrapper">
                                    <div id="chartTotalFat"></div>
                                </div>
                            </div>
                            <?php } ?>

                            <?php if (count($visceral_fat_dates) > 1) { ?>
                            <!-- Visceral Fat -->
                            <div class="chart-card">
                                <div class="chart-card-header">
                                    <h6 class="chart-card-title">Visceral Fat</h6>
                                </div>
                                <div class="chart-wrapper">
                                    <div id="chartVisceralFat"></div>
                                </div>
                            </div>
                            <?php } ?>

                            <?php if (count($muscle_mass_dates) > 1) { ?>
                            <!-- Muscles Mass / LBS -->
                            <div class="chart-card">
                                <div class="chart-card-header">
                                    <h6 class="chart-card-title">Muscles Mass <span class="chart-card-unit">/ LBS</span></h6>
                                </div>
                                <div class="chart-wrapper">
                                    <div id="chartMuscularMass"></div>
                                </div>
                            </div>
                            <?php } ?>

                        <?php } else { ?>
                            <?php if ($pdf_file == '') { ?>
                            <div style="padding-left:20px;font-weight:bold;color: red;">Please change the date criteria as the selected date range has no data available to display</div>
                            <?php } ?>
                        <?php } ?>

                    </div>
                </div>

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

    <!-- Mobile Bottom Navigation -->
    <div id="mobile-nav-placeholder"></div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/apexcharts@3.54.0/dist/apexcharts.min.js"></script>
    <script src="./js/layout.js"></script>

<script language="javascript" type="text/javascript" src="../coach/js/jquery.js"></script>

<script type="text/javascript">
    var selected_dates = <?php echo json_encode($selected_dates); ?>;
    var selected_dates_grid = <?php echo json_encode($selected_dates_grid); ?>;
    var weight = <?php echo json_encode($weight); ?>;
    var weight_dates = <?php echo json_encode($weight_dates); ?>;
    var bf_percnt = <?php echo json_encode($bf_percnt); ?>;
    var bf_percnt_dates = <?php echo json_encode($bf_percnt_dates); ?>;
    var lean_mass = <?php echo json_encode($lean_mass); ?>;
    var lean_mass_dates = <?php echo json_encode($lean_mass_dates); ?>;
    var total_fat = <?php echo json_encode($total_fat); ?>;
    var total_fat_dates = <?php echo json_encode($total_fat_dates); ?>;
    var height = <?php echo json_encode($height); ?>;
    var height_dates = <?php echo json_encode($height_dates); ?>;
    var visceral_fat = <?php echo json_encode($visceral_fat); ?>;
    var visceral_fat_dates = <?php echo json_encode($visceral_fat_dates); ?>;
    var muscle_mass = <?php echo json_encode($muscle_mass); ?>;
    var muscle_mass_dates = <?php echo json_encode($muscle_mass_dates); ?>;
    var no_data = <?php echo $no_data; ?>;

    // Transform C3 data format to ApexCharts format
    function transformC3ToApex(datesArray, valuesArray) {
        var categories = [];
        var data = [];
        for (var i = 1; i < datesArray.length; i++) {
            if (valuesArray[i] !== '' && valuesArray[i] !== '0' && valuesArray[i] !== null) {
                categories.push(datesArray[i]);
                data.push(parseFloat(valuesArray[i]));
            }
        }
        return { categories: categories, data: data };
    }

    function createApexChartOptions(color, data, categories, yLabel) {
        return {
            chart: {
                type: 'area',
                height: 260,
                width: '100%',
                fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
                toolbar: { show: false },
                animations: {
                    enabled: true,
                    easing: 'easeinout',
                    speed: 800
                },
                redrawOnParentResize: true,
                redrawOnWindowResize: true
            },
            series: [{
                name: yLabel,
                data: data
            }],
            colors: [color],
            fill: {
                type: 'gradient',
                gradient: {
                    shadeIntensity: 1,
                    opacityFrom: 0.35,
                    opacityTo: 0.02,
                    stops: [0, 100]
                }
            },
            stroke: {
                curve: 'smooth',
                width: 2.5,
                lineCap: 'round'
            },
            dataLabels: { enabled: false },
            grid: { show: false },
            xaxis: {
                categories: categories,
                axisBorder: { show: false },
                axisTicks: { show: false },
                crosshairs: {
                    show: true,
                    stroke: { color: color, width: 1, dashArray: 4 }
                },
                labels: {
                    style: { colors: '#9CA3AF', fontSize: '11px' },
                    offsetY: 2,
                    formatter: function(val) {
                        return val ? val.replace(/, \d{4}$/, '') : val;
                    }
                },
                tooltip: { enabled: false }
            },
            yaxis: {
                labels: {
                    style: { colors: '#9CA3AF', fontSize: '11px' },
                    formatter: function(val) {
                        return val ? val.toFixed(1) : val;
                    }
                }
            },
            tooltip: {
                theme: false,
                custom: function({ series, seriesIndex, dataPointIndex, w }) {
                    var val = series[seriesIndex][dataPointIndex];
                    var date = categories[dataPointIndex];
                    var cleanLabel = yLabel.replace(/\s*\(.*?\)/, '');
                    return '<div class="chart-tooltip">' +
                        '<div class="chart-tooltip-date">Date: ' + date + '</div>' +
                        '<div class="chart-tooltip-value">' + cleanLabel + ': ' + val.toFixed(1) + '</div>' +
                        '</div>';
                }
            },
            markers: {
                size: 0,
                strokeWidth: 0,
                hover: { size: 5, sizeOffset: 0 }
            }
        };
    }

    var charts = [];

    if (no_data == 0) {
        // Height
        if (height_dates.length > 1) {
            var heightData = transformC3ToApex(height_dates, height);
            if (heightData.data.length > 0) {
                charts.push(new ApexCharts(document.querySelector("#chartHeight"),
                    createApexChartOptions('#F59E0B', heightData.data, heightData.categories, 'Height / Inches')));
            }
        }

        // Weight
        if (weight_dates.length > 1) {
            var weightData = transformC3ToApex(weight_dates, weight);
            if (weightData.data.length > 0) {
                charts.push(new ApexCharts(document.querySelector("#chartWeight"),
                    createApexChartOptions('#10B981', weightData.data, weightData.categories, 'Weight / LBS')));
            }
        }

        // Body Fat %
        if (bf_percnt_dates.length > 1) {
            var bfData = transformC3ToApex(bf_percnt_dates, bf_percnt);
            if (bfData.data.length > 0) {
                charts.push(new ApexCharts(document.querySelector("#chartBodyFat"),
                    createApexChartOptions('#EF4444', bfData.data, bfData.categories, 'Body Fat %')));
            }
        }

        // Lean Mass
        if (lean_mass_dates.length > 1) {
            var leanData = transformC3ToApex(lean_mass_dates, lean_mass);
            if (leanData.data.length > 0) {
                charts.push(new ApexCharts(document.querySelector("#chartLeanMass"),
                    createApexChartOptions('#8B5CF6', leanData.data, leanData.categories, 'Lean Mass / LBS')));
            }
        }

        // Total Fat
        if (total_fat_dates.length > 1) {
            var fatData = transformC3ToApex(total_fat_dates, total_fat);
            if (fatData.data.length > 0) {
                charts.push(new ApexCharts(document.querySelector("#chartTotalFat"),
                    createApexChartOptions('#F43F5E', fatData.data, fatData.categories, 'Total FAT / LBS')));
            }
        }

        // Visceral Fat
        if (visceral_fat_dates.length > 1) {
            var visceralData = transformC3ToApex(visceral_fat_dates, visceral_fat);
            if (visceralData.data.length > 0) {
                charts.push(new ApexCharts(document.querySelector("#chartVisceralFat"),
                    createApexChartOptions('#3B82F6', visceralData.data, visceralData.categories, 'Visceral Fat')));
            }
        }

        // Muscle Mass
        if (muscle_mass_dates.length > 1) {
            var muscleData = transformC3ToApex(muscle_mass_dates, muscle_mass);
            if (muscleData.data.length > 0) {
                charts.push(new ApexCharts(document.querySelector("#chartMuscularMass"),
                    createApexChartOptions('#34D399', muscleData.data, muscleData.categories, 'Muscles Mass / LBS')));
            }
        }

        Promise.all(charts.map(function(c) { return c.render(); })).then(function() {
            window.dispatchEvent(new Event('resize'));
        });
    }

    // =========================================================
    // FILTER TABS & CUSTOM DATE RANGE
    // =========================================================
    const filterTabs = document.querySelector('#graph-chart-filter-tabs');
    const chartFilterForm = document.querySelector('#chartFilterForm');
    const startDateInput = document.querySelector('#start_date');
    const endDateInput = document.querySelector('#end_date');
    const modalStartDate = document.querySelector('#modal_start_date');
    const modalEndDate = document.querySelector('#modal_end_date');
    const dateRangeModal = document.querySelector('#dateRangeModal');
    const calendarBtn = document.querySelector('#calendarBtn');

    // Format date as YYYY-MM-DD
    function formatDateYMD(d) {
        var yyyy = d.getFullYear();
        var mm = String(d.getMonth() + 1).padStart(2, '0');
        var dd = String(d.getDate()).padStart(2, '0');
        return yyyy + '-' + mm + '-' + dd;
    }

    // Format date as MMM DD, YYYY for display
    function formatDateDisplay(d) {
        return d.toLocaleDateString('en-GB', {
            day: '2-digit',
            month: 'short',
            year: 'numeric'
        });
    }

    // Preset range buttons (1W, 1M, 3M, 6M)
    filterTabs.querySelectorAll('.white-black-filter-btn[data-range]').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var range = this.getAttribute('data-range');
            var today = new Date();
            var fromDate = new Date();

            if (range === '1W') {
                fromDate.setDate(today.getDate() - 7);
            } else if (range === '1M') {
                fromDate.setMonth(today.getMonth() - 1);
            } else if (range === '3M') {
                fromDate.setMonth(today.getMonth() - 3);
            } else if (range === '6M') {
                fromDate.setMonth(today.getMonth() - 6);
            }

            startDateInput.value = formatDateYMD(fromDate);
            endDateInput.value = formatDateYMD(today);

            // Remove active from all preset buttons
            filterTabs.querySelectorAll('.white-black-filter-btn[data-range]').forEach(function(b) {
                b.classList.remove('active');
            });
            this.classList.add('active');

            // Remove any custom date button
            var oldDateBtn = document.querySelector('.custom-date-btn');
            if (oldDateBtn) oldDateBtn.remove();

            // Submit form
            chartFilterForm.submit();
        });
    });

    // Calendar button opens custom date range modal
    calendarBtn.addEventListener('click', function() {
        dateRangeModal.style.display = 'flex';
        // Initialize dropdownDatepicker on modal inputs
        try {
            $(modalStartDate).dropdownDatepicker({
                defaultDateFormat: 'yyyy-mm-dd',
                displayFormat: 'mdy',
                submitFormat: 'yyyy-mm-dd'
            });
            $(modalEndDate).dropdownDatepicker({
                defaultDateFormat: 'yyyy-mm-dd',
                displayFormat: 'mdy',
                submitFormat: 'yyyy-mm-dd'
            });
        } catch(e) {}
    });

    // Modal Apply button
    document.querySelector('#modalSubmit').addEventListener('click', function() {
        var fromVal = modalStartDate.value;
        var toVal = modalEndDate.value;

        if (!fromVal || !toVal) {
            alert('Please select both start and end dates');
            return;
        }

        // Update hidden form inputs
        startDateInput.value = fromVal;
        endDateInput.value = toVal;

        // Remove active from preset buttons
        filterTabs.querySelectorAll('.white-black-filter-btn[data-range]').forEach(function(b) {
            b.classList.remove('active');
        });

        // Remove old custom button
        var oldDateBtn = document.querySelector('.custom-date-btn');
        if (oldDateBtn) oldDateBtn.remove();

        // Create custom date range button
        var fromDate = new Date(fromVal + 'T00:00:00');
        var toDate = new Date(toVal + 'T00:00:00');
        var displayText = formatDateDisplay(fromDate) + ' - ' + formatDateDisplay(toDate);

        var dateBtn = document.createElement('button');
        dateBtn.className = 'white-black-filter-btn custom-date-btn active';
        dateBtn.textContent = displayText;

        // Insert before calendar wrapper
        var calendarWrapper = document.querySelector('.calendar-wrapper');
        filterTabs.insertBefore(dateBtn, calendarWrapper);

        // Close modal
        dateRangeModal.style.display = 'none';

        // Submit form
        chartFilterForm.submit();
    });

    // Modal Cancel button
    document.querySelector('#modalCancel').addEventListener('click', function() {
        dateRangeModal.style.display = 'none';
    });

    // Close modal on background click
    dateRangeModal.addEventListener('click', function(e) {
        if (e.target === dateRangeModal) {
            dateRangeModal.style.display = 'none';
        }
    });

    // Custom date button click handler (for already-created custom buttons)
    function attachCustomDateBtnHandler(btn) {
        btn.addEventListener('click', function() {
            filterTabs.querySelectorAll('.white-black-filter-btn').forEach(function(b) {
                b.classList.remove('active');
            });
            this.classList.add('active');
            // Re-submit with same dates
            chartFilterForm.submit();
        });
    }
</script>

<script src="../coach/js/jquery-dropdown-datepicker.min.js"></script>
<script>
    // Initialize dropdownDatepicker on the hidden form inputs
    $(function() {
        $('#start_date').dropdownDatepicker({
            defaultDateFormat: 'yyyy-mm-dd',
            displayFormat: 'mdy',
            submitFormat: 'yyyy-mm-dd'
        });
        $('#end_date').dropdownDatepicker({
            defaultDateFormat: 'yyyy-mm-dd',
            displayFormat: 'mdy',
            submitFormat: 'yyyy-mm-dd'
        });
    });
</script>
<style>
    .container1 select {
        padding: 10px;
        background: #ffffff;
        border: 1px solid #CCCCCC;
        border-radius: 3px;
        margin: 0 3px;
    }
</style>
<?php
include('member-footer.php');
?>