<?php
if (!function_exists('h')) {
    function h($s)
    {
        return htmlspecialchars((string)$s, ENT_QUOTES);
    }
}

$baseDir = realpath(__DIR__ . '/../../public');
$photoDir = $baseDir . '/media/animals/' . (int)$animal['id'];

function fileToDataUri(string $path): ?string
{
    if (!is_file($path)) {
        return null;
    }
    $data = file_get_contents($path);
    if ($data === false) {
        return null;
    }
    $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
    $mime = match($ext) {
        'jpg','jpeg' => 'image/jpeg',
        'png' => 'image/png',
        'webp' => 'image/webp',
        'gif' => 'image/gif',
        default => 'application/octet-stream'
    };
    return "data:$mime;base64," . base64_encode($data);
}

function labelStatus(string $s): string
{
    return match ($s) {
        'refuge' => t('status.refuge'),
        'fa' => t('status.fa'),
        'fa_permanente' => t('status.fa_permanente'),
        'quarantaine' => t('status.quarantaine'),
        'soin' => t('status.soin'),
        'isolation' => t('status.isolation'),
        'hospitalise','hospitalisé' => t('status.hospitalise'),
        'reserve','réservé' => t('status.reserve'),
        'adopte','adopté' => t('status.adopte'),
        'decede','décédé' => t('status.decede'),
        'enfui' => t('status.enfui'),
        default => $s,
    };
}

function fivFelvText(array $a): string
{
    // adapte selon tes colonnes réelles (chez toi ça marche déjà côté liste)
    $fiv = (string)($a['fiv'] ?? '');
    $felv = (string)($a['felv'] ?? '');
    if ($fiv === '' && $felv === '') {
        return t('animals.test_unknown');
    }
    if ($fiv === '0' && $felv === '0') {
        return t('animals.test_negative');
    }
    if ($fiv === '1' && $felv === '1') {
        return 'FIV/FELV+';
    }
    if ($fiv === '1') {
        return 'FIV+';
    }
    if ($felv === '1') {
        return 'FELV+';
    }
    // fallback : si tu stockes déjà du texte
    return trim($fiv . ' ' . $felv);
}

function kindClass(string $k): string
{
    $k = strtolower(trim($k));
    return match($k) {
        'consult' => 'k-consult',
        'contrôle','controle' => 'k-control',
        'hospi','hospitalisation' => 'k-hospi',
        'chirurgie' => 'k-surgery',
        'analyse','analyses' => 'k-lab',
        'vaccin' => 'k-vaccine',
        default => 'k-default'
    };
}


$mainPhotoUri = null;
if (!empty($primary_photo)) {
    $mainPhotoUri = fileToDataUri($photoDir . '/' . $primary_photo);
}
?>
<!doctype html>
<html lang="<?= h(I18n::locale()) ?>">

<head>
    <meta charset="utf-8">
    <title><?= h(t('pdf.medical_record', ['name' => $animal['name'] ?? ''])) ?></title>
    <style>
        @page {
            size: A4 portrait;
            margin: 14mm 12mm 18mm;
        }

        body {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 11.5px;
            color: #111;
            margin: 0;
        }

        h1 {
            font-size: 18px;
            margin: 0 0 6px;
        }

        h2 {
            font-size: 13px;
            margin: 18px 0 8px;
            border-bottom: 1px solid #ddd;
            padding-bottom: 4px;
        }

        .muted {
            color: #666;
        }

        .small {
            font-size: 10.5px;
        }

        .box {
            border: 1px solid #ddd;
            padding: 10px;
            border-radius: 6px;
        }

        .row {
            width: 100%;
        }

        .left {
            width: 34%;
            vertical-align: top;
        }

        .right {
            width: 66%;
            vertical-align: top;
        }

        table.grid {
            width: 100%;
            border-collapse: collapse;
        }

        .grid td,
        .grid th {
            border: 1px solid #ddd;
            padding: 6px;
            vertical-align: top;
        }

        .grid th {
            background: #f3f3f3;
            text-align: left;
        }

        .badge {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 10px;
            border: 1px solid #bbb;
            font-size: 10.5px;
        }

        .tag {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 4px;
            background: #f3f3f3;
            border: 1px solid #ddd;
        }

        .photo {
            width: 100%;
            height: 220px;
            object-fit: cover;
            border: 1px solid #ddd;
        }

        .sep {
            height: 10px;
        }

        .k {
            color: #444;
            font-weight: bold;
        }

        .note-kind {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 10px;
            border: 1px solid #ddd;
            font-size: 10px;
        }

        .badge {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 10px;
            font-size: 10px;
            border: 1px solid #ccc;
        }

        .k-consult {
            background: #e8f0ff;
            border-color: #9db8ff;
        }

        .k-control {
            background: #e8fff1;
            border-color: #9dffc1;
        }

        .k-hospi {
            background: #ffecec;
            border-color: #ff9d9d;
        }

        .k-surgery {
            background: #fff4e5;
            border-color: #ffd29d;
        }

        .k-lab {
            background: #f2e8ff;
            border-color: #c89dff;
        }

        .k-vaccine {
            background: #e6fbff;
            border-color: #9de7ff;
        }

        .k-default {
            background: #f3f3f3;
            border-color: #ddd;
        }

        .print-toolbar {
            position: sticky;
            top: 0;
            z-index: 10;
            display: flex;
            justify-content: flex-end;
            gap: 8px;
            margin: 0 0 16px;
            padding: 10px;
            background: #fff;
            border-bottom: 1px solid #ddd;
        }

        .print-toolbar button,
        .print-toolbar a {
            border: 1px solid #1d273b;
            border-radius: 6px;
            padding: 8px 13px;
            background: #fff;
            color: #1d273b;
            font: 600 14px Arial, sans-serif;
            text-decoration: none;
            cursor: pointer;
        }

        .print-toolbar button {
            background: #1d273b;
            color: #fff;
        }

        .document-certification {
            margin: 0 0 12px;
            padding: 7px 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background: #f7f7f7;
            color: #626976;
            font-size: 9px;
        }

        @media print {
            .print-toolbar {
                display: none !important;
            }

            h2 {
                break-after: avoid;
            }

            table.grid tr {
                break-inside: avoid;
            }
        }

    </style>
</head>

<body>

    <div class="print-toolbar"><a href="/animal?id=<?= (int)$animal['id'] ?>">←
            <?= h(t('pdf.back_record')) ?></a><button type="button" onclick="window.print()">🖨
            <?= h(t('pdf.print')) ?></button></div>
    <div class="document-certification"><?= h($footerText ?? '') ?></div>

    <h1><?= h(t('pdf.medical_record', ['name' => $animal['name'] ?? ''])) ?></h1>
    <div class="muted small">
        <?= h(t('pdf.generated_on', ['date' => date('d/m/Y H:i')])) ?> • <?= h(t('pdf.internal_code')) ?> :
        <?= h($animal['internal_code'] ?? '') ?>
    </div>

    <?php
$fivPos = ((int)($animal['fiv'] ?? 0) === 1);
$felvPos = ((int)($animal['felv'] ?? 0) === 1);
?>

    <?php if ($fivPos || $felvPos): ?>
    <div style="
background:#b91c1c;
color:white;
padding:12px;
margin-bottom:15px;
border-radius:6px;
font-weight:bold;
font-size:14px;
">
        ⚠️ <?= h(t('pdf.health_alert')) ?> :
        <?= $fivPos ? 'FIV+ ' : '' ?>
        <?= $felvPos ? 'FeLV+' : '' ?>
    </div>
    <?php endif; ?>

    <table class="row" cellspacing="0" cellpadding="0">
        <?php if (!empty($death)): ?>
        <caption
            style="caption-side:top;text-align:left;border:2px solid #222;padding:10px;margin:10px 0 15px;border-radius:6px;">
            <strong><?= h(t('pdf.death_recorded', ['date' => (($deathDate = DateTimeImmutable::createFromFormat('Y-m-d', (string)$death['deceased_date'])) ? $deathDate->format('d/m/Y') : t('pdf.unknown_date'))])) ?></strong><br>
            <?= h(t('animal.cause')) ?> :
            <?= h(DeathController::causeLabel((string)$death['cause_code'])) ?><?= !empty($death['euthanized']) ? ' · ' . h(t('animal.euthanasia')) : '' ?><br>
            <span
                class="small muted"><?= h(!empty($death['occurred_in_care']) ? t('pdf.death_in_care') : t('pdf.death_outside_care')) ?><?= $death['crematorium_name'] ? ' · ' . h(t('pdf.crematorium')) . ' : ' . h($death['crematorium_name']) : '' ?></span>
        </caption>
        <?php endif; ?>
        <tr>
            <td class="left">
                <div class="box">
                    <?php if ($mainPhotoUri): ?>
                    <img class="photo" src="<?= h($mainPhotoUri) ?>" alt="">
                    <div class="sep"></div>
                    <?php else: ?>
                    <div class="muted"><?= h(t('pdf.no_main_photo')) ?></div>
                    <div class="sep"></div>
                    <?php endif; ?>

                    <div><span class="k"><?= h(t('animal.status')) ?> :</span> <span
                            class="badge"><?= h(labelStatus((string)($animal['status'] ?? ''))) ?></span></div>
                    <div><span class="k"><?= h(t('animal.species')) ?> :</span> <?= h(match (strtolower((string)($animal['species'] ?? ''))) {
                        'cat', 'chat' => t('species.cat'), 'dog', 'chien' => t('species.dog'), 'nac' => t('species.nac'), default => (string)($animal['species'] ?? '')
                    }) ?></div>
                    <div><span class="k"><?= h(t('animal.sex')) ?> :</span> <?= h($animal['sex'] ?? '') ?></div>
                    <div><span class="k"><?= h(t('animal.birth')) ?> :</span> <?= h($animal['birth_date'] ?? '') ?>
                    </div>
                    <div><span class="k"><?= h(t('animal.form.identification')) ?> :</span> <?= h(match((string)($animal['identification_type'] ?? 'unknown')) {
                        'microchip' => t('animal.microchip'),'tattoo' => t('animal.tattoo'),default => t('common.not_provided')
                    }) ?><?= !empty($animal['chip_id']) ? ' · ' . h($animal['chip_id']) : '' ?></div>
                    <div><span class="k">FIV/FELV :</span> <?= h(fivFelvText($animal)) ?></div>

                    <?php if (!empty($animal['intake_date']) || !empty($animal['quarantine_until'])): ?>
                    <div class="sep"></div>
                    <div><span class="k"><?= h(t('pdf.entry')) ?> :</span> <?= h($animal['intake_date'] ?? '') ?></div>
                    <div><span class="k"><?= h(t('animal.form.quarantine_exit')) ?> :</span>
                        <?= h($animal['quarantine_until'] ?? '') ?></div>
                    <?php endif; ?>
                </div>
            </td>

            <td class="right" style="padding-left:12px;">
                <div class="box">
                    <div class="k"><?= h(t('pdf.summary')) ?></div>
                    <div class="sep"></div>

                    <div>
                        <span class="tag"><?= h(t('pdf.last_medical')) ?></span>
                        <?php if (empty($last_med)): ?>
                        <span class="muted">—</span>
                        <?php else: ?>
                        <span><?= h(substr((string)$last_med['noted_at'], 0, 16)) ?></span>
                        <?php if (!empty($last_med['kind'])): ?> • <span
                            class="note-kind"><?= h($last_med['kind']) ?></span><?php endif; ?>
                        <?php if (!empty($last_med['reason'])): ?><div class="small"><span
                                class="k"><?= h(t('pdf.reason')) ?> :</span> <?= h($last_med['reason']) ?></div>
                        <?php endif; ?>
                        <?php if (!empty($last_med['weight_kg'])): ?><div class="small"><span
                                class="k"><?= h(t('pdf.weight')) ?> :</span> <?= h($last_med['weight_kg']) ?> kg</div>
                        <?php endif; ?>
                        <?php if (!empty($last_med['diagnosis'])): ?><div class="small"><span
                                class="k"><?= h(t('pdf.diagnosis')) ?> :</span> <?= h($last_med['diagnosis']) ?></div>
                        <?php endif; ?>
                        <?php if (!empty($last_med['plan'])): ?><div class="small"><span
                                class="k"><?= h(t('pdf.plan')) ?> :</span> <?= h($last_med['plan']) ?></div>
                        <?php endif; ?>
                        <?php endif; ?>
                    </div>

                    <div class="sep"></div>

                    <div>
                        <span class="tag"><?= h(t('pdf.next_vaccine')) ?></span>
                        <?php if (empty($next_vaccine)): ?>
                        <span class="muted">—</span>
                        <?php else: ?>
                        <span><?= h($next_vaccine['vaccine_name'] ?? '') ?></span>
                        • <span class="k"><?= h($next_vaccine['due_date'] ?? '') ?></span>
                        <?php endif; ?>
                    </div>

                    <?php if (!empty($animal['notes'])): ?>
                    <div class="sep"></div>
                    <div class="k"><?= h(t('common.notes')) ?></div>
                    <div><?= nl2br(h($animal['notes'])) ?></div>
                    <?php endif; ?>
                </div>

                <div class="sep"></div>
                <div class="muted small">
                    <?= h(t('pdf.internal_document', ['association' => AppSettings::get('association_name')])) ?>
                </div>
            </td>
        </tr>
    </table>

    <h2><?= h(t('pdf.medical_notes')) ?></h2>
    <?php if (empty($medical_notes)): ?>
    <div class="muted"><?= h(t('pdf.no_medical_notes')) ?></div>
    <?php else: ?>
    <table class="grid">
        <tr>
            <th style="width:90px;"><?= h(t('common.date')) ?></th>
            <th style="width:80px;"><?= h(t('animal.form.type')) ?></th>
            <th><?= h(t('pdf.content')) ?></th>
            <th style="width:170px;"><?= h(t('pdf.clinic_vet')) ?></th>
        </tr>
        <?php foreach ($medical_notes as $n): ?>
        <tr>
            <td><?= h(substr((string)$n['noted_at'], 0, 10)) ?></td>
            <td><span class="badge <?= kindClass((string)($n['kind'] ?? '')) ?>">
                    <?= h($n['kind'] ?? '') ?>
                </span></td>
            <td>
                <?php if (!empty($n['reason'])): ?><b><?= h(t('pdf.reason')) ?>:</b>
                <?= h($n['reason']) ?><br><?php endif; ?>
                <?php if (!empty($n['weight_kg'])): ?><b><?= h(t('pdf.weight')) ?>:</b> <?= h($n['weight_kg']) ?>
                kg<br><?php endif; ?>
                <?php if (!empty($n['symptoms'])): ?><b><?= h(t('pdf.symptoms')) ?>:</b>
                <?= nl2br(h($n['symptoms'])) ?><br><?php endif; ?>
                <?php if (!empty($n['exam'])): ?><b><?= h(t('pdf.exam')) ?>:</b>
                <?= nl2br(h($n['exam'])) ?><br><?php endif; ?>
                <?php if (!empty($n['diagnosis'])): ?><b><?= h(t('pdf.diagnosis')) ?>:</b>
                <?= nl2br(h($n['diagnosis'])) ?><br><?php endif; ?>
                <?php if (!empty($n['plan'])): ?><b><?= h(t('pdf.plan')) ?>:</b>
                <?= nl2br(h($n['plan'])) ?><br><?php endif; ?>
                <?php
                        $notePhotos = $medicalPhotosByNote[$n['id']] ?? [];
            ?>

                <?php if (!empty($notePhotos)): ?>
                <div style="margin-top:8px;">
                    <strong><?= h(t('pdf.photos')) ?> :</strong><br>

                    <?php foreach ($notePhotos as $p):
                        $absolutePath = __DIR__ . '/../../data/private-media/animals/' . (int)$animal['id'] . '/meds/' . $p['filename'];
                        if (file_exists($absolutePath)):

                            $uri = fileToDataUri($absolutePath);
                            ?>
                    <img src="<?= $uri ?>" style="width:160px;">
                    <?php endif; endforeach; ?>
                </div>
                <?php endif; ?>
            </td>
            <td>
                <?php if (!empty($n['clinic_name'])): ?><?= h($n['clinic_name']) ?><br><?php endif; ?>
                <?php if (!empty($n['vet_name'])): ?><?= h($n['vet_name']) ?><?php endif; ?>

            </td>
        </tr>
        <?php endforeach; ?>
    </table>
    <?php endif; ?>

    <h2><?= h(t('pdf.treatments')) ?></h2>
    <?php if (empty($treatments)): ?>
    <div class="muted"><?= h(t('pdf.no_treatment')) ?></div>
    <?php else: ?>
    <table class="grid">
        <tr>
            <th style="width:65px;"><?= h(t('pdf.state')) ?></th>
            <th><?= h(t('pdf.medication')) ?></th>
            <th style="width:95px;"><?= h(t('pdf.start')) ?></th>
            <th style="width:95px;"><?= h(t('pdf.end')) ?></th>
            <th style="width:170px;"><?= h(t('pdf.clinic_vet')) ?></th>
            <th><?= h(t('common.notes')) ?></th>
        </tr>
        <?php foreach ($treatments as $t): ?>
        <tr>
            <td><?= ((int)$t['ongoing'] === 1) ? t('pdf.ongoing') : t('pdf.finished') ?></td>
            <td><?= h($t['medication_name'] ?? '') ?></td>
            <td><?= h($t['start_date'] ?? '') ?></td>
            <td><?= h($t['end_date'] ?? '') ?></td>
            <td>
                <?php if (!empty($t['clinic_name'])): ?><?= h($t['clinic_name']) ?><br><?php endif; ?>
                <?php if (!empty($t['vet_name'])): ?><?= h($t['vet_name']) ?><?php endif; ?>
            </td>
            <td class="small">
                <?php if (!empty($t['route'])): ?><b><?= h(t('pdf.route')) ?>:</b>
                <?= h($t['route']) ?><br><?php endif; ?>
                <?php if (!empty($t['dose_text'])): ?><b><?= h(t('pdf.dosage')) ?>:</b>
                <?= h($t['dose_text']) ?><br><?php endif; ?>
                <?= !empty($t['notes']) ? nl2br(h($t['notes'])) : '' ?>
            </td>
        </tr>
        <?php endforeach; ?>
    </table>
    <?php endif; ?>

    <h2><?= h(t('pdf.vaccines')) ?></h2>
    <?php if (empty($vaccinations)): ?>
    <div class="muted"><?= h(t('pdf.no_vaccine')) ?></div>
    <?php else: ?>
    <table class="grid">
        <tr>
            <th><?= h(t('pdf.vaccine')) ?></th>
            <th style="width:95px;"><?= h(t('pdf.done_on')) ?></th>
            <th style="width:95px;"><?= h(t('pdf.booster')) ?></th>
            <th style="width:170px;"><?= h(t('pdf.clinic_vet')) ?></th>
            <th><?= h(t('common.notes')) ?></th>
        </tr>
        <?php foreach ($vaccinations as $v): ?>
        <tr>
            <td><?= h($v['vaccine_name'] ?? '') ?></td>
            <td><?= h($v['done_date'] ?? '') ?></td>
            <td><?= h($v['due_date'] ?? '') ?></td>
            <td>
                <?php if (!empty($v['clinic_name'])): ?><?= h($v['clinic_name']) ?><br><?php endif; ?>
                <?php if (!empty($v['vet_name'])): ?><?= h($v['vet_name']) ?><?php endif; ?>
            </td>
            <td class="small">
                <?php if (!empty($v['lot'])): ?><b><?= h(t('pdf.lot')) ?>:</b> <?= h($v['lot']) ?><br><?php endif; ?>
                <?= !empty($v['notes']) ? nl2br(h($v['notes'])) : '' ?>
            </td>
        </tr>
        <?php endforeach; ?>
    </table>
    <?php endif; ?>

</body>

</html>
