<?php
/**
 * @var \App\Model\Entity\Participant $participant
 * @var array{total:int,last:?object,next:?object,balance:?float} $stats
 * @var \Cake\Datasource\ResultSetInterface|\Cake\Collection\CollectionInterface $events
 * @var array<int,array{name:string,size:int,mtime:int}> $files
 */
$this->assign('title', 'Participant Overview');

$fn = function($ts){
    return $ts ? (new \Cake\I18n\FrozenTime($ts))->i18nFormat('dd-MMM-yyyy hh:mm a') : '—';
};

$fmtAddr = function($a){
    if (!$a) return '—';
    $line1 = trim((string)($a->address_line1 ?? ''));
    $line2 = trim((string)($a->address_line2 ?? ''));
    $city  = trim((string)($a->city ?? ''));
    $reg   = trim((string)($a->region ?? ''));
    $pc    = trim((string)($a->postcode ?? ''));
    $country = trim((string)($a->country ?? ''));

    $parts1 = array_filter([$line1, $line2], fn($x)=>$x!=='');
    $parts2 = array_filter([$city, $reg, $pc], fn($x)=>$x!=='');

    $rows = [];
    if ($parts1) $rows[] = implode(', ', array_map('h', $parts1));
    if ($parts2) $rows[] = implode(' ', array_map('h', $parts2));
    if ($country!=='') $rows[] = h($country);

    return $rows ? implode('<br>', $rows) : '—';
};

$dateOnly = function($v){
    return $v ? (new \Cake\I18n\FrozenTime($v))->i18nFormat('dd-MMM-yyyy') : '—';
};

$genderLabel = function($g){
    $map = [
        'male'      => 'Male',
        'female'    => 'Female',
        'nonbinary' => 'Non-binary',
        'intersex'  => 'Intersex',
        'other'     => 'Other',
        'na'        => 'Prefer not to say',
        ''          => 'Prefer not to say',
        null        => 'Prefer not to say',
    ];
    return $map[$g] ?? ucfirst((string)$g);
};

$addrList  = $participant->participant_addresses ?? [];
$addrCount = is_countable($addrList) ? count($addrList) : 0;
$firstAddr = $addrCount ? $addrList[0] : null;
?>
<section class="section">
    <div class="section-body">
        <div class="row">
            <div class="col-12 col-lg-3 mb-3">
                <?= $this->element('participants/sidebar', [
                    'participant' => $participant,
                    'active'      => 'overview',
                ]) ?>
            </div>

            <div class="col-12 col-lg-9">
                <?= $this->Flash->render() ?>

                <div class="card mb-4">
                    <div class="card-body d-flex align-items-center">
                        <div class="avatar-circle mr-3">
                            <span><?= h(strtoupper(substr($participant->first_name ?? 'U', 0, 1))) ?></span>
                        </div>
                        <div>
                            <div class="h5 mb-1">
                                <?= h(trim(($participant->first_name ?? '').' '.($participant->last_name ?? ''))) ?: 'Unnamed' ?>
                                <?php if (!empty($participant->preferred_name)): ?>
                                    <small class="text-muted">(<?= h($participant->preferred_name) ?>)</small>
                                <?php endif; ?>
                            </div>
                            <div class="text-muted">
                                <?= h($participant->email ?? '—') ?>
                                <?php if (!empty($participant->phone)): ?> · <?= h($participant->phone) ?><?php endif; ?>
                            </div>
                        </div>
                        <div class="ml-auto">
                            <?= $this->Html->link('Edit', ['action'=>'edit',$participant->id], ['class'=>'btn btn-primary btn-sm']) ?>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-12 col-xl-6">
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h4 class="mb-0">General</h4>
                                <?= $this->Html->link('Edit', ['action'=>'edit', $participant->id, '#'=>'card-personal'], ['class'=>'btn btn-link btn-sm']) ?>
                            </div>
                            <div class="card-body">
                                <div class="row small">
                                    <div class="col-5 text-muted">Legal Name</div>
                                    <div class="col-7">
                                        <?= h(trim(($participant->first_name ?? '').' '.($participant->middle_name ?? '').' '.($participant->last_name ?? ''))) ?: '—' ?>
                                        <?php if (!empty($participant->preferred_name)): ?>
                                            <span class="badge badge-light ml-2">Current</span>
                                        <?php endif; ?>
                                    </div>

                                    <div class="col-5 text-muted mt-2">Date of Birth</div>
                                    <div class="col-7 mt-2"><?= $dateOnly($participant->dob ?? null) ?></div>

                                    <div class="col-5 text-muted mt-2">Gender</div>
                                    <div class="col-7 mt-2"><?= $genderLabel($participant->gender ?? null) ?></div>

                                    <div class="col-5 text-muted mt-2">Review Date</div>
                                    <div class="col-7 mt-2"><?= $dateOnly($participant->review_date ?? null) ?></div>

                                    <div class="col-5 text-muted mt-2">Practice Locations</div>
                                    <div class="col-7 mt-2">
                                        <?php if ($addrCount): ?>
                                            <span>
                                                <?= h(trim(($firstAddr->address_line1 ?? ''))) ?>
                                                <?php if (!empty($firstAddr->city)): ?>
                                                    , <?= h($firstAddr->city) ?>
                                                <?php endif; ?>
                                            </span>
                                            <?php if ($addrCount > 1): ?>
                                                <span class="text-muted small">(+<?= $addrCount-1 ?> more)</span>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            —
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-12 col-xl-6">
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h4 class="mb-0">Appointments Overview</h4>
                                <?= $this->Html->link('Edit', ['controller'=>'Calendar','action'=>'index'], ['class'=>'btn btn-link btn-sm']) ?>
                            </div>
                            <div class="card-body">
                                <div class="row text-center">
                                    <div class="col-6 col-md-3 mb-3">
                                        <div class="dash-number"><?= (int)$stats['total'] ?></div>
                                        <div class="text-muted small">Total</div>
                                    </div>
                                    <div class="col-6 col-md-3 mb-3">
                                        <div class="dash-number"><?= $stats['last'] ? $stats['last']->start?->i18nFormat('dd-MMM') : '—' ?></div>
                                        <div class="text-muted small">Last</div>
                                        <div class="small"><?= $stats['last'] ? $stats['last']->start?->i18nFormat('hh:mm a') : '' ?></div>
                                    </div>
                                    <div class="col-6 col-md-3 mb-3">
                                        <div class="dash-number"><?= $stats['next'] ? $stats['next']->start?->i18nFormat('dd-MMM') : '—' ?></div>
                                        <div class="text-muted small">Next</div>
                                        <div class="small"><?= $stats['next'] ? $stats['next']->start?->i18nFormat('hh:mm a') : '' ?></div>
                                    </div>
                                    <div class="col-6 col-md-3 mb-3">
                                        <div class="dash-number"><?= $stats['balance'] === null ? '—' : ('AU$'.number_format((float)$stats['balance'],2)) ?></div>
                                        <div class="text-muted small">Balance</div>
                                    </div>
                                </div>

                                <?php if ($stats['next']): ?>
                                    <div class="mt-2">
                                        <?= $this->Html->link(
                                            'Open calendar',
                                            ['controller'=>'Calendar','action'=>'index'],
                                            ['class'=>'btn btn-sm btn-outline-primary']
                                        ) ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-12 col-xl-6">
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h4 class="mb-0">Practitioner Access & Privacy</h4>
                                <?= $this->Html->link('Edit', ['action'=>'edit',$participant->id,'#'=>'card-clinicians'], ['class'=>'btn btn-link btn-sm']) ?>
                            </div>
                            <div class="card-body">
                                <?php if (!empty($participant->login)): ?>
                                    <ul class="list-unstyled mb-0">
                                        <?php foreach ($participant->login as $u):
                                            $name = trim(($u->first_name ?? '').' '.($u->last_name ?? '')) ?: (string)$u->email; ?>
                                            <li class="d-flex align-items-center py-1">
                                                <span class="mr-2 badge badge-light"><?= h($name) ?></span>
                                                <span class="text-muted small">Status / Access: Current</span>
                                            </li>
                                        <?php endforeach; ?>
                                    </ul>
                                <?php else: ?>
                                    <div class="text-muted">None assigned.</div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <div class="col-12 col-xl-6">
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h4 class="mb-0">Communication & Reminders</h4>
                                <?= $this->Html->link('Edit', ['controller'=>'Calendar','action'=>'index'], ['class'=>'btn btn-link btn-sm']) ?>
                            </div>
                            <div class="card-body small">
                                <div class="text-muted">Communication Preferences</div>
                                <div>Email: <strong><?= h($participant->email ?? '—') ?></strong></div>
                                <div>SMS: <strong><?= !empty($participant->phone) ? 'Enabled' : '—' ?></strong></div>
                                <hr>
                                <div class="text-muted">Reminders</div>
                                <div>Settings: <strong>Default</strong></div>
                                <div class="mt-2">
                                    <?= $this->Html->link('Go to calendar reminders', ['controller'=>'Calendar','action'=>'index'], ['class'=>'btn btn-link btn-sm pl-0']) ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card mb-4" id="contactCard">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h4 class="mb-0">Contact</h4>
                        <div>
                            <button type="button" class="btn btn-soft btn-sm" id="btnToggleContacts" aria-expanded="false">Show all</button>
                            <?= $this->Html->link('Edit', ['action'=>'edit',$participant->id,'#'=>'card-contact'], ['class'=>'btn btn-link btn-sm']) ?>
                        </div>
                    </div>

                    <div class="card-body">
                        <?php
                        $contacts = $participant->contacts ?? [];
                        if (!$contacts && ($participant->phone || $participant->email)) {
                            $contacts = [];
                            if ($participant->phone) $contacts[] = (object)[
                                'type'=>'phone','label'=>'self|mobile','value'=>$participant->phone,'is_primary'=>0,'is_emergency'=>0
                            ];
                            if ($participant->email) $contacts[] = (object)[
                                'type'=>'email','label'=>'self|personal','value'=>$participant->email,'is_primary'=>1,'is_emergency'=>0
                            ];
                        }

                        $primary = null;
                        foreach ($contacts as $c) { if ((int)($c->is_primary ?? 0) === 1) { $primary = $c; break; } }

                        // —— 标签拆分
                        $fmtLabel = function($label) {
                            $label = (string)($label ?? '');
                            [$rel, $tag] = array_pad(explode('|', $label, 2), 2, '');
                            $rel = $rel ?: 'self';
                            $relMap = [
                                'self'=>'Self','parent'=>'Parent','spouse'=>'Spouse/Partner','sibling'=>'Sibling',
                                'child'=>'Child','relative'=>'Relative','friend'=>'Friend','guardian'=>'Guardian',
                                'caregiver'=>'Caregiver','other'=>'Other'
                            ];
                            $tagMap = ['mobile'=>'Mobile','home'=>'Home','work'=>'Work','personal'=>'Personal','other'=>'Other'];
                            $relTxt = $relMap[$rel] ?? ucfirst($rel);
                            $tagTxt = $tagMap[$tag] ?? ($tag !== '' ? ucfirst($tag) : '');
                            return trim($relTxt . ($tagTxt ? ' / ' . $tagTxt : ''));
                        };
                        ?>

                        <div id="contactSummary" class="mb-2">
                            <?php if ($primary): ?>
                                <div class="small text-muted mb-1">Primary</div>
                                <div class="h6 mb-0">
                                    <?= h(strtoupper($primary->type)) ?> · <?= h($primary->value) ?>
                                    <span class="badge badge-primary ml-2">PRIMARY</span>
                                    <?php if (!empty($primary->is_emergency)): ?>
                                        <span class="badge badge-danger ml-1">EMERGENCY</span>
                                    <?php endif; ?>
                                </div>
                                <?php if (!empty($primary->label)): ?>
                                    <div class="text-muted small"><?= h($fmtLabel($primary->label)) ?></div>
                                <?php endif; ?>
                            <?php else: ?>
                                <div class="text-muted">No contact info</div>
                            <?php endif; ?>
                        </div>

                        <div id="contactFull" class="d-none">
                            <?php if ($contacts): ?>
                                <div class="table-responsive">
                                    <table class="table table-sm mb-0 align-middle">
                                        <thead>
                                        <tr>
                                            <th style="width:90px">Type</th>
                                            <th style="width:240px">Label</th>
                                            <th>Value</th>
                                            <th style="width:160px">Flags</th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        <?php foreach ($contacts as $c): ?>
                                            <tr>
                                                <td class="text-uppercase"><?= h($c->type ?? '') ?></td>
                                                <td><?= h($fmtLabel($c->label ?? '')) ?></td>
                                                <td class="text-monospace"><?= h($c->value ?? '') ?></td>
                                                <td>
                                                    <?php if (!empty($c->is_primary)): ?>
                                                        <span class="badge badge-primary">PRIMARY</span>
                                                    <?php endif; ?>
                                                    <?php if (!empty($c->is_emergency)): ?>
                                                        <span class="badge badge-danger ml-1">EMERGENCY</span>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php else: ?>
                                <div class="text-muted">No contact info</div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <div class="card mb-4" id="addresses">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h4 class="mb-0">Addresses</h4>
                        <?= $this->Html->link('Edit', ['action'=>'edit', $participant->id, '#'=>'card-addresses'], ['class'=>'btn btn-link btn-sm']) ?>
                    </div>
                    <div class="card-body">
                        <?php if ($addrCount): ?>
                            <div class="table-responsive">
                                <table class="table table-sm mb-0">
                                    <thead>
                                    <tr>
                                        <th style="width:140px;">Type</th>
                                        <th>Address</th>
                                        <th style="width:180px;">Time Zone</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    <?php foreach ($addrList as $a): ?>
                                        <tr>
                                            <td>
                                                <span class="badge badge-light text-uppercase">
                                                    <?= h($a->address_type ?? 'other') ?>
                                                </span>
                                            </td>
                                            <td><?= $this->Html->tag('div', $fmtAddr($a), ['escape' => false]) ?></td>
                                            <td><?= h($a->time_zone ?? '') ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="text-muted">No addresses.</div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="card mb-4" id="notes">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h4 class="mb-0">Notes</h4>
                        <?= $this->Html->link('Edit', ['action'=>'edit', $participant->id, '#' => 'card-notes'], ['class'=>'btn btn-link btn-sm']) ?>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($participant->note)): ?>
                            <div><?= nl2br(h($participant->note)) ?></div>
                        <?php else: ?>
                            <div class="text-muted">No notes.</div>
                        <?php endif; ?>
                    </div>
                </div>


                <div class="card mb-4" id="files">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h4 class="mb-0">Files</h4>
                        <small class="text-muted">Max 20MB · pdf/jpg/png/doc/xls/txt/rtf</small>
                    </div>
                    <div class="card-body">
                        <?= $this->Form->create(null, [
                            'type' => 'file',
                            'url'  => ['action' => 'uploadFile', $participant->id],
                            'templates' => ['inputContainer' => '{{content}}']
                        ]) ?>
                        <div class="form-row align-items-center">
                            <div class="col">
                                <input type="file" name="files[]" class="form-control" multiple>
                            </div>
                            <div class="col-auto">
                                <button class="btn btn-primary">Upload</button>
                            </div>
                        </div>
                        <?= $this->Form->end() ?>

                        <hr>

                        <?php if (!empty($files)): ?>
                            <div class="table-responsive">
                                <table class="table table-sm mb-0">
                                    <thead><tr><th>Name</th><th>Size</th><th>Uploaded</th><th class="text-right">Actions</th></tr></thead>
                                    <tbody>
                                    <?php foreach ($files as $f): ?>
                                        <tr>
                                            <td><?= h($f['name']) ?></td>
                                            <td><?= number_format($f['size']/1024,1) ?> KB</td>
                                            <td><?= (new \Cake\I18n\FrozenTime($f['mtime']))->i18nFormat('yyyy-MM-dd HH:mm') ?></td>
                                            <td class="text-right">
                                                <?= $this->Html->link('Download',
                                                    ['action'=>'downloadFile',$participant->id,$f['name']],
                                                    ['class'=>'btn btn-outline-secondary btn-sm']) ?>
                                                <?= $this->Form->postLink('Delete',
                                                    ['action'=>'deleteFile',$participant->id],
                                                    ['confirm'=>'Delete this file?','class'=>'btn btn-outline-danger btn-sm','data'=>['name'=>$f['name']]]) ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="text-muted">No files yet.</div>
                        <?php endif; ?>
                    </div>
                </div>

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

<style>
    .avatar-circle{width:56px;height:56px;border-radius:50%;background:#f3f4f6;display:flex;align-items:center;justify-content:center;}
    .avatar-circle span{font-weight:600;font-size:18px;color:#111827;}
    .dash-number{font-size:20px;font-weight:700;}
    .btn-soft{background:#eef2ff;border:0;color:#4f46e5;}
    .btn-soft:hover{background:#e0e7ff;color:#4338ca;}
    .badge.text-uppercase{letter-spacing:.02em;}
    #addresses .table td, #addresses .table th{vertical-align:top;}
</style>

<?php $this->start('scriptBottom'); ?>
<script>
    (function(){
        var btn  = document.getElementById('btnToggleContacts');
        var sum  = document.getElementById('contactSummary');
        var full = document.getElementById('contactFull');
        if (!btn || !sum || !full) return;

        function setExpanded(expanded){
            btn.setAttribute('aria-expanded', expanded ? 'true' : 'false');
            btn.textContent = expanded ? 'Hide all' : 'Show all';
            full.classList.toggle('d-none', !expanded);
            sum.classList.toggle('d-none',  expanded);
        }

        setExpanded(btn.getAttribute('aria-expanded') === 'true');

        btn.addEventListener('click', function(){
            setExpanded(!(btn.getAttribute('aria-expanded') === 'true'));
        });
    })();
</script>

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