<?php
// ============================================================
//  Admin: edit a member
// ============================================================
//
//  Admins can change any field on a member record. Changes are
//  validated against local DB and Zoho Books for duplicates, then
//  pushed to Zoho first before being persisted locally — so member
//  records and Zoho contacts stay in lock-step.
//
// ============================================================

$page_title = 'Edit Member';
require __DIR__ . '/_guard.php';
require_once __DIR__ . '/../includes/zoho.php';
require_once __DIR__ . '/../includes/member_history.php';

$id = (int)($_GET['id'] ?? 0);
$member = db_row('SELECT * FROM members WHERE id = :id', ['id' => $id]);
if (!$member) {
    http_response_code(404);
    exit('Member not found.');
}

$categories = require __DIR__ . '/../data/categories.php';

$saved = false;
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $action = $_POST['action'] ?? 'save';

    if ($action === 'zoho_sync') {
        $zoho_synced = zoho_sync_member($id);
        $member = db_row('SELECT * FROM members WHERE id = :id', ['id' => $id]);

    } elseif ($action === 'add_note') {
        $note_body = trim((string)($_POST['note_body'] ?? ''));
        if ($note_body !== '') {
            // First line (or first 80 chars) becomes the timeline summary;
            // full text goes in body so it's preserved as the admin typed it.
            $first_line = trim(strtok($note_body, "\n")) ?: $note_body;
            $summary = mb_strlen($first_line) > 80
                ? mb_substr($first_line, 0, 77) . '…'
                : $first_line;
            member_history_log((int)$id, 'note', $summary, $note_body);
            $note_added = true;
        }

    } elseif ($action === 'journey_update') {
        require_once __DIR__ . '/../includes/journey.php';
        $statuses = $_POST['step_status'] ?? [];
        $notes_in = $_POST['step_notes']  ?? [];
        if (is_array($statuses)) {
            foreach ($statuses as $sid => $st) {
                $sid = (int)$sid;
                if (!$sid) continue;
                $note = isset($notes_in[$sid]) ? trim((string)$notes_in[$sid]) : null;
                if ($note === '') $note = null;
                journey_update_progress($id, $sid, (string)$st, $note);
            }
        }
        $journey_saved = true;

    } elseif ($action === 'save') {
        $updates = [
            'first_name'    => trim($_POST['first_name']    ?? ''),
            'last_name'     => trim($_POST['last_name']     ?? ''),
            'phone'         => trim($_POST['phone']         ?? '') ?: null,
            'business_name' => trim($_POST['business_name'] ?? ''),
            'industry'      => trim($_POST['industry']      ?? '') ?: null,
            'tier'          => trim($_POST['tier']          ?? 'Bronze'),
            'status'        => trim($_POST['status']        ?? 'pending'),
            'renewal_date'  => trim($_POST['renewal_date']  ?? '') ?: null,
            'join_date'     => trim($_POST['join_date']     ?? '') ?: null,
            'banking_details' => trim($_POST['banking_details'] ?? '') ?: null,
        ];

        // Email is editable separately so admin can fix typos. Only include if actually changed.
        $new_email = strtolower(trim((string)($_POST['email'] ?? '')));
        $email_changed = ($new_email !== '' && $new_email !== strtolower(trim((string)$member['email'])));
        if ($email_changed) {
            $updates['email'] = $new_email;
        }

        // Validate enums
        if (!in_array($updates['tier'], ['Bronze','Silver','Gold','Platinum','Diamond'], true)) {
            $error = 'Invalid tier.';
        } elseif (!in_array($updates['status'], ['pending','active','suspended','cancelled'], true)) {
            $error = 'Invalid status.';
        } else {
            // ── Pre-flight: validate + dupe check against local DB and Zoho ──
            require_once __DIR__ . '/../includes/zoho.php';
            $check_payload = [
                'first_name'    => $updates['first_name'],
                'last_name'     => $updates['last_name'],
                'business_name' => $updates['business_name'],
                'phone'         => $updates['phone'],
            ];
            if ($email_changed) $check_payload['email'] = $new_email;

            $check = zoho_validate_member_changes((int)$id, $check_payload);
            if (!$check['ok']) {
                $error = $check['error'];
            } else {
                // ── Push to Zoho FIRST so we never have local-only changes ───
                $zoho_ok = true;
                $zoho_msg = '';
                if (!empty($member['zoho_contact_id'])) {
                    $zoho_payload = $check_payload;  // same fields
                    $r = zoho_update_contact((string)$member['zoho_contact_id'], $zoho_payload, (int)$id);
                    if (!$r['ok']) {
                        $zoho_ok  = false;
                        $zoho_msg = $r['error'] ?? 'Unknown Zoho error';
                    }
                }

                if (!$zoho_ok) {
                    $error = 'Could not save: Zoho rejected the change. ' . $zoho_msg;
                } else {
                    // Apply locally
                    $before = $member;  // snapshot for diff
                    db_update('members', $id, $updates);

                    $after = db_row('SELECT * FROM members WHERE id = :id', ['id' => $id]);

                    // Log the change to member history
                    $watch = array_keys($updates);
                    member_history_log_changes((int)$id, $before, $after, $watch);

                    // Special-case: status flip to cancelled gets its own event
                    if ($member['status'] !== 'cancelled' && $updates['status'] === 'cancelled') {
                        member_history_log((int)$id, 'cancelled',
                            'Member cancelled by admin',
                            null
                        );
                        app_log("Admin cancelled member $id ({$after['email']})");
                    }

                    $member = $after;
                    $saved = true;
                }
            }
        }
    }
}

// Fetch related data for display
// (No more local invoices/activity queries — invoice history lives in
// the dedicated /admin/invoices.php page now, and member activity is
// tracked through Settings → Zoho Books log + email log.)

// Journey data — needed in the right column under the Zoho card
require_once __DIR__ . '/../includes/journey.php';
$journey_rows     = journey_load((int)$id, $member['tier']);
$journey_pct      = journey_percent($journey_rows);
$journey_cnts     = journey_counts($journey_rows);
$journey_complete = ($journey_pct === 100 && !empty($journey_rows));
?>

<section class="section">
    <div class="container">

        <p class="muted" style="margin:0;font-size:.9rem;">
            <a href="members.php">&larr; All members</a>
        </p>
        <h1>Edit member #<?= $id ?></h1>

        <?php if ($saved): ?>
            <div class="alert alert-success" data-autohide>
                <strong>Saved.</strong> Member record updated and synced to Zoho.
            </div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="alert alert-error"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <div class="grid grid-2">

            <!-- Main edit form -->
            <form method="post" action="member-edit.php?id=<?= $id ?>" class="card">
                <?= csrf_field() ?>
                <input type="hidden" name="action" value="save">

                <h2 style="margin-top:0;">Details</h2>

                <div class="grid grid-2" style="gap:0 1.25rem;">
                    <div>
                        <label>First name *</label>
                        <input type="text" name="first_name" required value="<?= htmlspecialchars($member['first_name']) ?>">
                    </div>
                    <div>
                        <label>Last name *</label>
                        <input type="text" name="last_name" required value="<?= htmlspecialchars($member['last_name']) ?>">
                    </div>
                </div>

                <label>Email *</label>
                <input type="email" name="email" required value="<?= htmlspecialchars($member['email']) ?>">
                <p class="muted" style="font-size:.8rem;margin-top:.25rem;">
                    Changing the email will update it in Zoho Books too. Duplicate-checked against
                    other members and existing Zoho customers before saving.
                </p>

                <label>Phone</label>
                <input type="tel" name="phone" value="<?= htmlspecialchars($member['phone'] ?? '') ?>">

                <label>Business name *</label>
                <input type="text" name="business_name" required value="<?= htmlspecialchars($member['business_name']) ?>">

                <label>Industry</label>
                <select name="industry">
                    <option value="">&mdash; none &mdash;</option>
                    <?php foreach ($categories as $c): ?>
                        <option value="<?= htmlspecialchars($c['slug']) ?>"
                                <?= ($member['industry'] ?? '') === $c['slug'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($c['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <hr style="margin:1.5rem 0;border:none;border-top:1px solid var(--line);">

                <h3>Membership</h3>

                <div class="grid grid-2" style="gap:0 1.25rem;">
                    <div>
                        <label>Tier *</label>
                        <select name="tier" required>
                            <?php foreach (['Bronze','Silver','Gold','Platinum','Diamond'] as $t): ?>
                                <option value="<?= $t ?>" <?= $member['tier']===$t?'selected':'' ?>><?= $t ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label>Status *</label>
                        <select name="status" required>
                            <?php foreach (['pending','active','suspended','cancelled'] as $s): ?>
                                <option value="<?= $s ?>" <?= $member['status']===$s?'selected':'' ?>><?= $s ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="grid grid-2" style="gap:0 1.25rem;">
                    <div>
                        <label>Join date</label>
                        <input type="date" name="join_date" value="<?= htmlspecialchars($member['join_date'] ?? '') ?>">
                    </div>
                    <div>
                        <label>Renewal date</label>
                        <input type="date" name="renewal_date" value="<?= htmlspecialchars($member['renewal_date'] ?? '') ?>">
                    </div>
                </div>

                <label>Banking details on file</label>
                <textarea name="banking_details" rows="4"><?= htmlspecialchars($member['banking_details'] ?? '') ?></textarea>

                <hr style="margin:1.5rem 0;border:none;border-top:1px solid var(--line);">

                <h3>Administration</h3>
                <p class="muted" style="font-size:.85rem;margin-top:0;">
                    Admin users are managed separately on the
                    <?php if (!empty($admin['role']) && $admin['role'] === 'super_admin'): ?>
                        <a href="users.php">Admin Users page</a>.
                    <?php else: ?>
                        Admin Users page (super_admin only).
                    <?php endif; ?>
                </p>

                <button type="submit" class="btn mt-3">Save changes</button>
                <a href="members.php" class="btn btn-outline mt-3">Cancel</a>

                <p class="muted mt-3" style="font-size:.85rem;">
                    Saving updates the DB record and syncs the contact to Zoho Books.
                    Email and business name changes are duplicate-checked locally and against
                    Zoho before saving. Setting status to <code>cancelled</code> also schedules
                    the cancellation email and listing removal.
                </p>
            </form>

            <div>
                <!-- Zoho sync card -->
                <form method="post" action="member-edit.php?id=<?= $id ?>" class="card">
                    <?= csrf_field() ?>
                    <input type="hidden" name="action" value="zoho_sync">

                    <h3 style="margin-top:0;">Zoho Books</h3>
                    <?php if (!empty($member['zoho_contact_id'])): ?>
                        <p style="font-size:.9rem;margin:0 0 .5rem;">
                            <span class="tag tag-ok">✓ Linked</span>
                            <code style="font-size:.78rem;"><?= htmlspecialchars($member['zoho_contact_id']) ?></code>
                        </p>
                        <p class="muted" style="font-size:.85rem;margin:0 0 .75rem;">
                            This member has a Zoho Books contact. Click below to verify or repair the link.
                        </p>
                    <?php else: ?>
                        <p style="font-size:.9rem;margin:0 0 .75rem;">
                            <span class="tag tag-err">Not linked</span>
                            No Zoho Books contact for this member yet.
                        </p>
                    <?php endif; ?>
                    <?php if (isset($zoho_synced)): ?>
                        <div class="alert <?= $zoho_synced ? 'alert-success' : 'alert-error' ?>" style="margin:0 0 .75rem;font-size:.85rem;">
                            <?= $zoho_synced ? '✓ Synced to Zoho.' : '✗ Sync failed — see Zoho log.' ?>
                        </div>
                    <?php endif; ?>
                    <button type="submit" class="btn btn-outline">
                        <?= !empty($member['zoho_contact_id']) ? 'Re-sync to Zoho' : 'Create in Zoho' ?>
                    </button>
                    <a href="zoho-log.php" style="display:inline-block;margin-left:.5rem;font-size:.82rem;">View log →</a>

                    <?php if (!empty($member['zoho_contact_id'])): ?>
                        <hr style="margin:1rem 0;border:none;border-top:1px solid var(--line);">
                        <p class="muted" style="font-size:.85rem;margin:0 0 .5rem;">
                            Customer history pulled live from Zoho Books.
                        </p>
                        <a href="../member/view-statement.php?member_id=<?= $id ?>" target="_blank" class="btn btn-outline" style="margin-right:.4rem;">
                            View statement
                        </a>
                        <a href="../admin/invoices.php?q=<?= urlencode($member['email']) ?>" class="btn btn-outline">
                            View invoices
                        </a>
                    <?php endif; ?>
                </form>

                <!-- Journey -->
                <div id="journey" class="card mt-3" style="padding:1.5rem;">
                    <div style="display:flex;justify-content:space-between;align-items:center;gap:1rem;flex-wrap:wrap;margin-bottom:1rem;">
                        <div>
                            <h2 style="margin:0;">Onboarding Journey</h2>
                            <p class="muted" style="margin:.2rem 0 0;font-size:.88rem;">
                                <?= htmlspecialchars($member['tier']) ?>-tier checklist ·
                                <?= $journey_cnts['done'] ?> done ·
                                <?= $journey_cnts['in_progress'] ?> in progress ·
                                <?= $journey_cnts['not_started'] ?> not started
                            </p>
                        </div>
                        <a href="journey-templates.php" style="font-size:.82rem;">⚙ Edit template</a>
                    </div>

                    <?php if (!empty($journey_saved)): ?>
                        <div class="alert alert-success" data-autohide>Journey updated.</div>
                    <?php endif; ?>

                    <div class="jp-bar-label">
                        <span>Overall progress</span>
                        <span class="pct"><?= $journey_pct ?>%</span>
                    </div>
                    <div class="jp-bar" style="margin-bottom:1.25rem;">
                        <div class="jp-bar-fill <?= $journey_complete ? 'complete' : '' ?>" style="width:<?= $journey_pct ?>%;"></div>
                    </div>

                    <?php if (empty($journey_rows)): ?>
                        <p class="muted" style="font-size:.9rem;">
                            No journey steps configured for <?= htmlspecialchars($member['tier']) ?> tier.
                            <a href="journey-templates.php">Set them up →</a>
                        </p>
                    <?php else: ?>
                        <form method="post" action="member-edit.php?id=<?= $id ?>#journey">
                            <?= csrf_field() ?>
                            <input type="hidden" name="action" value="journey_update">

                            <?php foreach ($journey_rows as $i => $row):
                                $st = $row['status'];
                            ?>
                                <div class="j-step <?= htmlspecialchars($st) ?>">
                                    <div class="j-step-num"><?= ($i+1) ?></div>
                                    <div class="j-step-body">
                                        <h4><?= htmlspecialchars($row['name']) ?></h4>
                                        <?php if (!empty($row['description'])): ?>
                                            <p><?= htmlspecialchars($row['description']) ?></p>
                                        <?php endif; ?>
                                        <?php if ($row['completed_at']): ?>
                                            <div class="j-meta">✓ Completed <?= date('j M Y', strtotime($row['completed_at'])) ?></div>
                                        <?php elseif ($row['started_at']): ?>
                                            <div class="j-meta">Started <?= date('j M Y', strtotime($row['started_at'])) ?></div>
                                        <?php endif; ?>
                                    </div>
                                    <select name="step_status[<?= $row['id'] ?>]">
                                        <option value="not_started" <?= $st==='not_started'?'selected':'' ?>>Not started</option>
                                        <option value="in_progress" <?= $st==='in_progress'?'selected':'' ?>>In progress</option>
                                        <option value="done"        <?= $st==='done'?'selected':'' ?>>Done</option>
                                    </select>

                                    <div class="j-step-notes">
                                        <button type="button" class="j-step-notes-toggle"
                                                onclick="this.nextElementSibling.style.display=this.nextElementSibling.style.display==='block'?'none':'block';">
                                            📝 <?= !empty($row['notes']) ? 'Edit note' : 'Add note' ?>
                                        </button>
                                        <textarea name="step_notes[<?= $row['id'] ?>]" rows="2"
                                            placeholder="Internal note — only visible to admins"
                                            style="display:<?= !empty($row['notes']) ? 'block' : 'none' ?>;margin-top:.3rem;"><?= htmlspecialchars($row['notes'] ?? '') ?></textarea>
                                    </div>
                                </div>
                            <?php endforeach; ?>

                            <div style="display:flex;justify-content:flex-end;gap:.75rem;margin-top:1rem;">
                                <button type="submit" class="btn">Save journey</button>
                            </div>
                        </form>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- ========================================================== -->
        <!--  Member history & internal notes                           -->
        <!-- ========================================================== -->
        <?php
        $history = db_all(
            'SELECT * FROM member_history WHERE member_id = :id
              ORDER BY occurred_at DESC, id DESC LIMIT 200',
            ['id' => $id]
        );

        $event_meta = [
            'note'                   => ['icon'=>'📝', 'color'=>'#f59e0b', 'label'=>'Note'],
            'profile_updated'        => ['icon'=>'✏️', 'color'=>'#6366f1', 'label'=>'Profile updated'],
            'status_changed'         => ['icon'=>'⚡', 'color'=>'#6366f1', 'label'=>'Status changed'],
            'tier_changed'           => ['icon'=>'⭐', 'color'=>'#6366f1', 'label'=>'Tier changed'],
            'cancelled'              => ['icon'=>'✕',  'color'=>'#dc2626', 'label'=>'Cancelled'],
            'cancellation_scheduled' => ['icon'=>'⏳', 'color'=>'#dc2626', 'label'=>'Cancellation scheduled'],
            'subscription_added'     => ['icon'=>'➕', 'color'=>'#10b981', 'label'=>'Subscription added'],
            'subscription_cancelled' => ['icon'=>'✕',  'color'=>'#dc2626', 'label'=>'Subscription cancelled'],
            'subscription_reactivated' => ['icon'=>'↻', 'color'=>'#10b981', 'label'=>'Reactivated'],
            'payment_received'       => ['icon'=>'💰', 'color'=>'#10b981', 'label'=>'Payment received'],
            'invoice_synced'         => ['icon'=>'📄', 'color'=>'#06b6d4', 'label'=>'Invoice synced'],
            'zoho_synced'            => ['icon'=>'🔗', 'color'=>'#06b6d4', 'label'=>'Zoho synced'],
            'zoho_failed'            => ['icon'=>'⚠️', 'color'=>'#dc2626', 'label'=>'Zoho sync failed'],
            'signup'                 => ['icon'=>'🎉', 'color'=>'#10b981', 'label'=>'Signed up'],
            'listing_updated'        => ['icon'=>'📋', 'color'=>'#6366f1', 'label'=>'Listing updated'],
        ];
        $default_meta = ['icon'=>'•', 'color'=>'#9ca3af', 'label'=>'Event'];

        function fmt_diff_value($v): string {
            if ($v === null || $v === '') return '<em style="color:#9ca3af;">empty</em>';
            return htmlspecialchars((string)$v);
        }
        ?>

        <div id="history" class="card mt-3" style="padding:1.5rem;">
            <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:1rem;flex-wrap:wrap;margin-bottom:.25rem;">
                <h2 style="margin:0;">History &amp; notes</h2>
                <a href="task-edit.php?member_id=<?= $id ?>" class="btn btn-outline" style="font-size:.82rem;padding:.4rem .85rem;">
                    + Create task for this member
                </a>
            </div>
            <p class="muted" style="margin:.25rem 0 1.25rem;font-size:.85rem;">
                Everything that's happened to this member, plus internal notes for hand-off between team members.
                Notes are visible to admins only — never to the member.
            </p>

            <!-- Add a note -->
            <?php if (!empty($note_added)): ?>
                <div class="alert alert-success" data-autohide style="margin-bottom:1rem;">
                    <strong>Note added.</strong>
                </div>
            <?php endif; ?>

            <form method="post" action="member-edit.php?id=<?= $id ?>#history" style="margin-bottom:1.5rem;">
                <?= csrf_field() ?>
                <input type="hidden" name="action" value="add_note">

                <label for="note_body" style="display:block;font-weight:600;font-size:.85rem;margin-bottom:.4rem;">
                    Add an internal note
                </label>
                <textarea id="note_body" name="note_body" rows="3" maxlength="4000"
                          placeholder="e.g. Spoke to John on the phone — wants to upgrade to Silver next month. Following up Friday."
                          style="width:100%;padding:.65rem .8rem;border:1px solid var(--line);border-radius:6px;font-size:.9rem;font-family:inherit;resize:vertical;"></textarea>
                <div style="display:flex;justify-content:flex-end;margin-top:.5rem;">
                    <button type="submit" class="btn">Add note</button>
                </div>
            </form>

            <!-- Timeline -->
            <?php if (empty($history)): ?>
                <p class="muted" style="font-size:.9rem;text-align:center;padding:1.5rem;">
                    No history recorded yet.
                </p>
            <?php else: ?>
                <div class="mh-timeline">
                    <?php foreach ($history as $h):
                        $meta = $event_meta[$h['event_type']] ?? $default_meta;
                        $is_note = $h['event_type'] === 'note';
                        $diff = null;
                        if (!$is_note && $h['body']) {
                            $maybe = json_decode($h['body'], true);
                            if (is_array($maybe)) $diff = $maybe;
                        }
                    ?>
                        <div class="mh-row <?= $is_note ? 'mh-note' : '' ?>">
                            <div class="mh-dot" style="background:<?= htmlspecialchars($meta['color']) ?>;">
                                <?= $meta['icon'] ?>
                            </div>
                            <div class="mh-body">
                                <div class="mh-head">
                                    <strong class="mh-summary">
                                        <?= $is_note ? '📝 Note' : htmlspecialchars($h['summary']) ?>
                                    </strong>
                                    <span class="mh-meta">
                                        <?= htmlspecialchars(date('j M Y · H:i', strtotime($h['occurred_at']))) ?>
                                        <?php if (!$is_note && $h['actor_type'] && $h['actor_type'] !== 'system'): ?>
                                            · <?= htmlspecialchars(ucfirst($h['actor_type'])) ?><?= $h['actor_name'] ? ': '.htmlspecialchars($h['actor_name']) : '' ?>
                                        <?php elseif (!$is_note && $h['actor_type'] === 'system'): ?>
                                            · automated
                                        <?php endif; ?>
                                    </span>
                                </div>

                                <?php if ($is_note && !empty($h['body'])): ?>
                                    <div class="mh-note-body"><?= nl2br(htmlspecialchars($h['body'])) ?></div>
                                    <div class="mh-note-attr">
                                        — <strong><?= htmlspecialchars($h['actor_name'] ?: 'Unknown user') ?></strong>
                                        <?php if (!empty($h['actor_type']) && $h['actor_type'] !== 'system'): ?>
                                            <span class="mh-note-attr-role">(<?= htmlspecialchars(ucfirst($h['actor_type'])) ?>)</span>
                                        <?php endif; ?>
                                    </div>
                                <?php elseif ($diff): ?>
                                    <table class="mh-diff">
                                        <?php foreach ($diff as $field => $change): ?>
                                            <tr>
                                                <td class="mh-diff-field"><?= htmlspecialchars(member_history_field_label((string)$field)) ?></td>
                                                <td class="mh-diff-from"><?= fmt_diff_value($change['from'] ?? null) ?></td>
                                                <td class="mh-diff-arrow">→</td>
                                                <td class="mh-diff-to"><?= fmt_diff_value($change['to'] ?? null) ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </table>
                                <?php elseif (!empty($h['body'])): ?>
                                    <div class="mh-text"><?= nl2br(htmlspecialchars($h['body'])) ?></div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <style>
        .mh-timeline{position:relative;}
        .mh-row{position:relative;display:flex;gap:1rem;padding:.5rem 0 1rem 0;}
        .mh-row:not(:last-child)::before{
            content:'';position:absolute;left:14px;top:32px;bottom:0;width:2px;background:#e5e7eb;
        }
        .mh-dot{
            width:30px;height:30px;border-radius:50%;display:flex;align-items:center;justify-content:center;
            color:#fff;font-size:.85rem;flex-shrink:0;z-index:1;font-weight:600;
        }
        .mh-body{flex:1;min-width:0;padding-top:.25rem;}
        .mh-head{display:flex;justify-content:space-between;align-items:flex-start;gap:.75rem;flex-wrap:wrap;margin-bottom:.25rem;}
        .mh-summary{font-size:.92rem;color:#1f2937;}
        .mh-meta{font-size:.72rem;color:#6b7280;white-space:nowrap;}

        .mh-note .mh-body{
            background:#fef9c3;border:1px solid #fde047;border-radius:6px;padding:.65rem .85rem;margin-top:-.1rem;
        }
        .mh-note-body{
            font-size:.9rem;color:#713f12;margin-top:.4rem;line-height:1.45;white-space:pre-wrap;
        }
        .mh-note-attr{
            margin-top:.75rem;padding-top:.5rem;border-top:1px dashed #d4a015;
            font-size:.78rem;color:#713f12;font-style:italic;text-align:right;
        }
        .mh-note-attr strong{font-weight:700;font-style:normal;}
        .mh-note-attr-role{color:#a16207;font-size:.72rem;margin-left:.25rem;}

        .mh-diff{margin-top:.4rem;font-size:.82rem;border-collapse:collapse;}
        .mh-diff td{padding:.2rem .5rem;vertical-align:top;}
        .mh-diff-field{color:#6b7280;font-weight:600;white-space:nowrap;}
        .mh-diff-from{color:#9ca3af;text-decoration:line-through;max-width:280px;overflow-wrap:break-word;}
        .mh-diff-arrow{color:#9ca3af;}
        .mh-diff-to{color:#1f2937;font-weight:600;max-width:280px;overflow-wrap:break-word;}
        .mh-text{font-size:.85rem;color:#4b5563;margin-top:.3rem;line-height:1.45;}
        </style>
    </div>
</section>

<?php require __DIR__ . '/_footer.php'; ?>