@extends('layouts.app')

@section('content')

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8 main-area">
            <h1 style="text-align: center;">
                符合代謝新收案  早鳥報名最划算
            </h1>
        </div>
    </div>
    <div style="height:20px;">&nbsp;</div>

    <div class="row justify-content-center">
        <div class="col-md-8 main-area">
            <h2 style="text-align: center;">報名表單</h2>

            <form id="dataForm" method="POST" action="/metabolism_fill_form" enctype="multipart/form-data" style="font-size: 1.4em; ">
                @csrf
                @if ($errors->any())
                    <div class="text-left mt-3 alert alert-block alert-dismissible alert-danger">
                        
                        <ul>
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif
                @if ($message = Session::get('success'))
                    <div class="text-left mt-3 alert alert-block alert-dismissible alert-success ">
                        
                        <strong>{{ $message }}</strong>
                    </div>
                @endif
                <div class="card">
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">疾病類別</label>
                            <div class="form-control" >
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="disease_type" id="diseaseType1" value="1" {{ old('disease_type') == "1" ? 'checked' : '' }} required>
                                    <label class="form-check-label" for="diseaseType1">
                                        代謝症候群（代謝症候群者）
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="disease_type" id="diseaseType5" value="5" {{ old('disease_type') == "5" ? 'checked' : '' }} required>
                                    <label class="form-check-label" for="diseaseType5">
                                        代謝症候群（糖尿病前期者）
                                    </label>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="regHospitalName" class="form-label">就醫院所</label>
                            <input type="text" class="form-control" id="regHospitalName" name="hospital_name" required value="{{ old('hospital_name') }}" placeholder="範例：XX醫院">
                        </div>
                        <div class="mb-3">
                            <label for="regName" class="form-label">姓名</label>
                            <input type="text" class="form-control" id="regName" name="name" required value="{{ old('name') }}" placeholder="範例：王大明">
                        </div>
                        <div class="mb-3">
                            <label for="regIdNumber" class="form-label">身份證字號</label>
                            <input type="text" class="form-control" id="regTwid" name="twid" required value="{{ old('twid') }}" placeholder="範例：H123456789">
                        </div>
                        
                        <div class="mb-3">
                            <label for="regPhone" class="form-label">行動電話</label>
                            <input type="text" class="form-control" id="regPhone" name="phone" required value="{{ old('phone') }}" placeholder="範例：09xxxxxxxx">
                        </div>
                        <div class="mb-3">
                            <label for="regEmail" class="form-label">電子信箱</label>
                            <input type="email" class="form-control" id="regEmail" name="email" required value="{{ old('email') }}" placeholder="範例：your_name@example.com">
                        </div>
                        <div class="mb-3">
                            <label for="regAddress" class="form-label">收件地址</label>
                           
                            <div class="city-selector-set input-group mb-3">
                                <select class="county form-control" required></select>
                                <select class="district form-control" required></select>
                                <input class="zipcode form-control" type="text" size="3" readonly placeholder="郵遞區號">
                                <input class="district_area form-control" type="text" size="10" name="district_area" required value="{{ old('district_area') }}" placeholder="XX里/村">
                            </div>
                            <input type="text" class="street form-control" name="street" required value="{{ old('street') }}" placeholder="範例：縣府路1號">
                            <input type="hidden" class="form-control" id="regAddress" name="address" required value="{{ old('address') }}">
                        </div>

                        <div class="mb-3">
                            <label class="form-label">記錄小卡</label>
                            <div class="input-group mb-3">
                                <button type="button" class="btn btn-outline-secondary btnBase64">選擇檔案</button>
                                <input type="text" class="form-control infoBase64" disabled="disabled" required placeholder="點擊選擇檔案(JPG、PNG、PDF檔案)">
                            </div>
                            <input type="file" class="fileBase64" accept="image/*,.pdf" style="display: none;">
                            
                            <input type="hidden" class="hFileTypeBase64" name="fileRecordCardFileType" value="{{ old('fileRecordCardFileType') }}" >
                            <input type="hidden" class="hFileNameBase64" name="fileRecordCardFileName" value="{{ old('fileRecordCardFileName') }}" >
                            <input type="hidden" class="hFileBase64" name="fileRecordCardBase64" value="{{ old('fileRecordCardBase64') }}">
                        </div>

                        <div class="mb-3">
                            <label class="form-label">身分證正面</label>
                            <div class="input-group mb-3">
                                <button type="button" class="btn btn-outline-secondary btnBase64">選擇檔案</button>
                                <input type="text" class="form-control infoBase64" disabled="disabled" required placeholder="點擊選擇檔案(JPG、PNG、PDF檔案)">
                            </div>
                            <input type="file" class="fileBase64" accept="image/*,.pdf" style="display: none;">
                            
                            <input type="hidden" class="hFileTypeBase64" name="fileTwidFrontFileType" value="{{ old('fileTwidFrontFileType') }}" >
                            <input type="hidden" class="hFileNameBase64" name="fileTwidFrontFileName" value="{{ old('fileTwidFrontFileName') }}" >
                            <input type="hidden" class="hFileBase64" name="fileTwidFrontBase64" value="{{ old('fileTwidFrontBase64') }}">
                            
                        </div>

                        <div class="mb-3">
                            <label class="form-label">身分證反面</label>
                            <div class="input-group mb-3">
                                <button type="button" class="btn btn-outline-secondary btnBase64">選擇檔案</button>
                                <input type="text" class="form-control infoBase64" disabled="disabled" required placeholder="點擊選擇檔案(JPG、PNG、PDF檔案)">
                            </div>
                            <input type="file" class="fileBase64" accept="image/*,.pdf" style="display: none;">
                            
                            <input type="hidden" class="hFileTypeBase64" name="fileTwidBackFileType" value="{{ old('fileTwidBackFileType') }}" >
                            <input type="hidden" class="hFileNameBase64" name="fileTwidBackFileName" value="{{ old('fileTwidBackFileName') }}" >
                            <input type="hidden" class="hFileBase64" name="fileTwidBackBase64" value="{{ old('fileTwidBackBase64') }}">
                        </div>
                                                
                        <div class="mb-3">
                            &nbsp;
                        </div>
                        
                        <button type="submit" class="btn btn-primary">提交審核</button>
                    </div>
                </div>

            </form>
            
            <p>&nbsp;</p>
        </div>
    </div>
    
</div>

@endsection

@section('script')
<script>
    
    $(document).ready(function(){
        $('#dataForm').submit(function(){
            $(this).find(':input[type=submit]').prop('disabled', true);
        });
        
        $('#regTwid').on('change', function(){
            var val = $(this).val();
            val = toHalfWidth(val);
            val = val.toUpperCase();
            if (verifyId(val)) {
                $(this).val(val);
            } else {
                alert('請輸入正確身份證字號');
                $(this).val('');
            }
            
        });

        $('#regEmail').on('change', function(){
            var val = $(this).val();
            val = toHalfWidth(val);
            $(this).val(val);
        });

        $('#regPhone').on('change', function(){
            const phoneRegex = /^09\d{8}$/;
            var phone = $(this).val();
            phone = toHalfWidth(phone);
            if (!phoneRegex.test(phone)) {
                alert('請輸入正確格式 09xxxxxxxx');
                $(this).val('');
            } else {
                $(this).val(phone);
            }
        });

        var tcs = new TwCitySelector({
            el: '.city-selector-set',
            elCounty: '.county', // 在 el 裡查找 element
            elDistrict: '.district', // 在 el 裡查找 element
            elZipcode: '.zipcode' // 在 el 裡查找 element
        });

        var addr = $('#regAddress').val();
        if (addr) {
            setTimeout(() => {
                var addrs = addr.split(' ');
                if (addrs.length == 5) {
                    $('.zipcode').val(addrs[0]);
                    tcs.setValue(addrs[1], addrs[2]);
                    $('.district_area').val(addrs[3]);
                    $('.street').val(addrs[4]);
                }    
            }, 500);
        }

        $('.district_area').on('change', function(){
            var district_area = $('.district_area').val();
            district_area = toHalfWidth(district_area);
            district_area = district_area.split(" ").join("");
            if (!(district_area.substr(district_area.length - 1) == '里' 
                || district_area.substr(district_area.length - 1) == '村')) 
            {
                alert('請填寫完整「XX里/村」');
                $('.district_area').val('');
            }
        });

        $('.county,.district,.zipcode,.district_area,.street').on('change', function(){
            setTimeout(() => {
                var country = $('.county').val();
                var district = $('.district').val();
                var zip = $('.zipcode').val();
                var district_area = $('.district_area').val();
                var street = $('.street').val();

                district_area = toHalfWidth(district_area);
                district_area = district_area.split(" ").join("");
                street = toHalfWidth(street);
                street = street.split(" ").join("");
                
                $('.district_area').val(district_area);
                $('.street').val(street);
                $('#regAddress').val(`${zip} ${country} ${district} ${district_area} ${street}`);
            }, 1);
        });

        $('.fileBase64').each(function(idx, elem) {
            var pElem = $(elem).parent();
            var btn = $(pElem).find('.btnBase64')[0];
            var info = $(pElem).find('.infoBase64')[0];
            var hFile = $(pElem).find('.hFileBase64')[0];
            var hFileName = $(pElem).find('.hFileNameBase64')[0];
            var hFileType = $(pElem).find('.hFileTypeBase64')[0];
            
            var fn = $(hFileName).val();
            if (fn) {
                $(info).val(`已選擇檔案：${fn}`);
                
                var previewElem = null;
                if (fn.split('.').pop() == 'pdf') {
                    previewElem = $('<embed class="preview" type="application/pdf" width="300" height="150"></embed>');
                } else {
                    previewElem = $('<img class="preview" height="150" />');
                }
                $(previewElem).appendTo(pElem);
                $(previewElem).attr('src', $(hFileType).val() + ',' + $(hFile).val());
            }

            $(btn).click(function() {
                $(elem).click();
            });
            $(elem).on('change', function(){
                const file = this.files[0];
                if (file) {
                    if (file.size > (1024*1024*5)) {
                        alert('超過可上傳的檔案容量(5MB)，請重新選擇。');
                        return;
                    }
                    if (!(file.type === 'image/png' || 
                        file.type === 'image/jpeg' ||
                        file.type === 'application/pdf')) 
                    {
                        alert('請選擇正確的檔案格式上傳(.jpg/.jpeg/.png/.pdf)。');
                        return;
                    }
                    $(pElem).find('.preview').remove();
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const bodys = e.target.result.split(',');
                        $(hFileType).val(bodys[0]);
                        $(hFile).val(bodys[1]);
                        $(hFileName).val(file.name);
                        $(info).val(`已選擇檔案：${file.name}`);
                        
                        var previewElem = null;
                        if (file.name.split('.').pop() == 'pdf') {
                            previewElem = $('<embed class="preview" type="application/pdf" width="300" height="150"></embed>');
                        } else {
                            previewElem = $('<img class="preview" height="150" />');
                        }
                        $(previewElem).appendTo(pElem);
                        $(previewElem).attr('src', e.target.result);
                    };
                    reader.readAsDataURL(file);
                }
            });
        });
    });
</script>
@endsection
