<?php
$fields = [
    [
        "Head:::Trauma",
        "Eyes:::Blindness|Cataracts|Glaucoma|Wears glasses/contacts",
        "Ears:::Hearing aids",
        "Nose/Sinuses:::Allergic Rhinitis|Sinus infections",
        "Mouth/Throat/Teeth:::Dentures",
        "Cardiovascular:::Aneurysm|Angina|DVT|Dysrhythmia|HTN|Murmur|Myocardial infarction|Other heart disease",
    ],
    [
        "Respiratory:::Asthma|Bronchitis|COPD - Bronchitis/Emphysema|Pleuritis|Pneumonia",
        "Gastrointestinal:::Cirrhosis|GERD|Gallbladder disease|Heartburn|Hemorrhoids|Hepatitis|Hiatal hernia|Jaundice|Ulcer",
        "Genitourinary:::Hernia|Incontinence|Nephrolithiasis|Other kidney disease|STDs|UTI(s)",
    ],
    [
        "Musculoskeletal:::Arthritis|Gout|M/S injury",
        "Skin:::Dermatitis|Mole(s)|Other skin condition(s)|Psoriasis",
        "Neurological:::Epilepsy|Seizures|Severe headaches, migraines|Stroke|TIA",
        "Psychiatric:::Bipolar disorder|Depression|Hallucinations, delusions|Suicidal ideation|Suicide attempts",
    ],
    [
        "Endocrine:::Goiter|Hyperlipidemia|Hypothyroidism|Thyroid disease|Thyroiditis|Type I DM|Type II DM",
        "Heme/Onc:::Anemia|Cancer",
        "Infectious:::HIV|STDs|Tuberculosis (dz)|Tuberculosis (exposure)",
    ]
];

$customFields = [];

if($section) {
    $customItems = $section->sectionTemplate->customItems;
    $perColumn = floor(count($customItems) / 4);
    if($perColumn < 5) $perColumn = 5;
    $inColumn = 0;
    foreach ($customItems as $customItem) {
        if(!isset($customFields[$inColumn])) $customFields[$inColumn] = [];
        $customFields[$inColumn][] = $customItem->label;
        if(count($customFields[$inColumn]) >= $perColumn) {
            $inColumn++;
        }
    }
    for ($i=0; $i<count($customFields); $i++) {
        $customFields[$i] = [':::' . implode("|", $customFields[$i])];
    }
}

//$customFields = [
//    [
//        ":::Anxiety disorder|BPH|carpal tunnel|CHF|Degernative Disc Disorder|Fibromyalgia",
//    ],
//    [
//        ":::Hard of Hearing|Hearing Impairment|Lupus|Multiple Falls|Multiple kidney stones|Multiple Rib Fractures",
//    ],
//    [
//        ":::Neuropathy|Obesity|Obstructive Sleep Apnea|Primary immunodeficiency diso|pulmonary hypertension|Restless Leg Syndrome",
//    ],
//    [
//        ":::Rhinitis|Russell Silver Syndrome|transverse myelitis|Vertigo",
//    ]
//];

$contentData = false;
if($section){
    $contentData = json_decode($section->content_data, true);
}
if(!$contentData) {
    $contentData = [];
}
for ($i = 0; $i < count($fields); $i++) {
    for($j = 0; $j < count($fields[$i]); $j++) {
        $parts = explode(":::", $fields[$i][$j]);
        $head = 'custom';
        if(!empty($parts[0])) $head = $parts[0];
        $values = explode("|", $parts[1]);
        for($k = 0; $k < count($values); $k++) {
            $fName = $head . '_' . sanitize_field_name($values[$k]);
            if(!isset($contentData[$fName])) {
                $contentData[$fName] = '';
            }
        }
    }
}
for ($i = 0; $i < count($customFields); $i++) {
    for($j = 0; $j < count($customFields[$i]); $j++) {
        $parts = explode(":::", $customFields[$i][$j]);
        $head = 'custom';
        if(!empty($parts[0])) $head = $parts[0];
        $values = explode("|", $parts[1]);
        for($k = 0; $k < count($values); $k++) {
            $fName = $head . '_' . sanitize_field_name($values[$k]);
            if(!isset($contentData[$fName])) {
                $contentData[$fName] = '';
            }
        }
    }
}

$formID = rand(0, 100000);
?>
<form method="POST" action="/process_form_submit" onsubmit="return submitForm_NoteSection_{{ $formID }}(this);">
    <?php if($section): ?>
        <input type="hidden" name="section_uid" value="<?= $section->uid?>">
    <?php else: ?>
        <input type="hidden" name="note_uid" value="<?= $note->uid?>">
        <input type="hidden" name="section_template_uid" value="<?= $sectionTemplate->uid ?>">
    <?php endif; ?>

    <div class="mb-3 d-flex align-items-start">
        <div class="width-100px mr-3">
            <label class="text-secondary mb-1">Blood Type</label>
            <select name="blood_type" class="form-control form-control-sm width-100px">
                <option value=""> -- select -- </option>
                <option <?= isset($contentData['blood_type']) && $contentData['blood_type'] === 'A' ? 'selected' : '' ?> value="A">A</option>
                <option <?= isset($contentData['blood_type']) && $contentData['blood_type'] === 'AB' ? 'selected' : '' ?> value="AB">AB</option>
                <option <?= isset($contentData['blood_type']) && $contentData['blood_type'] === 'B' ? 'selected' : '' ?> value="B">B</option>
                <option <?= isset($contentData['blood_type']) && $contentData['blood_type'] === 'O' ? 'selected' : '' ?> value="O">O</option>
            </select>
        </div>
        <div class="width-100px mr-3">
            <label class="text-secondary mb-1">RH</label>
            <select name="blood_rh" class="form-control form-control-sm width-100px">
                <option value=""> -- select -- </option>
                <option <?= isset($contentData['blood_rh']) && $contentData['blood_rh'] === '+ve' ? 'selected' : '' ?> value="+ve">+ve</option>
                <option <?= isset($contentData['blood_rh']) && $contentData['blood_rh'] === '-ve' ? 'selected' : '' ?> value="-ve">-ve</option>
            </select>
        </div>
    </div>

    <div class="row mb-3">
        @for ($i = 0; $i < count($fields); $i++)
            <div class="col-md-3">
                @for($j = 0; $j < count($fields[$i]); $j++)
                    <?php
                        $parts = explode(":::", $fields[$i][$j]);
                        $head = 'custom';
                        if(!empty($parts[0])) $head = $parts[0];
                        $values = explode("|", $parts[1]);
                    ?>
                    @if($head !== 'custom')
                        <div class="font-weight-bold mb-2">{{ $head }}</div>
                    @endif
                    @for($k = 0; $k < count($values); $k++)
                        <?php
                            if(isset($values[$k])){
                                $fName = $head . '_' . sanitize_field_name($values[$k]);
                            }
                        ?>
                        <label class="d-flex align-items-center mb-1">
                            <input type="checkbox" name="{{ $fName }}" class="m-0"
                                   onchange="onItemSelected_{{ $formID }}(this)"
                                   {{ $contentData[$fName] ? 'checked' : '' }}>
                            <span class="mx-2">{{ $values[$k] }}</span>
                            <div moe>
                                <a href="#" start show>
                                    <i class="<?= trim(@$contentData[$fName . '__comments']) === '' ? 'far' : 'fas' ?> <?= $contentData[$fName] ? '' : 'd-none' ?> fa-comment"></i>
                                </a>
                                <div url="/nop">
                                    <div class="mb-2">
                                        <textarea name="{{ $fName }}__comments"
                                                  onchange="onCommentChange_{{ $formID }}(this)"
                                                  onkeyup="onCommentChange_{{ $formID }}(this)"
                                                  onpaste="onCommentChange_{{ $formID }}(this)"
                                                  class="form-control form-control-sm ns-custom-comment"
                                        >{{ @$contentData[$fName . '__comments'] }}</textarea>
                                    </div>
                                    <div class="">
                                        <button type="button" class="btn btn-sm btn-primary" cancel>Close
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </label>
                    @endfor
                @endfor
            </div>
        @endfor
    </div>

    <div class="row border-top pt-3">
        <div class="col-12">
            <div class="d-flex align-items-center mb-2">
                <span class="font-weight-bold">Custom Items</span>
                <span class="mx-2 text-secondary">|</span>
                <div moe>
                    <a href="#" start show>Add</a>
                    <div custom-item-form url="/api/sectionTemplateCustomItem/create">
                        <div class="mb-2">
                            <input type="text" placeholder="Label" class="form-control form-control-sm label_new_custom_item">
                        </div>
                        <div>
                            <button type="button" class="btn btn-sm btn-primary mr-1"
                                    onclick="return saveCustomItem_{{ $formID }}($(this).closest('[moe]'))">Submit</button>
                            <button type="button" class="btn btn-sm btn-default border"
                                    onclick="return cancelCustomItem_{{ $formID }}()">Cancel</button>
                        </div>
                    </div>
                </div>
            </div>

            @if($customFields && count($customFields))
                <div class="row mb-3">
                    @for ($i = 0; $i < count($customFields); $i++)
                        <div class="col-md-3 custom-field-column" data-column="{{ $i + 1 }}">
                            @for($j = 0; $j < count($customFields[$i]); $j++)
                                <?php
                                $parts = explode(":::", $customFields[$i][$j]);
                                $head = 'custom';
                                if(!empty($parts[0])) $head = $parts[0];
                                $values = explode("|", $parts[1]);
                                ?>
                                @if($head !== 'custom')
                                    <div class="font-weight-bold mb-2">{{ $head }}</div>
                                @endif
                                @for($k = 0; $k < count($values); $k++)
                                    <?php
                                    $fName = $head . '_' . sanitize_field_name($values[$k]);
                                    ?>
                                    <label class="d-flex align-items-center mb-1">
                                        <input type="checkbox" name="{{ $fName }}" class="m-0"
                                               onchange="onItemSelected_{{ $formID }}(this)"
                                            {{ $contentData[$fName] ? 'checked' : '' }}>
                                        <span class="mx-2">{{ $values[$k] }}</span>
                                        <div moe>
                                            <a href="#" start show>
                                                <i class="<?= trim(@$contentData[$fName . '__comments']) === '' ? 'far' : 'fas' ?> <?= $contentData[$fName] ? '' : 'd-none' ?> fa-comment"></i>
                                            </a>
                                            <div url="/nop">
                                                <div class="mb-2">
                                        <textarea name="{{ $fName }}__comments"
                                                  onchange="onCommentChange_{{ $formID }}(this)"
                                                  onkeyup="onCommentChange_{{ $formID }}(this)"
                                                  onpaste="onCommentChange_{{ $formID }}(this)"
                                                  class="form-control form-control-sm ns-custom-comment"
                                        >{{ @$contentData[$fName . '__comments'] }}</textarea>
                                                </div>
                                                <div class="">
                                                    <button type="button" class="btn btn-sm btn-primary" cancel>Close
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </label>
                                @endfor
                            @endfor
                        </div>
                    @endfor
                </div>
            @else
                <div class="row mb-3">
                    <div class="col-md-3 custom-field-column" data-column="1"></div>
                </div>
            @endif
        </div>
    </div>

    <div class="row mb-3">
        <div class="col-12">
            <textarea rte type="text" class="form-control form-control-sm p-2"
                      name="comments"
                      data-shortcuts=""
                      placeholder="Value"><?= isset($contentData['comments']) ? $contentData['comments'] : '' ?></textarea>
        </div>
    </div>

    <div class="form-group m-0 d-flex">
        <button class="btn btn-sm btn-primary mr-2">Submit</button>
        <button class="btn btn-sm btn-default border" onclick="return cancelForm_NoteSection_{{ $formID }}(this)">Cancel</button>
    </div>
</form>
<script>
    function submitForm_NoteSection_{{ $formID }}(_form) {
        showMask();
        $.post(_form.action, $(_form).serialize(), function(_data) {
            fastReload();
        });
        return false;
    }
    function cancelForm_NoteSection_{{ $formID }}(_trigger) {
        $(_trigger).closest('.note-section').toggleClass('edit');
        return false;
    }
    function onCommentChange_{{ $formID }}(_trigger) {
        _trigger = $(_trigger);
        var empty = $.trim(_trigger.val()) === '';
        if(empty) {
            _trigger.closest('[moe]').find('i').first().removeClass('fas').addClass('far');
        }
        else {
            _trigger.closest('[moe]').find('i').first().removeClass('far').addClass('fas');
        }
    }
    function onItemSelected_{{ $formID }}(_trigger) {
        if(_trigger.checked) {
            $(_trigger).siblings('[moe]').find('i').first().removeClass('d-none');
        }
        else {
            $(_trigger).siblings('[moe]').find('i').first().addClass('d-none');
        }
    }
    function saveCustomItem_{{ $formID }}(_moe) {
        console.log('saveCustomItem_{{ $formID }}');
        let label = $.trim(_moe.find('.label_new_custom_item').first().val());
        if(!label) return false;
        showMask();
        $.post('/api/sectionTemplateCustomItem/create', {
            sectionTemplateUid: '{{ $section->sectionTemplate->uid }}',
            label: label
        }, function(_data) {
            hideMask();
            if(_data && _data.success) {
                appendCustomItem(label);
                hideMoeFormMask();
                $('[custom-item-form]').hide();
            }
            else {
                toastr.error(_data.message);
            }
        }, 'json');
        return false;
    }
    function cancelCustomItem_{{ $formID }}(_moe) {
        hideMoeFormMask();
        $('div[moe]').hide();
        return false;
    }
    function appendCustomItem(_name) {
        let sanitized = 'custom_' + _name.toLowerCase().replace(/[^0-9a-z]/ig, '_');
        let html = '<label class="d-flex align-items-center mb-1">' +
            '<input type="checkbox" name="' + sanitized + '" class="m-0" onchange="onItemSelected_{{ $formID }}(this)">' +
                '<span class="mx-2">' + _name + '</span>' +
                '<div moe>' +
                    '<a href="#" start show><i class="far d-none fa-comment"></i></a>' +
                    '<div url="/nop">' +
                        '<div class="mb-2">' +
                            '<textarea name="' + _name + '__comments" onchange="onCommentChange_{{ $formID }}(this)" onkeyup="onCommentChange_{{ $formID }}(this)" onpaste="onCommentChange_{{ $formID }}(this)" class="form-control form-control-sm ns-custom-comment"></textarea>' +
                        '</div>' +
                        '<div class=""><button type="button" class="btn btn-sm btn-primary" cancel>Close</button></div>' +
                    '</div>' +
                '</div>' +
            '</label>';
        let targetColumn = $('.custom-field-column').first(), numItems = -1;
        $('.custom-field-column').each(function() {
            if(numItems === -1 || numItems > $(this).find('>label').length) {
                numItems = $(this).find('>label').length;
                targetColumn = $(this);
            }
        });
        targetColumn.append(html);
        initMoes();
    }
</script>
