<?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_screen.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();

$bp1 = array('Systolic / mm Hg');
$bp2 = array('Diastolic / mm Hg');

$blood_pressure_data = array();

if (isset($_POST['form_submit']) && ($_POST['form_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;
}
$screen = new Baseline_screen();

//getting baseline details
$blood_pressure_data = $screen->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);
    $bp1[] = '';
    $bp2[] = '';
    $i = strtotime('+1 day', $i);
    $arr++;
}

for ($j = 0; $j < count($blood_pressure_data); $j++) {
    if (in_array(date('m/d/y', strtotime($blood_pressure_data[$j]->date)), $selected_dates)) {
        $key = array_search(date('m/d/y', strtotime($blood_pressure_data[$j]->date)), $selected_dates);
        $bp_exp = explode('/', $blood_pressure_data[$j]->blood_presure);
        $bp1[$key] = isset($bp_exp[0]) ? $bp_exp[0] : "";
        $bp2[$key] = isset($bp_exp[1]) ? $bp_exp[1] : "";
    }
}

//removing empty data
$bp1_dates = $selected_dates;
$bp2_dates = $selected_dates;

//to remove the empty values in graph
for ($k = 0; $k < count($selected_dates); $k++) {
    if ($bp1[$k] == '' || $bp1[$k] == '0') {
        unset($bp1[$k]);
        unset($bp1_dates[$k]);
    }
    if ($bp2[$k] == '' || $bp2[$k] == '0') {
        unset($bp2[$k]);
        unset($bp2_dates[$k]);
    }
}
$bp1 = array_values($bp1);
$bp2 = array_values($bp2);
$bp1_dates = array_values($bp1_dates);
$bp2_dates = array_values($bp2_dates);

$no_data = 0;
if (count($bp1_dates) <= 1 && count($bp2_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("blood_preasure", $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">Blood Pressure</h1>
                        <p class="page-header-subtitle">Track Your Blood Pressure 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="form_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($bp1_dates) > 1) { ?>
                            <!-- Systolic / mmHg -->
                            <div class="chart-card">
                                <div class="chart-card-header">
                                    <h6 class="chart-card-title">Systolic <span class="chart-card-unit">/ mmHg</span></h6>
                                </div>
                                <div class="chart-wrapper">
                                    <div id="chartSystolic"></div>
                                </div>
                            </div>
                            <?php } ?>

                            <?php if (count($bp2_dates) > 1) { ?>
                            <!-- Diastolic / mmHg -->
                            <div class="chart-card">
                                <div class="chart-card-header">
                                    <h6 class="chart-card-title">Diastolic <span class="chart-card-unit">/ mmHg</span></h6>
                                </div>
                                <div class="chart-wrapper">
                                    <div id="chartDiastolic"></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 bp1 = <?php echo json_encode($bp1); ?>;
    var bp2 = <?php echo json_encode($bp2); ?>;
    var bp1_dates = <?php echo json_encode($bp1_dates); ?>;
    var bp2_dates = <?php echo json_encode($bp2_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 createChartOptions(color, data, categories, yLabel, yMin, yMax, tickAmount, unit, minNormal, maxNormal) {
        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
                },
                offsetX: -12,
                parentHeightOffset: 0,
                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 },
            // ===== RED DOTTED MEDICAL RANGE LINES =====
            annotations: {
                yaxis: [
                    {
                        y: minNormal,
                        borderColor: '#EF4444',
                        strokeDashArray: 6,
                        borderWidth: 1.5,
                        label: {
                            borderColor: '#EF4444',
                            style: {
                                color: '#fff',
                                background: '#EF4444',
                                fontSize: '10px'
                            },
                            text: 'Min ' + minNormal
                        }
                    },
                    {
                        y: maxNormal,
                        borderColor: '#EF4444',
                        strokeDashArray: 6,
                        borderWidth: 1.5,
                        label: {
                            borderColor: '#EF4444',
                            style: {
                                color: '#fff',
                                background: '#EF4444',
                                fontSize: '10px'
                            },
                            text: 'Max ' + maxNormal
                        }
                    }
                ]
            },
            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: {
                min: yMin,
                max: yMax,
                tickAmount: tickAmount,
                offsetX: -12,
                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) + ' ' + unit + '</div>' +
                        '</div>';
                }
            },
            markers: {
                size: 0,
                strokeWidth: 0,
                hover: { size: 5, sizeOffset: 0 }
            }
        };
    }

    var charts = [];

    if (no_data == 0) {
        // Systolic (medical range: 90-120)
        if (bp1_dates.length > 1) {
            var bp1Data = transformC3ToApex(bp1_dates, bp1);
            if (bp1Data.data.length > 0) {
                charts.push(new ApexCharts(document.querySelector("#chartSystolic"),
                    createChartOptions(
                        '#1D4ED8',           // color (blue)
                        bp1Data.data,        // data
                        bp1Data.categories,  // categories
                        'Systolic',          // label
                        90,                  // yMin
                        160,                 // yMax
                        7,                   // tickAmount
                        'mmHg',              // unit
                        90,                  // minNormal
                        120                  // maxNormal
                    )));
            }
        }

        // Diastolic (medical range: 60-80)
        if (bp2_dates.length > 1) {
            var bp2Data = transformC3ToApex(bp2_dates, bp2);
            if (bp2Data.data.length > 0) {
                charts.push(new ApexCharts(document.querySelector("#chartDiastolic"),
                    createChartOptions(
                        '#60A5FA',           // color (light blue)
                        bp2Data.data,        // data
                        bp2Data.categories,  // categories
                        'Diastolic',         // label
                        50,                  // yMin
                        100,                 // yMax
                        5,                   // tickAmount
                        'mmHg',              // unit
                        60,                  // minNormal
                        80                   // maxNormal
                    )));
            }
        }

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