@extends ('layouts.patient')
@section('inner-content')

    <link href="/c3/c3.min.css" rel="stylesheet">
    <script src="/c3/d3.v5.min.js" charset="utf-8"></script>
    <script src="/c3/c3.min.js"></script>

    <div class="d-flex align-items-center">
        <h4 class="font-weight-bold mb-0 text-secondary font-size-16">Vitals Graph</h4>
        <?php
        $months = [];
        $monthNames = [];
        for ($i=6; $i>=0; $i--) {
            $m = date_sub(date_create(), date_interval_create_from_date_string($i . " month" . ($i === 1 ? '' : 's')));
            $monthNames[] = date_format($m, "M, Y");
            $months[] = date_format($m, "Y-m-01");
        }
        $current = $filter ? $filter : $months[count($months) - 1];
        ?>
        <select class="ml-auto max-width-200px form-control form-control-sm"
                onchange="fastLoad('/patients/view/{{$patient->uid}}/vitals-graph/' + this.value, true, false, false)">
            <?php for ($i=count($months) - 1; $i>=0; $i--): ?>
            <option value="{{$months[$i]}}" {{ $current === $months[$i] ? 'selected' : '' }}>{{$monthNames[$i]}}</option>
            <?php endfor; ?>
        </select>
    </div>

    <hr class="m-neg-4">

    <div id="vitalsGraphComponent" class="stag-chart">
        <h4 class="font-weight-bold mb-3 text-secondary font-size-14 text-center">Blood Pressure</h4>
        <div id="bp-chart" class="mb-4">BP Graph</div>
        <hr class="m-neg-4">
        <h4 class="font-weight-bold mb-3 text-secondary font-size-14 text-center">Weight</h4>
        <div id="weight-chart">Weight Graph</div>
    </div>

    <?php
    $dates = [];
    $startDate = $current;
    $nextMonthFirstDay = date_format(date_add(date_create($startDate), date_interval_create_from_date_string("1 month")), 'Y-m-d');

    $nextDay = $startDate;
    while ($nextDay !== $nextMonthFirstDay) {
        $dates[] = $nextDay;
        $nextDay = date_format(date_add(date_create($nextDay), date_interval_create_from_date_string('1 day')), 'Y-m-d');
    }

    $allMeasurements = $patient->nonZeroMeasurements->toArray();

    $bpData = [];
    $weightData = [];

    for ($i=0; $i<count($dates); $i++) {

        $date = $dates[$i];

        // sbp
        $sbp = array_filter($allMeasurements, function($_measurement) use ($date) {
            return $_measurement['label'] === 'SBP' && $_measurement['effective_date'] === $date;
        });
        if(count($sbp)) {
            $sbp = array_values($sbp);
            $sbp = $sbp[count($sbp) - 1];
        }
        else {
            $sbp = null;
        }
        // dbp
        $dbp = null;
        if($sbp) {
            $dbp = array_filter($allMeasurements, function($_measurement) use ($date) {
                $measurementDate = date('Y-m-d', strtotime($_measurement['effective_date']));
                return $_measurement['label'] === 'DBP' && $measurementDate === $date;
            });
            if(count($dbp)) {
                $dbp = array_values($dbp);
                $dbp = $dbp[count($dbp) - 1];
            }
            else {
                $dbp = null;
            }
        }
        if ($sbp && $dbp) {
            $bpData[] = [
                "date" => $date,
                "sbp" => $sbp["numeric_value"],
                "dbp" => $dbp["numeric_value"]
            ];
        }

        // weight
        $weight = array_filter($allMeasurements, function($_measurement) use ($date) {
            return $_measurement['label'] === 'Wt. (lbs.)' && $_measurement['effective_date'] === $date && !!$_measurement['numeric_value'];
        });
        if(count($weight)) {
            $weight = array_values($weight);
            $weight = $weight[count($weight) - 1];
            $weightData[] = [
                "date" => $date,
                "weight" => $weight["numeric_value"]
            ];
        }

    }

    $bpDates = [];
    $sbpValues = [];
    $dbpValues = [];
    for ($i = 0; $i < count($bpData); $i++) {
        $bpDates[] = $bpData[$i]['date'];
        $sbpValues[] = $bpData[$i]['sbp'];
        $dbpValues[] = $bpData[$i]['dbp'];
    }

    $weightDates = [];
    $weightValues = [];
    for ($i = 0; $i < count($weightData); $i++) {
        $weightDates[] = $weightData[$i]['date'];
        $weightValues[] = $weightData[$i]['weight'];
    }

    ?>

    <script>
        (function() {
            function init() {
                bpChart();
                weightChart();
            }
            function bpChart() {
                var chart = c3.generate({
                    bindto: '#bp-chart',
                    data: {
                        x: 'x',
                        // xFormat: '%Y%m%d', // 'xFormat' can be used as custom format of 'x'
                        columns: [
                            ['x', <?= implode(", ", array_map(function($_x) { return "'" . $_x . "'"; }, $bpDates)) ?>],
                            ['Systolic BP', <?= implode(", ", array_map(function($_x) { return "'" . $_x . "'"; }, $sbpValues)) ?>],
                            ['Diastolic BP', <?= implode(", ", array_map(function($_x) { return "'" . $_x . "'"; }, $dbpValues)) ?>]
                        ]
                    },
                    axis: {
                        x: {
                            type: 'timeseries',
                            tick: {
                                format: '%Y-%m-%d',
                                multiline: true,
                                fit: true,
                                rotate: -45
                            },
                        },
                        y: {
                            show: true,
                            label: {
                                text: 'Blood Pressure (mmHg)',
                                position: 'outer-middle'
                            },
                            min: 60,
                            max: 220
                        },
                    },
                    regions: [
                        {axis: 'y', start: 100, end: 130, class: 'safe-region', label: 'Safe Systolic BP: 100 to 130 mmHg'},
                        {axis: 'y', start: 60, end: 90, class: 'safe-region', label: 'Safe Diastolic BP: 60 to 90 mmHg'}
                    ]
                });
            }
            function weightChart() {
                var chart = c3.generate({
                    bindto: '#weight-chart',
                    data: {
                        x: 'x',
                        columns: [
                            ['x', <?= implode(", ", array_map(function($_x) { return "'" . $_x . "'"; }, $weightDates)) ?>],
                            ['Weight', <?= implode(", ", array_map(function($_x) { return "'" . $_x . "'"; }, $weightValues)) ?>]
                        ]
                    },
                    axis: {
                        x: {
                            type: 'timeseries',
                            tick: {
                                format: '%Y-%m-%d',
                                multiline: true,
                                fit: true,
                                rotate: -45
                            },
                        },
                        y: {
                            show: true,
                            label: {
                                text: 'Weight (lbs)',
                                position: 'outer-middle'
                            },
                            min: 70,
                            max: 250
                        },
                    },
                    regions: [
                        // {axis: 'y', start: 100, end: 140, class: 'safe-region', label: 'Safe Weight: 100 to 140 lbs'},
                    ]
                });
            }
            addMCInitializer('vitalsGraph', init, '#vitalsGraphComponent');
        }).call(window);
    </script>

@endsection
