<?php
/** @var \App\Model\Entity\Login $specializations */

$this->Html->css('https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/flatpickr.min.css', ['block' => 'css']);
$this->Html->css('https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css', ['block' => 'css']);
$role = strtolower((string)($this->Identity->get('role') ?? ''));

?>
<style>
    .pw-rules{list-style:none;margin:.5rem 0 0 0;padding-left:0}
    .pw-rules li{display:flex;align-items:center}
    .pw-rules li i{margin-right:.4rem}
    .pw-rules .pw-ok{color:#28a745;}
    .pw-rules .pw-bad{color: #df0026;}
</style>

<section class="section">
    <div class="container mt-5">
        <div class="row">
            <div class="col-12 col-sm-10 offset-sm-1 col-md-8 offset-md-2 col-lg-8 offset-lg-2 col-xl-8 offset-xl-2">
                <div class="card card-primary">
                    <div class="card-header"><h4>Add New Clinician</h4></div>
                    <div class="alert <?= $role === 'admin' ? 'alert-success' : 'alert-danger' ?> d-flex align-items-center mb-4" role="alert" style="gap:.5rem;">
                        <i class="fas <?= $role === 'admin' ? 'fa-user-shield' : 'fa-lock' ?>"></i>
                        <div>
                            Only administrators can create accounts.
                            <?php if ($role === 'admin'): ?>
                                You are signed in as <strong>admin</strong>.
                            <?php else: ?>
                                You are not authorized to use this page.
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="card-body">
                        <?= $this->Form->create(
                            null,
                            [
                                'url' => ['controller' => 'ClinicianRegister', 'action' => 'index'],
                                'class' => 'needs-validation',
                                'novalidate' => true
                            ]
                        ) ?>

                        <div class="row">
                            <div class="form-group col-6">
                                <?= $this->Form->label('first_name', 'First Name') ?>
                                <?= $this->Form->text('first_name', ['id'=>'first_name','class'=>'form-control','required'=>true,'autofocus'=>true]) ?>
                                <div class="invalid-feedback">Please enter your first name.</div>
                            </div>
                            <div class="form-group col-6">
                                <?= $this->Form->label('last_name', 'Last Name') ?>
                                <?= $this->Form->text('last_name', ['id'=>'last_name','class'=>'form-control']) ?>
                            </div>
                        </div>

                        <div class="row">
                            <div class="form-group col-6">
                                <?= $this->Form->label('email', 'Email') ?>
                                <?= $this->Form->email('email', ['id'=>'email','class'=>'form-control','required'=>true]) ?>
                                <div class="invalid-feedback">Please enter a valid email address.</div>
                            </div>
                            <div class="form-group col-6">
                                <?= $this->Form->label('mobile_phone', 'Mobile Phone Number') ?>
                                <?= $this->Form->text('mobile_phone', [
                                    'id'=>'mobile_phone','class'=>'form-control','required'=>true,
                                    'placeholder'=>'+61 xxx xxx xxx',
                                    'pattern'=>'^\+?\d[\d\s-]{7,15}$'
                                ]) ?>
                                <div class="invalid-feedback">Enter a valid phone number (e.g. +61 xxx xxx xxx).</div>
                            </div>
                        </div>

                        <div class="form-group">
                            <?= $this->Form->label('date_of_birth', 'Date of Birth') ?>
                            <?= $this->Form->text('date_of_birth', ['id'=>'date_of_birth','class'=>'form-control','required'=>true]) ?>
                            <div class="invalid-feedback">Please choose your date of birth.</div>
                        </div>

                        <div class="form-group">
                            <?= $this->Form->label('specializations._ids', 'Assign Specializations') ?>

                            <?= $this->Form->select('specializations._ids', $specializations, [
                                'id'               => 'specializations_ids',
                                'multiple'         => true,
                                'class'            => 'form-control select2',
                                'data-placeholder' => 'Select one or more specializations',
                                'value'            => $preSelectedIds ?? null,
                            ]) ?>


                            <small class="form-text text-muted">You can choose multiple specializations.</small>
                        </div>

                        <div class="row">
                            <div class="form-group col-6">
                                <?= $this->Form->label('password', 'Password', ['class'=>'d-block']) ?>
                                <?= $this->Form->password('password', [
                                    'id'=>'password','class'=>'form-control','required'=>true,
                                    'pattern'=>'^(?=.*[A-Z])(?=.*\d).{8,}$','aria-describedby'=>'pwHelp'
                                ]) ?>
                                <ul class="pw-rules" id="pwRules" style="margin:6px 0 0 0;padding-left:22px;">
                                    <li id="rule-length" class="pw-bad"><i class="far fa-dot-circle"></i> At least 8 characters</li>
                                    <li id="rule-upper"  class="pw-bad"><i class="far fa-dot-circle"></i> At least 1 uppercase letter</li>
                                    <li id="rule-number" class="pw-bad"><i class="far fa-dot-circle"></i> At least 1 number</li>
                                </ul>
                                <div id="pwFeedback" class="invalid-feedback">Password does not meet the requirements above.</div>
                            </div>
                            <div class="form-group col-6">
                                <?= $this->Form->label('password_confirm', 'Password Confirmation', ['class'=>'d-block']) ?>
                                <?= $this->Form->password('password_confirm', ['id'=>'password_confirm','class'=>'form-control','required'=>true]) ?>
                                <div id="pw2Feedback" class="invalid-feedback">Passwords do not match.</div>
                            </div>
                        </div>

                        <div class="row pw-toggle-row" style="margin-top:-6px;margin-bottom:16px;">
                            <div class="form-group col-12">
                                <div class="custom-control custom-checkbox">
                                    <input type="checkbox" class="custom-control-input" id="showPw">
                                    <label class="custom-control-label" for="showPw">
                                        <i class="far fa-eye" id="showPwIcon" style="margin-right:6px;"></i>
                                        <span id="showPwText">Show passwords</span>
                                    </label>
                                </div>
                            </div>
                        </div>



                        <div class="form-group">
                            <button type="submit" class="btn btn-primary btn-lg btn-block">Register</button>
                        </div>

                        <?= $this->Form->end() ?>

                    </div>

                    <div class="mb-4 text-muted text-center">
                        Already Registered?
                        <a href="<?= $this->Url->build(['controller'=>'Login','action'=>'index']) ?>">Login</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<?php $this->start('scriptBottom'); ?>
<script src="https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/flatpickr.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.full.min.js"></script>
<script>
    (function(){
        const dobEl = document.getElementById('date_of_birth');
        if (dobEl && typeof window.flatpickr === 'function') {
            window.flatpickr(dobEl, {
                dateFormat: 'Y-m-d',
                altInput: true,
                altFormat: 'd/m/Y',
                maxDate: 'today',
                allowInput: true
            });
        }

        const form = document.querySelector('form.needs-validation');
        const pwd  = document.getElementById('password');
        const pwd2 = document.getElementById('password_confirm');

        const rules = {
            len:    document.getElementById('rule-length'),
            upper:  document.getElementById('rule-upper'),
            number: document.getElementById('rule-number')
        };
        const pwFeedback  = document.getElementById('pwFeedback');
        const pw2Feedback = document.getElementById('pw2Feedback');

        function toggleRule(liEl, ok){
            if (!liEl) return;
            const icon = liEl.querySelector('i');
            liEl.classList.toggle('pw-ok',  ok);
            liEl.classList.toggle('pw-bad', !ok);
            if (icon){
                icon.classList.toggle('fa-check-circle', ok);
                icon.classList.toggle('fa-dot-circle',  !ok);
            }
        }

        function updatePwHints(){
            if (!pwd) return;
            const v = pwd.value || '';
            const okLen = v.length >= 8;
            const okUp  = /[A-Z]/.test(v);
            const okNum = /\d/.test(v);

            toggleRule(rules.len,    okLen);
            toggleRule(rules.upper,  okUp);
            toggleRule(rules.number, okNum);

            if (!(okLen && okUp && okNum)) {
                pwd.setCustomValidity('invalid');
                if (pwFeedback) pwFeedback.textContent =
                    'Note that it must be more than 8 characters, and it must include at least one capital letter and at least one number.';
            } else {
                pwd.setCustomValidity('');
                if (pwFeedback) pwFeedback.textContent = 'Password looks good.';
            }
        }

        function checkMatch(){
            if (!pwd || !pwd2) return;
            if (!pwd2.value) { pwd2.setCustomValidity(''); return; }
            const mis = pwd.value !== pwd2.value;
            pwd2.setCustomValidity(mis ? 'mismatch' : '');
            if (pw2Feedback) pw2Feedback.textContent = mis ? 'Passwords do not match.' : 'Passwords match.';
        }

        if (pwd)  pwd.addEventListener('input', ()=>{ updatePwHints(); checkMatch(); });
        if (pwd2) pwd2.addEventListener('input', checkMatch);
        updatePwHints();

        const showPw   = document.getElementById('showPw');
        const showIcon = document.getElementById('showPwIcon');
        const showText = document.getElementById('showPwText');
        if (showPw) {
            showPw.addEventListener('change', function(){
                const show = this.checked;
                [pwd, pwd2].forEach(el => { if (el) el.type = show ? 'text' : 'password'; });
                if (showIcon){
                    showIcon.classList.toggle('fa-eye', !show);
                    showIcon.classList.toggle('fa-eye-slash', show);
                }
                if (showText) showText.textContent = show ? 'Show passwords': 'Show passwords';
            });
        }

        if (form) {
            form.addEventListener('submit', function(e){
                updatePwHints(); checkMatch();
                if (!form.checkValidity()){
                    e.preventDefault();
                    e.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        }
    })();

    if (window.jQuery) {
        jQuery(function($){
            const $sel = $('#specializations_ids');
            if ($sel.length) {
                $sel.select2({
                    width: '100%',
                    placeholder: $sel.data('placeholder') || '',
                    allowClear: true,
                    closeOnSelect: false
                });
            }
        });
    }
</script>


<?php $this->end(); ?>
