<?php $m = $member; ?>
<div class="row g-4">
    <!-- Left Sidebar -->
    <div class="col-lg-3">
        <div class="card text-center">
            <div class="card-body">
                <?php if ($m['photo_path']): ?>
                <img src="/uploads/<?= e($m['photo_path']) ?>" class="rounded-circle mb-3" style="width:120px;height:120px;object-fit:cover" alt="">
                <?php else: ?>
                <div class="rounded-circle bg-secondary d-inline-flex align-items-center justify-content-center mb-3" style="width:120px;height:120px"><i class="fas fa-user fa-3x text-white"></i></div>
                <?php endif; ?>
                <h5><?= e($m['full_name_en']) ?><?php if ($m['vip']): ?> <i class="fas fa-star text-warning"></i><?php endif; ?></h5>
                <?php if ($m['full_name_ar']): ?><p class="text-muted mb-1"><?= e($m['full_name_ar']) ?></p><?php endif; ?>
                <p class="mb-1"><strong><?= e($m['membership_number']) ?></strong></p>
                <p class="mb-2"><?= status_badge($m['status']) ?></p>
                <p class="small text-muted mb-0"><?= e($m['type_name_en']) ?></p>
            </div>
            <div class="card-footer">
                <div class="d-flex gap-1 justify-content-center flex-wrap">
                    <?php if (auth_can('members.edit')): ?>
                    <a href="/members/<?= $m['id'] ?>/edit" class="btn btn-sm btn-outline-warning"><i class="fas fa-edit"></i></a>
                    <?php endif; ?>
                    <a href="/members/<?= $m['id'] ?>/print" class="btn btn-sm btn-outline-info" target="_blank"><i class="fas fa-print"></i></a>
                    <?php if (auth_can('members.status')): ?>
                    <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#statusModal"><i class="fas fa-exchange-alt"></i></button>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Quick Info -->
        <div class="card mt-3">
            <div class="card-body small">
                <?php if ($m['primary_phone']): ?><p class="mb-1"><i class="fas fa-phone me-2 text-muted"></i><?= e($m['primary_phone']) ?></p><?php endif; ?>
                <?php if ($m['primary_email']): ?><p class="mb-1"><i class="fas fa-envelope me-2 text-muted"></i><?= e($m['primary_email']) ?></p><?php endif; ?>
                <?php if ($m['nationality_en']): ?><p class="mb-1"><i class="fas fa-flag me-2 text-muted"></i><?= e($m['nationality_en']) ?></p><?php endif; ?>
                <?php if ($m['date_of_birth']): ?><p class="mb-1"><i class="fas fa-birthday-cake me-2 text-muted"></i><?= format_date($m['date_of_birth']) ?></p><?php endif; ?>
                <p class="mb-1"><i class="fas fa-calendar me-2 text-muted"></i>Joined: <?= format_date($m['join_date']) ?></p>
                <p class="mb-0"><i class="fas fa-walking me-2 text-muted"></i>Visits: <?= number_format($m['visit_count']) ?></p>
            </div>
        </div>

        <!-- Tags -->
        <div class="card mt-3">
            <div class="card-header py-2"><small class="fw-bold">Tags</small></div>
            <div class="card-body" id="tags-container">
                <?php foreach ($tags as $tag): ?>
                <span class="badge me-1 mb-1" style="background:<?= e($tag['tag_color'] ?? '#6c757d') ?>"><?= e($tag['tag_name']) ?>
                    <?php if (auth_can('members.edit')): ?>
                    <i class="fas fa-times ms-1 btn-remove-tag" data-id="<?= $tag['id'] ?>" style="cursor:pointer"></i>
                    <?php endif; ?>
                </span>
                <?php endforeach; ?>
                <?php if (auth_can('members.edit')): ?>
                <div class="input-group input-group-sm mt-2">
                    <input type="text" class="form-control" id="new-tag-input" placeholder="Add tag...">
                    <button class="btn btn-outline-primary" id="btn-add-tag"><i class="fas fa-plus"></i></button>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="col-lg-9">
        <ul class="nav nav-tabs mb-3" role="tablist">
            <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#t-overview">Overview</a></li>
            <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#t-family">Family & Deps</a></li>
            <?php if (auth_can('members.financial')): ?>
            <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#t-financial">Financial</a></li>
            <?php endif; ?>
            <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#t-docs">Documents</a></li>
            <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#t-subs">Subscriptions</a></li>
            <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#t-notes">Notes</a></li>
            <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#t-history">History</a></li>
        </ul>

        <div class="tab-content">
            <!-- Overview -->
            <div class="tab-pane fade show active" id="t-overview">
                <div class="card"><div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <table class="table table-sm table-borderless">
                                <tr><td class="text-muted w-40">National ID</td><td><?= e($m['national_id'] ?? '—') ?></td></tr>
                                <tr><td class="text-muted">Passport</td><td><?= e($m['passport_number'] ?? '—') ?></td></tr>
                                <tr><td class="text-muted">Gender</td><td><?= ucfirst($m['gender']) ?></td></tr>
                                <tr><td class="text-muted">Marital Status</td><td><?= ucfirst($m['marital_status'] ?? '—') ?></td></tr>
                                <tr><td class="text-muted">Occupation</td><td><?= e($m['occupation'] ?? '—') ?></td></tr>
                                <tr><td class="text-muted">Employer</td><td><?= e($m['employer'] ?? '—') ?></td></tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <table class="table table-sm table-borderless">
                                <tr><td class="text-muted w-40">Address</td><td><?= e($m['address_line1'] ?? '—') ?></td></tr>
                                <tr><td class="text-muted">City</td><td><?= e($m['city_en'] ?? '—') ?></td></tr>
                                <tr><td class="text-muted">Country</td><td><?= e($m['country_en'] ?? '—') ?></td></tr>
                                <tr><td class="text-muted">Emergency</td><td><?= e($m['emergency_contact_name'] ?? '—') ?> <?= $m['emergency_contact_phone'] ? '(' . e($m['emergency_contact_phone']) . ')' : '' ?></td></tr>
                                <tr><td class="text-muted">Last Visit</td><td><?= format_date($m['last_visit_date']) ?: '—' ?></td></tr>
                                <tr><td class="text-muted">Balance</td><td class="<?= $m['outstanding_balance'] > 0 ? 'text-danger fw-bold' : 'text-success' ?>"><?= money($m['outstanding_balance']) ?></td></tr>
                            </table>
                        </div>
                    </div>
                </div></div>

                <!-- Status Timeline -->
                <?php if (!empty($statusHistory)): ?>
                <div class="card mt-3"><div class="card-header py-2"><small class="fw-bold">Status History</small></div><div class="card-body">
                    <div class="table-responsive"><table class="table table-sm">
                        <thead><tr><th>Date</th><th>From</th><th>To</th><th>Reason</th><th>By</th></tr></thead>
                        <tbody>
                        <?php foreach ($statusHistory as $sh): ?>
                        <tr>
                            <td><?= format_datetime($sh['changed_at']) ?></td>
                            <td><?= $sh['from_status'] ? status_badge($sh['from_status']) : '—' ?></td>
                            <td><?= status_badge($sh['to_status']) ?></td>
                            <td><?= e($sh['reason'] ?? '—') ?></td>
                            <td><?= e($sh['changed_by_name'] ?? '—') ?></td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table></div>
                </div></div>
                <?php endif; ?>
            </div>

            <!-- Family & Dependents -->
            <div class="tab-pane fade" id="t-family">
                <div class="card"><div class="card-header d-flex justify-content-between align-items-center py-2">
                    <small class="fw-bold">Dependents (<?= count($dependents) ?>)</small>
                    <?php if (auth_can('dependents.manage')): ?>
                    <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#depModal" id="btn-add-dep"><i class="fas fa-plus me-1"></i>Add</button>
                    <?php endif; ?>
                </div><div class="card-body">
                    <?php if (empty($dependents)): ?>
                    <p class="text-muted text-center py-3">No dependents</p>
                    <?php else: ?>
                    <div class="table-responsive"><table class="table table-sm">
                        <thead><tr><th>Name</th><th>Relationship</th><th>Gender</th><th>DOB</th><th>Status</th><th>Actions</th></tr></thead>
                        <tbody>
                        <?php foreach ($dependents as $dep): ?>
                        <tr>
                            <td><?= e($dep['full_name_en']) ?></td>
                            <td><?= e($dep['rel_type_en']) ?></td>
                            <td><?= ucfirst($dep['gender']) ?></td>
                            <td><?= format_date($dep['date_of_birth']) ?></td>
                            <td><?= status_badge($dep['status']) ?></td>
                            <td>
                                <?php if (auth_can('dependents.manage')): ?>
                                <button class="btn btn-sm btn-outline-warning btn-edit-dep" data-id="<?= $dep['id'] ?>"><i class="fas fa-edit"></i></button>
                                <button class="btn btn-sm btn-outline-danger btn-delete-dep" data-id="<?= $dep['id'] ?>"><i class="fas fa-trash"></i></button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table></div>
                    <?php endif; ?>
                </div></div>
            </div>

            <!-- Financial -->
            <?php if (auth_can('members.financial')): ?>
            <div class="tab-pane fade" id="t-financial">
                <div class="row g-3 mb-3">
                    <div class="col-md-3"><div class="card border-primary h-100"><div class="card-body text-center"><small class="text-muted">Total Invoiced</small><h5><?= money($balances['total_invoiced'] ?? 0) ?></h5></div></div></div>
                    <div class="col-md-3"><div class="card border-success h-100"><div class="card-body text-center"><small class="text-muted">Total Paid</small><h5><?= money($balances['total_paid'] ?? 0) ?></h5></div></div></div>
                    <div class="col-md-3"><div class="card border-danger h-100"><div class="card-body text-center"><small class="text-muted">Outstanding</small><h5 class="text-danger"><?= money($balances['outstanding_balance'] ?? 0) ?></h5></div></div></div>
                    <div class="col-md-3"><div class="card border-info h-100"><div class="card-body text-center"><small class="text-muted">Credit</small><h5 class="text-success"><?= money($balances['credit_balance'] ?? 0) ?></h5></div></div></div>
                </div>
                <div class="card"><div class="card-header py-2"><small class="fw-bold">Recent Invoices</small></div><div class="card-body">
                    <div class="table-responsive"><table class="table table-sm">
                        <thead><tr><th>Invoice #</th><th>Type</th><th>Date</th><th>Total</th><th>Paid</th><th>Balance</th><th>Status</th></tr></thead>
                        <tbody>
                        <?php foreach ($recentInvoices as $inv): ?>
                        <tr>
                            <td><?= e($inv['invoice_number']) ?></td><td><?= ucfirst(str_replace('_', ' ', $inv['invoice_type'])) ?></td>
                            <td><?= format_date($inv['invoice_date']) ?></td><td><?= money($inv['total_amount']) ?></td>
                            <td><?= money($inv['paid_amount']) ?></td><td><?= money($inv['balance_due']) ?></td><td><?= status_badge($inv['status']) ?></td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table></div>
                </div></div>
            </div>
            <?php endif; ?>

            <!-- Documents -->
            <div class="tab-pane fade" id="t-docs">
                <div class="card"><div class="card-header d-flex justify-content-between align-items-center py-2">
                    <small class="fw-bold">Documents (<?= count($documents) ?>)</small>
                    <?php if (auth_can('members.edit')): ?>
                    <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#docUploadModal"><i class="fas fa-upload me-1"></i>Upload</button>
                    <?php endif; ?>
                </div><div class="card-body">
                    <div class="table-responsive"><table class="table table-sm">
                        <thead><tr><th>Name</th><th>Type</th><th>Uploaded</th><th>Expiry</th><th>Verified</th><th>Actions</th></tr></thead>
                        <tbody>
                        <?php foreach ($documents as $doc): ?>
                        <tr>
                            <td><?= e($doc['document_name']) ?></td>
                            <td><?= e($doc['document_type']) ?></td>
                            <td><?= format_date($doc['uploaded_at']) ?></td>
                            <td><?= format_date($doc['expiry_date']) ?: '—' ?></td>
                            <td><?= $doc['is_verified'] ? '<i class="fas fa-check-circle text-success"></i>' : '<i class="fas fa-clock text-warning"></i>' ?></td>
                            <td>
                                <a href="/uploads/<?= e($doc['file_path']) ?>" class="btn btn-sm btn-outline-primary" target="_blank"><i class="fas fa-download"></i></a>
                                <?php if (auth_can('members.edit') && !$doc['is_verified']): ?>
                                <button class="btn btn-sm btn-outline-success btn-verify-doc" data-id="<?= $doc['id'] ?>"><i class="fas fa-check"></i></button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table></div>
                </div></div>
            </div>

            <!-- Subscriptions -->
            <div class="tab-pane fade" id="t-subs">
                <div class="card"><div class="card-body">
                    <div class="table-responsive"><table class="table table-sm">
                        <thead><tr><th>Period</th><th>Type</th><th>Start</th><th>End</th><th>Amount</th><th>Status</th></tr></thead>
                        <tbody>
                        <?php foreach ($subscriptions as $sub): ?>
                        <tr>
                            <td><?= e($sub['period_name_en'] ?? '—') ?></td><td><?= e($sub['sub_type_en'] ?? '—') ?></td>
                            <td><?= format_date($sub['start_date']) ?></td><td><?= format_date($sub['end_date']) ?></td>
                            <td><?= money($sub['net_amount']) ?></td><td><?= status_badge($sub['status']) ?></td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table></div>
                </div></div>
            </div>

            <!-- Notes -->
            <div class="tab-pane fade" id="t-notes">
                <div class="card"><div class="card-header d-flex justify-content-between align-items-center py-2">
                    <small class="fw-bold">Notes</small>
                    <?php if (auth_can('members.edit')): ?>
                    <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#noteModal"><i class="fas fa-plus me-1"></i>Add Note</button>
                    <?php endif; ?>
                </div><div class="card-body">
                    <?php foreach ($notes as $note): ?>
                    <div class="border rounded p-3 mb-2 <?= $note['is_pinned'] ? 'border-warning' : '' ?>">
                        <div class="d-flex justify-content-between">
                            <div><span class="badge bg-<?= $note['note_type'] === 'general' ? 'secondary' : ($note['note_type'] === 'financial' ? 'info' : 'warning') ?>"><?= ucfirst($note['note_type']) ?></span>
                            <?php if ($note['is_pinned']): ?><i class="fas fa-thumbtack text-warning ms-1"></i><?php endif; ?>
                            <?php if ($note['subject']): ?><strong class="ms-2"><?= e($note['subject']) ?></strong><?php endif; ?>
                            </div>
                            <small class="text-muted"><?= time_ago($note['created_at']) ?> by <?= e($note['author_name'] ?? '—') ?></small>
                        </div>
                        <p class="mb-0 mt-1"><?= nl2br(e($note['note_text'])) ?></p>
                    </div>
                    <?php endforeach; ?>
                    <?php if (empty($notes)): ?><p class="text-muted text-center">No notes yet</p><?php endif; ?>
                </div></div>
            </div>

            <!-- History -->
            <div class="tab-pane fade" id="t-history">
                <div class="card"><div class="card-header py-2"><small class="fw-bold">Recent Access</small></div><div class="card-body">
                    <div class="table-responsive"><table class="table table-sm">
                        <thead><tr><th>Time</th><th>Direction</th><th>Access Point</th><th>Granted</th></tr></thead>
                        <tbody>
                        <?php foreach ($accessLog as $al): ?>
                        <tr><td><?= format_datetime($al['access_time']) ?></td><td><?= ucfirst($al['direction']) ?></td><td><?= e($al['point_name'] ?? '—') ?></td><td><?= $al['granted'] ? '<i class="fas fa-check text-success"></i>' : '<i class="fas fa-times text-danger"></i>' ?></td></tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table></div>
                </div></div>
            </div>
        </div>
    </div>
</div>

<!-- Status Change Modal -->
<div class="modal fade" id="statusModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title">Change Status</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body">
        <form id="status-form">
            <?= csrf_field() ?>
            <div class="mb-3"><label class="form-label">New Status *</label>
                <select name="status" class="form-select" required>
                    <option value="">Select...</option>
                    <option value="active">Active</option><option value="suspended">Suspended</option>
                    <option value="terminated">Terminated</option><option value="deceased">Deceased</option>
                </select>
            </div>
            <div class="mb-3"><label class="form-label">Reason *</label><textarea name="reason" class="form-control" rows="3" required></textarea></div>
        </form>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" id="btn-save-status">Save</button>
    </div>
</div></div></div>

<!-- Dependent Modal -->
<div class="modal fade" id="depModal" tabindex="-1"><div class="modal-dialog modal-lg"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title" id="depModalTitle">Add Dependent</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body">
        <form id="dep-form">
            <?= csrf_field() ?>
            <input type="hidden" name="dep_id" id="dep-id" value="">
            <div class="row g-3">
                <div class="col-md-4"><label class="form-label">Relationship *</label><select name="relationship_type_id" class="form-select" required><option value="">—</option><?php foreach ($relTypes as $rt): ?><option value="<?= $rt['id'] ?>"><?= e(current_lang() === 'ar' ? $rt['name_ar'] : $rt['name_en']) ?></option><?php endforeach; ?></select><div class="invalid-feedback" data-field="relationship_type_id"></div></div>
                <div class="col-md-4"><label class="form-label">First Name (EN) *</label><input type="text" name="first_name_en" class="form-control" required><div class="invalid-feedback" data-field="first_name_en"></div></div>
                <div class="col-md-4"><label class="form-label">Last Name (EN) *</label><input type="text" name="last_name_en" class="form-control" required><div class="invalid-feedback" data-field="last_name_en"></div></div>
                <div class="col-md-4"><label class="form-label">Gender *</label><select name="gender" class="form-select" required><option value="male">Male</option><option value="female">Female</option></select></div>
                <div class="col-md-4"><label class="form-label">Date of Birth</label><input type="date" name="date_of_birth" class="form-control"></div>
                <div class="col-md-4"><label class="form-label">National ID</label><input type="text" name="national_id" class="form-control"></div>
                <div class="col-md-4"><label class="form-label">Phone</label><input type="text" name="phone" class="form-control"></div>
            </div>
        </form>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" id="btn-save-dep">Save</button>
    </div>
</div></div></div>

<!-- Note Modal -->
<div class="modal fade" id="noteModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title">Add Note</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body">
        <form id="note-form">
            <?= csrf_field() ?>
            <div class="mb-3"><label class="form-label">Type</label><select name="note_type" class="form-select"><option value="general">General</option><option value="financial">Financial</option><option value="disciplinary">Disciplinary</option><option value="medical">Medical</option><option value="internal">Internal</option></select></div>
            <div class="mb-3"><label class="form-label">Subject</label><input type="text" name="subject" class="form-control"></div>
            <div class="mb-3"><label class="form-label">Note *</label><textarea name="note_text" class="form-control" rows="4" required></textarea></div>
        </form>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" id="btn-save-note">Save</button>
    </div>
</div></div></div>

<!-- Doc Upload Modal -->
<div class="modal fade" id="docUploadModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title">Upload Document</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body">
        <form id="doc-form" enctype="multipart/form-data">
            <?= csrf_field() ?>
            <div class="mb-3"><label class="form-label">Document Name *</label><input type="text" name="document_name" class="form-control" required></div>
            <div class="mb-3"><label class="form-label">Type</label><select name="document_type" class="form-select"><option value="national_id">National ID</option><option value="passport">Passport</option><option value="photo">Photo</option><option value="birth_certificate">Birth Certificate</option><option value="other">Other</option></select></div>
            <div class="mb-3"><label class="form-label">Expiry Date</label><input type="date" name="expiry_date" class="form-control"></div>
            <div class="mb-3"><label class="form-label">File *</label><input type="file" name="document" class="form-control" required accept=".jpg,.jpeg,.png,.pdf,.doc,.docx"></div>
        </form>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" id="btn-upload-doc">Upload</button>
    </div>
</div></div></div>

<?php $__view->push('scripts') ?>
<script>
const memberId = <?= $m['id'] ?>;
const csrfToken = '<?= csrf_token() ?>';

// Status change
document.getElementById('btn-save-status')?.addEventListener('click', function() {
    const form = document.getElementById('status-form');
    const data = new FormData(form);
    $.post('/api/members/' + memberId + '/status', Object.fromEntries(data), function(r) {
        if (r.success) { FormHelper.showToast('success', r.message); setTimeout(() => location.reload(), 1000); }
        else { FormHelper.showToast('error', r.message); }
    });
});

// Add dependent
document.getElementById('btn-save-dep')?.addEventListener('click', function() {
    const form = document.getElementById('dep-form');
    const depId = document.getElementById('dep-id').value;
    const url = depId ? '/api/members/' + memberId + '/dependents/' + depId + '/update' : '/api/members/' + memberId + '/dependents/store';
    $.post(url, $(form).serialize(), function(r) {
        if (r.success) { FormHelper.showToast('success', r.message); setTimeout(() => location.reload(), 1000); }
        else { FormHelper.showToast('error', r.message || 'Error'); if (r.errors) FormHelper.showErrors(form, r.errors); }
    });
});

// Edit dependent
$(document).on('click', '.btn-edit-dep', function() {
    const id = $(this).data('id');
    $.get('/api/members/' + memberId + '/dependents/' + id, function(r) {
        if (r.success) {
            const d = r.data;
            document.getElementById('dep-id').value = d.id;
            document.getElementById('depModalTitle').textContent = 'Edit Dependent';
            const form = document.getElementById('dep-form');
            form.querySelector('[name=relationship_type_id]').value = d.relationship_type_id;
            form.querySelector('[name=first_name_en]').value = d.first_name_en;
            form.querySelector('[name=last_name_en]').value = d.last_name_en;
            form.querySelector('[name=gender]').value = d.gender;
            form.querySelector('[name=date_of_birth]').value = d.date_of_birth || '';
            form.querySelector('[name=national_id]').value = d.national_id || '';
            form.querySelector('[name=phone]').value = d.phone || '';
            new bootstrap.Modal(document.getElementById('depModal')).show();
        }
    });
});

// Delete dependent
$(document).on('click', '.btn-delete-dep', function() {
    const id = $(this).data('id');
    Swal.fire({ title: 'Remove dependent?', icon: 'warning', showCancelButton: true, confirmButtonColor: '#e53e3e', confirmButtonText: 'Yes, remove' }).then((result) => {
        if (result.isConfirmed) {
            $.post('/api/members/' + memberId + '/dependents/' + id + '/delete', {_token: csrfToken}, function(r) {
                if (r.success) { FormHelper.showToast('success', r.message); setTimeout(() => location.reload(), 800); }
            });
        }
    });
});

// Add note
document.getElementById('btn-save-note')?.addEventListener('click', function() {
    const form = document.getElementById('note-form');
    $.post('/api/members/' + memberId + '/notes', $(form).serialize(), function(r) {
        if (r.success) { FormHelper.showToast('success', r.message); setTimeout(() => location.reload(), 800); }
        else { FormHelper.showToast('error', r.message); }
    });
});

// Add tag
document.getElementById('btn-add-tag')?.addEventListener('click', function() {
    const input = document.getElementById('new-tag-input');
    if (!input.value.trim()) return;
    $.post('/api/members/' + memberId + '/tags', {_token: csrfToken, tag_name: input.value.trim()}, function(r) {
        if (r.success) { FormHelper.showToast('success', 'Tag added'); setTimeout(() => location.reload(), 500); }
        else { FormHelper.showToast('error', r.message); }
    });
});

// Remove tag
$(document).on('click', '.btn-remove-tag', function() {
    const id = $(this).data('id');
    $.post('/api/members/' + memberId + '/tags/' + id + '/delete', {_token: csrfToken}, function(r) {
        if (r.success) { location.reload(); }
    });
});

// Upload document
document.getElementById('btn-upload-doc')?.addEventListener('click', function() {
    const form = document.getElementById('doc-form');
    const fd = new FormData(form);
    $.ajax({ url: '/api/members/' + memberId + '/documents/upload', type: 'POST', data: fd, processData: false, contentType: false,
        success: function(r) { if (r.success) { FormHelper.showToast('success', r.message); setTimeout(() => location.reload(), 800); } else { FormHelper.showToast('error', r.message); } }
    });
});

// Verify document
$(document).on('click', '.btn-verify-doc', function() {
    const id = $(this).data('id');
    $.post('/api/members/' + memberId + '/documents/' + id + '/verify', {_token: csrfToken}, function(r) {
        if (r.success) { FormHelper.showToast('success', 'Verified'); setTimeout(() => location.reload(), 500); }
    });
});

// Reset dep modal on open
document.getElementById('btn-add-dep')?.addEventListener('click', function() {
    document.getElementById('dep-id').value = '';
    document.getElementById('depModalTitle').textContent = 'Add Dependent';
    document.getElementById('dep-form').reset();
});
</script>
<?php $__view->endPush() ?>