<?php
session_start(['gc_maxlifetime' => 14400, 'cookie_httponly' => true]); // Starting Session
include('../coach/functions.php');
include("../coach/objects/class.member.php");
include("configuration.php");
include '../coach/objects/baseline_measurement.class.php';

// Support both memberid and member_id session variables
$member_id = isset($_SESSION['memberid']) ? $_SESSION['memberid'] : 
             (isset($_SESSION['member_id']) ? $_SESSION['member_id'] : 0);

if ($member_id == 0) {
    header("Location: login.php");
    exit;
}

$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();

$chest = array('Chest / Inches');
$arm = array('Arm L / Inches');
$arm2 = array('Arm R / Inches');
$waist = array('Waist / Inches');
$hips = array('Hips / Inches');
$thigh = array('Thigh L / Inches');
$thigh2 = array('Thigh R / Inches');
$calf = array('Calf L / Inches');
$calf2 = array('Calf R / Inches');

$baseline_measurement_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;
}

$measurement = new Baseline_measurement();

//getting baseline details
$baseline_measurement_data = $measurement->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);
    $chest[] = '';
    $arm[] = '';
    $arm2[] = '';
    $waist[] = '';
    $hips[] = '';
    $thigh[] = '';
    $thigh2[] = '';
    $calf[] = '';
    $calf2[] = '';
    $i = strtotime('+1 day', $i);
    $arr++;
}

for ($j = 0; $j < count($baseline_measurement_data); $j++) {
    if (in_array(date('m/d/y', strtotime($baseline_measurement_data[$j]->date)), $selected_dates)) {
        $key = array_search(date('m/d/y', strtotime($baseline_measurement_data[$j]->date)), $selected_dates);
        $chest[$key] = $baseline_measurement_data[$j]->chest ? $baseline_measurement_data[$j]->chest : "";
        $arm[$key] = $baseline_measurement_data[$j]->arm1 ? $baseline_measurement_data[$j]->arm1 : "";
        $arm2[$key] = $baseline_measurement_data[$j]->arm2 ? $baseline_measurement_data[$j]->arm2 : "";
        $waist[$key] = $baseline_measurement_data[$j]->waist ? $baseline_measurement_data[$j]->waist : "";
        $hips[$key] = $baseline_measurement_data[$j]->hips ? $baseline_measurement_data[$j]->hips : "";
        $thigh[$key] = $baseline_measurement_data[$j]->thigh1 ? $baseline_measurement_data[$j]->thigh1 : "";
        $thigh2[$key] = $baseline_measurement_data[$j]->thigh2 ? $baseline_measurement_data[$j]->thigh2 : "";
        $calf[$key] = $baseline_measurement_data[$j]->calf1 ? $baseline_measurement_data[$j]->calf1 : "";
        $calf2[$key] = $baseline_measurement_data[$j]->calf2 ? $baseline_measurement_data[$j]->calf2 : "";
    }
}

//removing empty data
$chest_dates = $selected_dates;
$arm_dates = $selected_dates;
$arm2_dates = $selected_dates;
$waist_dates = $selected_dates;
$hips_dates = $selected_dates;
$thigh_dates = $selected_dates;
$thigh2_dates = $selected_dates;
$calf_dates = $selected_dates;
$calf2_dates = $selected_dates;

//to remove the empty values in graph
for ($k = 0; $k < count($selected_dates); $k++) {
    if (isset($chest[$k]) && ($chest[$k] == '' || $chest[$k] == '0')) {
        unset($chest[$k]);
        unset($chest_dates[$k]);
    }
    if (isset($arm[$k]) && ($arm[$k] == '' || $arm[$k] == '0')) {
        unset($arm[$k]);
        unset($arm_dates[$k]);
    }
    if (isset($arm2[$k]) && ($arm2[$k] == '' || $arm2[$k] == '0')) {
        unset($arm2[$k]);
        unset($arm2_dates[$k]);
    }
    if (isset($waist[$k]) && ($waist[$k] == '' || $waist[$k] == '0')) {
        unset($waist[$k]);
        unset($waist_dates[$k]);
    }
    if (isset($hips[$k]) && ($hips[$k] == '' || $hips[$k] == '0')) {
        unset($hips[$k]);
        unset($hips_dates[$k]);
    }
    if (isset($thigh[$k]) && ($thigh[$k] == '' || $thigh[$k] == '0')) {
        unset($thigh[$k]);
        unset($thigh_dates[$k]);
    }
    if (isset($thigh2[$k]) && ($thigh2[$k] == '' || $thigh2[$k] == '0')) {
        unset($thigh2[$k]);
        unset($thigh2_dates[$k]);
    }
    if (isset($calf[$k]) && ($calf[$k] == '' || $calf[$k] == '0')) {
        unset($calf[$k]);
        unset($calf_dates[$k]);
    }
    if (isset($calf2[$k]) && ($calf2[$k] == '' || $calf2[$k] == '0')) {
        unset($calf2[$k]);
        unset($calf2_dates[$k]);
    }
}

$chest = array_values($chest);
$chest_dates = array_values($chest_dates);
$arm = array_values($arm);
$arm2 = array_values($arm2);
$arm_dates = array_values($arm_dates);
$arm2_dates = array_values($arm2_dates);
$waist = array_values($waist);
$waist_dates = array_values($waist_dates);
$hips = array_values($hips);
$hips_dates = array_values($hips_dates);
$thigh = array_values($thigh);
$thigh2 = array_values($thigh2);
$thigh_dates = array_values($thigh_dates);
$thigh2_dates = array_values($thigh2_dates);
$calf = array_values($calf);
$calf2 = array_values($calf2);
$calf_dates = array_values($calf_dates);
$calf2_dates = array_values($calf2_dates);

$no_data = 0;
if (count($chest_dates) <= 1 && count($arm_dates) <= 1 && count($arm2_dates) <= 1 && count($waist_dates) <= 1 && count($hips_dates) <= 1 && count($thigh_dates) <= 1 && count($thigh2_dates) <= 1 && count($calf_dates) <= 1 && count($calf2_dates) <= 1) {
    $no_data = 1;
}

include('member-header.php');
?>
<style type="text/css">
    #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;
    }
</style>
<?php include('menu.php'); ?>
<?php if ($remoteClient == 1 && in_array("circumference_measurements", $remote_client)) { ?>
    <script>
        window.location.href = "member_homepage.php";
    </script>
<?php } ?>

    <!-- 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"></div>

        <!-- Main Content -->
        <main class="main-content">
            <!-- Page Header -->
            <header class="page-header">
                <div class="page-header-meta">
                    <div>
                        <h1 class="page-header-title">Circumference Measurements</h1>
                        <p class="page-header-subtitle">Track your body measurements 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>
                        <!-- Calendar 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>

                    <!-- Hidden Date Range Form -->
                    <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($chest_dates) > 1) { ?>
                            <!-- Chest / Inches -->
                            <div class="chart-card">
                                <div class="chart-card-header">
                                    <h6 class="chart-card-title">Chest <span class="chart-card-unit">/ Inches</span></h6>
                                </div>
                                <div class="chart-wrapper">
                                    <div id="chartChest"></div>
                                </div>
                            </div>
                            <?php } ?>

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

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

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

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

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

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

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

                            <?php if (count($calf2_dates) > 1) { ?>
                            <!-- Calf R / Inches -->
                            <div class="chart-card">
                                <div class="chart-card-header">
                                    <h6 class="chart-card-title">Calf R <span class="chart-card-unit">/ Inches</span></h6>
                                </div>
                                <div class="chart-wrapper">
                                    <div id="chartCalfR"></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 chest = <?php echo json_encode($chest); ?>;
    var chest_dates = <?php echo json_encode($chest_dates); ?>;
    var arm = <?php echo json_encode($arm); ?>;
    var arm2 = <?php echo json_encode($arm2); ?>;
    var arm_dates = <?php echo json_encode($arm_dates); ?>;
    var arm2_dates = <?php echo json_encode($arm2_dates); ?>;
    var waist = <?php echo json_encode($waist); ?>;
    var waist_dates = <?php echo json_encode($waist_dates); ?>;
    var hips = <?php echo json_encode($hips); ?>;
    var hips_dates = <?php echo json_encode($hips_dates); ?>;
    var thigh = <?php echo json_encode($thigh); ?>;
    var thigh2 = <?php echo json_encode($thigh2); ?>;
    var thigh_dates = <?php echo json_encode($thigh_dates); ?>;
    var thigh2_dates = <?php echo json_encode($thigh2_dates); ?>;
    var calf = <?php echo json_encode($calf); ?>;
    var calf2 = <?php echo json_encode($calf2); ?>;
    var calf_dates = <?php echo json_encode($calf_dates); ?>;
    var calf2_dates = <?php echo json_encode($calf2_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) + ' in</div>' +
                        '</div>';
                }
            },
            markers: {
                size: 0,
                strokeWidth: 0,
                hover: { size: 5, sizeOffset: 0 }
            }
        };
    }

    var charts = [];

    if (no_data == 0) {
        // Chest
        if (chest_dates.length > 1) {
            var chestData = transformC3ToApex(chest_dates, chest);
            if (chestData.data.length > 0) {
                charts.push(new ApexCharts(document.querySelector("#chartChest"),
                    createApexChartOptions('#8B5CF6', chestData.data, chestData.categories, 'Chest / Inches')));
            }
        }

        // Arm L
        if (arm_dates.length > 1) {
            var armData = transformC3ToApex(arm_dates, arm);
            if (armData.data.length > 0) {
                charts.push(new ApexCharts(document.querySelector("#chartArmL"),
                    createApexChartOptions('#3B82F6', armData.data, armData.categories, 'Arm L / Inches')));
            }
        }

        // Arm R
        if (arm2_dates.length > 1) {
            var arm2Data = transformC3ToApex(arm2_dates, arm2);
            if (arm2Data.data.length > 0) {
                charts.push(new ApexCharts(document.querySelector("#chartArmR"),
                    createApexChartOptions('#60A5FA', arm2Data.data, arm2Data.categories, 'Arm R / Inches')));
            }
        }

        // Waist
        if (waist_dates.length > 1) {
            var waistData = transformC3ToApex(waist_dates, waist);
            if (waistData.data.length > 0) {
                charts.push(new ApexCharts(document.querySelector("#chartWaist"),
                    createApexChartOptions('#EF4444', waistData.data, waistData.categories, 'Waist / Inches')));
            }
        }

        // Hips
        if (hips_dates.length > 1) {
            var hipsData = transformC3ToApex(hips_dates, hips);
            if (hipsData.data.length > 0) {
                charts.push(new ApexCharts(document.querySelector("#chartHips"),
                    createApexChartOptions('#F59E0B', hipsData.data, hipsData.categories, 'Hips / Inches')));
            }
        }

        // Thigh L
        if (thigh_dates.length > 1) {
            var thighData = transformC3ToApex(thigh_dates, thigh);
            if (thighData.data.length > 0) {
                charts.push(new ApexCharts(document.querySelector("#chartThighL"),
                    createApexChartOptions('#10B981', thighData.data, thighData.categories, 'Thigh L / Inches')));
            }
        }

        // Thigh R
        if (thigh2_dates.length > 1) {
            var thigh2Data = transformC3ToApex(thigh2_dates, thigh2);
            if (thigh2Data.data.length > 0) {
                charts.push(new ApexCharts(document.querySelector("#chartThighR"),
                    createApexChartOptions('#34D399', thigh2Data.data, thigh2Data.categories, 'Thigh R / Inches')));
            }
        }

        // Calf L
        if (calf_dates.length > 1) {
            var calfData = transformC3ToApex(calf_dates, calf);
            if (calfData.data.length > 0) {
                charts.push(new ApexCharts(document.querySelector("#chartCalfL"),
                    createApexChartOptions('#F43F5E', calfData.data, calfData.categories, 'Calf L / Inches')));
            }
        }

        // Calf R
        if (calf2_dates.length > 1) {
            var calf2Data = transformC3ToApex(calf2_dates, calf2);
            if (calf2Data.data.length > 0) {
                charts.push(new ApexCharts(document.querySelector("#chartCalfR"),
                    createApexChartOptions('#EC4899', calf2Data.data, calf2Data.categories, 'Calf R / Inches')));
            }
        }

        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');

    const defaultActiveBtn = filterTabs.querySelector('.white-black-filter-btn.active');

    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;
    }

    function formatDateDisplay(d) {
        return d.toLocaleDateString('en-GB', {
            day: '2-digit',
            month: 'short',
            year: 'numeric'
        });
    }

    // Preset range buttons
    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);

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

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

            chartFilterForm.submit();
        });
    });

    // Calendar button opens modal
    calendarBtn.addEventListener('click', function() {
        dateRangeModal.style.display = 'flex';
        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
    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;
        }

        startDateInput.value = fromVal;
        endDateInput.value = toVal;

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

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

        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;

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

        dateRangeModal.style.display = 'none';
        chartFilterForm.submit();
    });

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

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

<script src="../coach/js/jquery-dropdown-datepicker.min.js"></script>
<script>
    $(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');
?>