<?php
$point = App\Models\Point::getOrCreateOnlyTopLevelPointOfCategory($note, 'TYPICAL_DAY_LIFESTYLE', $sessionKey, true);
$contentData = [
    "lines" => [
        [
            "S" => '',
            "I" => '',
            "P" => '',
        ]
    ],
    "estimated_daily_calories" => [
        "S" => '',
        "P" => '',
    ],
    "estimated_daily_protein_grams" => [
        "S" => '',
        "P" => '',
    ],
    "estimated_daily_vegetable_servings" => [
        "S" => '',
        "P" => '',
    ],
    "estimated_daily_hours_of_sleep" => [
        "S" => '',
        "P" => '',
    ]
];
if ($point->lastChildReview && $point->lastChildReview->data) {
    $point->lastChildReview->data = json_decode($point->lastChildReview->data, true);
    $contentData = $point->lastChildReview->data;
}
?>

<div visit-moe no-auto-save close-on-save close-on-cancel class="d-block p-3" id="typical_day_lifestyle-{{$note->id}}">
    <form show url="/api/visitPoint/upsertChildReview" class="mcp-theme-1 frm-upsert-review-typical-day-ls">
        <input type="hidden" name="uid" value="<?= $point->uid ?>">
        <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
        <input type="hidden" name="segmentUid" value="<?= $segment->uid ?>">
        <input type="hidden" name="data" value="{{json_encode($contentData)}}">

        <p class="mb-2 font-weight-bold">Typical Day</p>

        <table class="table table-sm table-bordered mb-2 stag-sheet allow-row-addition mb-3" lines>
            <thead class="bg-light">
            <tr>
                <th class="border-bottom-0 text-secondary width-30px"></th>
                <th class="border-bottom-0 text-secondary">Subjective</th>
                <th class="border-bottom-0 text-secondary width-100px">Impression</th>
                <th class="border-bottom-0 text-secondary w-50">Plan</th>
            </tr>
            </thead>
            <tbody>
                @foreach(@$contentData["lines"] as $line)
                    <tr>
                        <td class="align-middle text-center bg-light"><a href="#" class="delete-line"><i class="fa fa-trash-alt on-hover-opaque text-danger"></i></a></td>
                        <td><textarea rows="1" key="S">{{@$line['S']}}</textarea></td>
                        <td><textarea rows="1" key="I">{{@$line['I']}}</textarea></td>
                        <td><textarea rows="1" key="P">{{@$line['P']}}</textarea></td>
                    </tr>
                @endforeach
            </tbody>
        </table>

        <p class="mb-2 font-weight-bold">Daily Aggregates</p>

        <table class="table table-sm table-bordered mb-2 stag-sheet" aggregates>
            <thead class="bg-light">
            <tr>
                <th class="border-bottom-0 text-secondary width-200px">Subject</th>
                <th class="border-bottom-0 text-secondary">Current</th>
                <th class="border-bottom-0 text-secondary w-50">Target</th>
            </tr>
            </thead>
            <tbody>
                <tr>
                    <td class="pl-1 align-middle bg-light">Est. Daily Calories</td>
                    <td><textarea rows="1" key="estimated_daily_calories->S">{{@$contentData["estimated_daily_calories"]["S"]}}</textarea></td>
                    <td><textarea rows="1" key="estimated_daily_calories->P">{{@$contentData["estimated_daily_calories"]["P"]}}</textarea></td>
                </tr>
                <tr>
                    <td class="pl-1 align-middle bg-light">Est. Daily Protein Grams</td>
                    <td><textarea rows="1" key="estimated_daily_protein_grams->S">{{@$contentData["estimated_daily_protein_grams"]["S"]}}</textarea></td>
                    <td><textarea rows="1" key="estimated_daily_protein_grams->P">{{@$contentData["estimated_daily_protein_grams"]["P"]}}</textarea></td>
                </tr>
                <tr>
                    <td class="pl-1 align-middle bg-light">Est. Daily Vegetable Servings</td>
                    <td><textarea rows="1" key="estimated_daily_vegetable_servings->S">{{@$contentData["estimated_daily_vegetable_servings"]["S"]}}</textarea></td>
                    <td><textarea rows="1" key="estimated_daily_vegetable_servings->P">{{@$contentData["estimated_daily_vegetable_servings"]["P"]}}</textarea></td>
                </tr>
                <tr>
                    <td class="pl-1 align-middle bg-light">Est. Daily Hours Of Sleep</td>
                    <td><textarea rows="1" key="estimated_daily_hours_of_sleep->S">{{@$contentData["estimated_daily_hours_of_sleep"]["S"]}}</textarea></td>
                    <td><textarea rows="1" key="estimated_daily_hours_of_sleep->P">{{@$contentData["estimated_daily_hours_of_sleep"]["P"]}}</textarea></td>
                </tr>
            </tbody>
        </table>

        <div class="pt-2">
            <button submit class="btn btn-sm btn-primary mr-2"><i class="fa fa-save"></i></button>
            <div class="d-inline-flex align-self-stretch align-items-center">
                <span class="autosave-indicator saving text-sm text-secondary">Saving changes &hellip;</span>
                <span class="autosave-indicator saved text-sm text-secondary">
                    <i class="fa fa-check"></i>
                    Saved
                </span>
            </div>
        </div>
    </form>
</div>
<script>
    (function() {
        function init() {
            let parentSegment = $('[data-segment-template-name="typical_day_lifestyle"] ');

            function getRowBefore(_tr) {
                return _tr.prev();
            }

            function moveToPrevRowInput(_td) {
                let tr = getRowBefore(_td.closest('tr'));
                tr.find('td:eq(' + _td.index() + ') textarea').first().focus();
            }

            function getRowAfter(_tr) {
                return _tr.next();
            }

            function getOrCreateRowAfter(_tr) {
                let tr = getRowAfter(_tr);
                if(!tr.length) {
                    tr = newRow().insertAfter(_tr);
                }
                return tr;
            }

            function createRowAfter(_tr) {
                return newRow().insertAfter(_tr);
            }

            function newRow() {
                return $('<tr><td class="align-middle text-center bg-light"><a href="#" class="delete-line"><i class="fa fa-trash-alt on-hover-opaque text-danger"></i></a></td>' +
                    '<td><textarea rows="1" key="S"></textarea></td>' +
                    '<td><textarea rows="1" key="I"></textarea></td>' +
                    '<td><textarea rows="1" key="P"></textarea></td></tr>');
            }

            function createAndMoveToNextRowInput(_td) {
                let tr = createRowAfter(_td.closest('tr'));
                tr.find('td:eq(' + _td.index() + ') textarea').first().focus();
            }

            function moveToNextRowInput(_td, _forceCreate = false) {
                let tr = _forceCreate ? getOrCreateRowAfter(_td.closest('tr')) : getRowAfter(_td.closest('tr'));
                if(tr.length) {
                    tr.find('td:eq(' + _td.index() + ') textarea').first().focus();
                }
            }

            function moveToPrevInput(_td) {
                _td.prev().find('textarea').first().focus();
            }

            function moveToNextInput(_td) {
                _td.next().find('textarea').first().focus();
            }

            function generateData(_parentSegment) {
                let data = {};
                let lines = [];
                _parentSegment.find('.stag-sheet[lines] tbody tr').each(function() {
                    let line = {};
                    $(this).find('textarea').each(function() {
                        line[$(this).attr('key')] = this.value;
                    });
                    lines.push(line);
                });
                data.lines = lines;
                data.estimated_daily_calories = {
                    S: _parentSegment.find('.stag-sheet[aggregates] textarea[key="estimated_daily_calories->S"]').val(),
                    P: _parentSegment.find('.stag-sheet[aggregates] textarea[key="estimated_daily_calories->P"]').val()
                };
                data.estimated_daily_protein_grams = {
                    S: _parentSegment.find('.stag-sheet[aggregates] textarea[key="estimated_daily_protein_grams->S"]').val(),
                    P: _parentSegment.find('.stag-sheet[aggregates] textarea[key="estimated_daily_protein_grams->P"]').val()
                };
                data.estimated_daily_vegetable_servings = {
                    S: _parentSegment.find('.stag-sheet[aggregates] textarea[key="estimated_daily_vegetable_servings->S"]').val(),
                    P: _parentSegment.find('.stag-sheet[aggregates] textarea[key="estimated_daily_vegetable_servings->P"]').val()
                };
                data.estimated_daily_hours_of_sleep = {
                    S: _parentSegment.find('.stag-sheet[aggregates] textarea[key="estimated_daily_hours_of_sleep->S"]').val(),
                    P: _parentSegment.find('.stag-sheet[aggregates] textarea[key="estimated_daily_hours_of_sleep->P"]').val()
                };
                return JSON.stringify(data);
            }

            function autoSave() {
                parentSegment.find('[name="data"]').val(generateData(parentSegment));
                parentSegment.find('[name="data"]').trigger('save-trigger');
            }

            function autoGrowTextarea(_textarea) {
                _textarea.style.minHeight = "100%";
                _textarea.style.height = "calc(1.5em + .5rem + 2px)";
                _textarea.style.height = (_textarea.scrollHeight)+"px";
            }

            parentSegment
                .off('keydown', '.stag-sheet textarea')
                .on('keydown', '.stag-sheet textarea', function(_e) {
                    switch (_e.which) {
                        case 13: // ENTER: If shift NOT pressed, move to next row same column
                            if (!_e.shiftKey) {
                                if($(this).closest('.stag-sheet').is('.allow-row-addition')) {
                                    createAndMoveToNextRowInput($(this).closest('td'), );
                                }
                                else {
                                    moveToNextRowInput($(this).closest('td'), false);
                                }
                                return false;
                            }
                            break;
                        case 38: // UP: If caret already at 0, move up to prev row same column
                            if (this.selectionStart === this.selectionEnd && this.selectionStart === 0) {
                                moveToPrevRowInput($(this).closest('td'));
                                return false;
                            }
                            break;
                        case 40: // DOWN: If caret already at end, move down to next row same column
                            if (this.selectionStart === this.selectionEnd && this.selectionStart === this.value.length) {
                                moveToNextRowInput($(this).closest('td'));
                                return false;
                            }
                            break;
                        case 37: // LEFT: If caret already at 0, move left to prev column
                            if (this.selectionStart === this.selectionEnd && this.selectionStart === 0) {
                                moveToPrevInput($(this).closest('td'));
                                return false;
                            }
                            break;
                        case 39: // DOWN: If caret already at end, move right to next column
                            if (this.selectionStart === this.selectionEnd && this.selectionStart === this.value.length) {
                                moveToNextInput($(this).closest('td'));
                                return false;
                            }
                            break;
                        case 8: // BACKSPACE: If caret already at 0, move left to prev column
                            break;
                    }

                });

            parentSegment
                .off('input paste cut change', '.stag-sheet textarea')
                .on('input paste cut change', '.stag-sheet textarea', function() {
                    autoSave();
                });

            parentSegment
                .off('click.delete-line', '.stag-sheet .delete-line')
                .on('click.delete-line', '.stag-sheet .delete-line', function() {
                    let tr = $(this).closest('tr');
                    let isFirst = (tr.index() === 0);
                    if(isFirst) {
                        newRow().insertAfter(tr);
                    }
                    tr.remove();
                    autoSave();
                    return false;
                });

            parentSegment.find('.stag-sheet textarea').each(function() {
                autoGrowTextarea(this);
            });

            parentSegment
                .off('edit-mode-activated')
                .on('edit-mode-activated', function() {
                    parentSegment.find('.stag-sheet textarea').each(function() {
                        autoGrowTextarea(this);
                    });
                });

        }
        window.segmentInitializers.typical_day_lifestyle = init;
        addMCInitializer('typical_day_lifestyle-{{$note->id}}', init, '#typical_day_lifestyle-{{$note->id}}');
    }).call(window);
</script>
