<?php
/**
 * @var \Cake\Datasource\ResultSetInterface|\App\Model\Entity\Waitlist[] $items
 * @var array  $clinicians
 * @var string $q
 * @var string $status
 * @var int|string $cid
 * @var int    $perPage
 */
$this->assign('title', 'Waiting List');

$csrf     = $this->request->getAttribute('csrfToken');
$editBase = $this->Url->build(['action' => 'edit']);
$autoFillUrl = $this->Url->build(['action'=>'autoFill']);
?>
<style>
    .table.waitlist-table th,
    .table.waitlist-table td { vertical-align: middle; white-space: nowrap; }
    .table .col-order   { width: 64px;  text-align: right; }
    .table .col-id      { width: 72px; }
    .table .col-status  { width: 120px; }
    .table .col-created { width: 160px; }

    .cell-clip { max-width: 320px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    .table tbody tr:hover { background-color: rgba(0,0,0,.025); }

    .wl-badge{ display:inline-block; padding:.25rem .55rem; border-radius:12px; font-size:.75rem; line-height:1.1; }
    .wl-waiting   { background:#fff3cd; color:#856404; }
    .wl-scheduled { background:#d4edda; color:#155724; }
    .wl-cancelled { background:#f8d7da; color:#721c24; }

    .actions-cell{ width:300px; }
    .actions-wrap{ display:flex; justify-content:flex-end; gap:8px; flex-wrap:wrap; }

    .btn-action{ min-width:140px; }
    .table .actions-cell .btn,
    .table .actions-cell .btn *{ opacity:1 !important; visibility:visible !important; }

    .table .actions-cell .btn.btn-outline-success{ color:#28a745 !important; border-color:#28a745; }
    .table .actions-cell .btn.btn-outline-danger { color:#dc3545 !important; border-color:#dc3545; }
    .table .actions-cell .btn.btn-outline-secondary{ color:#6c757d !important; border-color:#6c757d; }
    .table .actions-cell .btn.btn-outline-primary{ color:#007bff !important; border-color:#007bff; }

    .table .actions-cell .btn.disabled, .table .actions-cell .btn:disabled{ opacity:.65 !important; pointer-events:none; }
    .table .actions-cell .btn i{ margin-right:.25rem; }

    @media (max-width: 1200px){ .actions-cell{ width:280px; } .cell-clip{ max-width: 260px; } }
    @media (max-width: 992px) { .actions-cell{ width:100%; } .actions-wrap{ justify-content:flex-start; } .btn-action{ min-width:130px; } .cell-clip{ max-width: 220px; } }
    @media (max-width: 576px) { .btn-action{ min-width:100%; } .actions-wrap{ gap:6px; } .cell-clip{ max-width: 180px; } }

    .modal-wl .modal-content{ border:0; border-radius:12px; box-shadow:0 10px 30px rgba(0,0,0,.12); }
    .modal-wl .modal-header{ border:0; padding:16px 16px 0; }
    .modal-wl .modal-body{   padding:8px 16px 16px; }
    .modal-wl .modal-footer{ border:0; padding:0 16px 16px; }
    .wl-kv{ font-size:13px; color:#6b7280; }
    .wl-kv b{ color:#111827; }
</style>

<section class="section">
    <div class="section-body">
        <div class="row">
            <div class="col-12">
                <div class="card">

                    <div class="card-header" style="align-items:center;gap:12px;">
                        <h4 class="mb-0">Waiting List</h4>

                        <form class="form-inline ml-auto" method="get" action="">
                            <div class="input-group mr-2">
                                <input type="search" name="q" class="form-control" placeholder="Search name / email / phone" value="<?= h($q ?? '') ?>">
                                <div class="input-group-append"><button class="btn btn-outline-secondary" type="submit">Search</button></div>
                            </div>

                            <label>
                                <select name="status" class="form-control mr-2" onchange="this.form.submit()">
                                    <?php $opts=[''=>'All status','waiting'=>'Waiting','scheduled'=>'Scheduled','cancelled'=>'Cancelled']; ?>
                                    <?php foreach ($opts as $k=>$v): ?>
                                        <option value="<?= h($k) ?>" <?= ($status ?? '')===$k?'selected':'' ?>><?= h($v) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </label>

                            <label>
                                <select name="cid" class="form-control mr-2" onchange="this.form.submit()">
                                    <option value="">All clinicians</option>
                                    <?php foreach (($clinicians ?? []) as $id=>$name): ?>
                                        <option value="<?= (int)$id ?>" <?= (string)($cid ?? '')===(string)$id ? 'selected':'' ?>><?= h($name) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </label>

                            <label>
                                <select name="limit" class="form-control mr-2" onchange="this.form.submit()">
                                    <?php foreach ([10,20,50,100,200] as $n): ?>
                                        <option value="<?= $n ?>" <?= (int)($perPage ?? 20)===$n?'selected':'' ?>><?= $n ?> rows</option>
                                    <?php endforeach; ?>
                                </select>
                            </label>
                        </form>
                    </div>

                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped mb-0">
                                <thead>
                                <tr>
                                    <th><?= $this->Paginator->sort('Waitlist.position','Order') ?></th>
                                    <th><?= $this->Paginator->sort('Waitlist.id','ID') ?></th>
                                    <th><?= $this->Paginator->sort('Waitlist.participant_name','Participant') ?></th>
                                    <th><?= $this->Paginator->sort('Waitlist.contact','Contact') ?></th>
                                    <th><?= $this->Paginator->sort('Waitlist.clinician_id','Clinician') ?></th>
                                    <th><?= $this->Paginator->sort('Waitlist.desired_date','Desired') ?></th>
                                    <th><?= $this->Paginator->sort('Waitlist.notes','Notes') ?></th>
                                    <th><?= $this->Paginator->sort('Waitlist.status','Status') ?></th>
                                    <th><?= $this->Paginator->sort('Waitlist.created','Created') ?></th>
                                    <th class="text-right actions-cell">Actions</th>
                                </tr>
                                </thead>

                                <tbody>
                                <?php if (count($items)): ?>
                                    <?php foreach ($items as $it): ?>
                                        <?php
                                        $p = $it->participant ?? null;
                                        $displayName = trim((string)($it->participant_name ?? ''));
                                        if ($displayName === '' && $p) { $displayName = trim(($p->first_name ?? '').' '.($p->last_name ?? '')); }

                                        $contact = (string)($it->contact ?? '');
                                        if ($contact === '' && $p) {
                                            $email = (string)($p->email ?? ''); $phone = (string)($p->phone ?? '');
                                            $contact = trim($email . ($email && $phone ? ' ' : '') . $phone);
                                        }

                                        $c = $it->login ?? null;
                                        $clinName = $c ? (trim(($c->first_name ?? '').' '.($c->last_name ?? '')) ?: ($c->email ?? '')) : '—';
                                        $desired = $it->desired_date instanceof \Cake\I18n\FrozenDate ? $it->desired_date->i18nFormat('yyyy-MM-dd') : (!empty($it->desired_date)?h((string)$it->desired_date):'—');

                                        $notesFull  = (string)($it->notes ?? '');
                                        $notesShort = $notesFull !== '' ? mb_strimwidth($notesFull,0,60,'…','UTF-8') : '—';

                                        $st = strtolower((string)($it->status ?? 'waiting'));
                                        $badgeClass = 'wl-badge wl-'.(in_array($st,['waiting','scheduled','cancelled'])?$st:'waiting');
                                        ?>
                                        <tr data-id="<?= (int)$it->id ?>" class="js-row">
                                            <td><?= (int)($it->position ?? 0) ?></td>
                                            <td><?= (int)$it->id ?></td>
                                            <td><?= $displayName !== '' ? h($displayName) : '—' ?></td>
                                            <td><?= $contact !== '' ? h($contact) : '—' ?></td>
                                            <td><?= h($clinName) ?></td>
                                            <td><?= $desired ?></td>
                                            <td title="<?= h($notesFull) ?>"><?= $notesShort !== '' ? h($notesShort) : '—' ?></td>
                                            <td><span class="<?= $badgeClass ?>"><?= h(ucfirst($st)) ?></span></td>
                                            <td><?= $it->created ? $it->created->i18nFormat('yyyy-MM-dd HH:mm') : '' ?></td>

                                            <td class="text-right actions-cell">
                                                <div class="actions-wrap">
                                                    <button type="button" class="btn btn-sm btn-outline-primary btn-action js-wl-edit">
                                                        <i class="fas fa-edit"></i> Edit
                                                    </button>

                                                    <?php if (($it->status ?? 'waiting') === 'waiting'): ?>
                                                        <?= $this->Form->create(null, ['url'=>['action'=>'markScheduled', $it->id], 'class'=>'m-0']) ?>
                                                        <?= $this->Form->button('<i class="fas fa-check"></i> Mark scheduled',
                                                            ['escapeTitle'=>false,'class'=>'btn btn-sm btn-outline-success btn-action',
                                                                'data-confirm'=>'Mark this entry as scheduled?']) ?>
                                                        <?= $this->Form->end() ?>
                                                    <?php else: ?>
                                                        <button class="btn btn-sm btn-outline-secondary btn-action" disabled>Mark scheduled</button>
                                                    <?php endif; ?>

                                                    <?= $this->Form->create(null, ['url'=>['action'=>'delete', $it->id], 'class'=>'m-0']) ?>
                                                    <?= $this->Form->button('<i class="fas fa-trash-alt"></i> Delete',
                                                        ['escapeTitle'=>false,'class'=>'btn btn-sm btn-outline-danger btn-action',
                                                            'data-confirm'=>'Delete this waitlist entry? This cannot be undone.']) ?>
                                                    <?= $this->Form->end() ?>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr><td colspan="10" class="text-center text-muted">No data</td></tr>
                                <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div class="card-footer d-flex justify-content-between align-items-center">
                        <div class="text-muted small">
                            Page <?= $this->Paginator->counter('{{page}}') ?> of <?= $this->Paginator->counter('{{pages}}') ?>,
                            showing <?= $this->Paginator->counter('{{current}}') ?> record(s) out of <?= $this->Paginator->counter('{{count}}') ?> total
                        </div>
                        <div>
                            <?= $this->Paginator->prev('« Prev', ['class'=>'btn btn-light btn-sm'], null, ['class'=>'btn btn-light btn-sm disabled']) ?>
                            <?= $this->Paginator->numbers(['class'=>'pagination pagination-sm mb-0', 'currentTag'=>'span']) ?>
                            <?= $this->Paginator->next('Next »', ['class'=>'btn btn-light btn-sm'], null, ['class'=>'btn btn-light btn-sm disabled']) ?>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</section>

<div class="modal fade modal-wl" id="wlEditModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header pb-2">
                <h6 class="mb-0">Edit Waitlist</h6>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="outline:none;">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body pt-2">
                <input type="hidden" id="wlEditId" />
                <div class="wl-kv mb-2">
                    <div><b id="wlEditName">—</b></div>
                    <div class="small">Contact: <span id="wlEditContact">—</span></div>
                    <div class="small">Desired: <span id="wlEditDesired">—</span></div>
                </div>
                <div class="form-group">
                    <label for="wlEditNotes">Notes</label>
                    <textarea id="wlEditNotes" class="form-control" rows="4" placeholder="Add notes / reasons..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="wlBtnSave">Save</button>
            </div>
        </div>
    </div>
</div>

<script>
    (function(){
        'use strict';
        var EDIT_BASE = '<?= h($editBase) ?>';
        var CSRF      = '<?= h($csrf) ?>';

        function openEdit(id){
            fetch(EDIT_BASE + '/' + encodeURIComponent(id) + '.json', {credentials:'same-origin'})
                .then(function(r){
                    if(!r.ok) throw new Error('Load failed');
                    return r.json();
                })
                .then(function(j){
                    document.getElementById('wlEditId').value = j.id || '';
                    document.getElementById('wlEditName').textContent    = j.name || '—';
                    document.getElementById('wlEditContact').textContent = j.contact || '—';
                    document.getElementById('wlEditDesired').textContent = j.desired_date || '—';
                    document.getElementById('wlEditNotes').value = j.notes || '';
                    $('#wlEditModal').modal('show');
                    setTimeout(function(){ document.getElementById('wlEditNotes').focus(); }, 80);
                })
                .catch(function(err){
                    alert(err && err.message ? err.message : 'Load failed');
                });
        }

        document.addEventListener('click', function(e){
            var btn = e.target.closest('.js-wl-edit');
            if (btn) {
                var tr = btn.closest('tr[data-id]');
                if (tr) openEdit(tr.getAttribute('data-id'));
                return;
            }
        });

        var tbody = document.querySelector('table.table tbody');
        if (tbody) {
            tbody.addEventListener('click', function(e){
                if (e.target.closest('.actions-wrap, a, button, input, label')) return;
                var tr = e.target.closest('tr[data-id]');
                if (tr) openEdit(tr.getAttribute('data-id'));
            });
        }

        document.addEventListener('click', function(e){
            if (e.target && e.target.id === 'wlBtnSave') {
                var id    = document.getElementById('wlEditId').value;
                var notes = document.getElementById('wlEditNotes').value;

                fetch(EDIT_BASE + '/' + encodeURIComponent(id) + '.json', {
                    method: 'POST',
                    credentials: 'same-origin',
                    headers: {'Content-Type':'application/json','X-CSRF-Token': CSRF},
                    body: JSON.stringify({ notes: notes })
                })
                    .then(function(r){ return r.json().catch(function(){return {};}).then(function(j){return {ok:r.ok, body:j};}); })
                    .then(function(res){
                        if (!res.ok || res.body.ok === false) throw new Error((res.body && res.body.error) || 'Save failed');
                        window.location.reload();
                    })
                    .catch(function(err){
                        alert(err && err.message ? err.message : 'Save failed');
                    });
            }
        });
    })();
</script>
