<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>
<div class="container-fluid">
    <div class="wrapper">
        <div class="content">
            <h2 class="text-center mt-4 mb-3">Emergency Contact Information</h2>
            <div class="table-responsive">
                <table id="emergencyTable" class="display table table-bordered table-striped align-middle">
                    <thead class="table-dark">
                        <tr>
                            <th>Parent Name</th>
                            <th>Students</th>
                            <th>Contact Name</th>
                            <th>Relation</th>
                            <th>Phone</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $modals = ''; ?>
                        <?php foreach ($groups as $group): ?>
                            <?php
                                // Build clickable student names (open Family Card)
                                $studentNames = array_map(function($s) {
                                    $sid = (int)($s['id'] ?? $s['student_id'] ?? 0);
                                    $label = esc(($s['firstname'] ?? '') . ' ' . ($s['lastname'] ?? ''));
                                    if ($sid > 0) {
                                        return '<a href="#" class="text-decoration-none" data-family-student-id="' . $sid . '">' . $label . '</a>';
                                    }
                                    return $label;
                                }, $group['students']);
                                $studentsCell = implode('<br>', $studentNames);
                            ?>
                            <?php foreach ($group['contacts'] as $contact): ?>
                                <tr>
                                    <td>
                                        <?php $pid = (int)($group['parent_id'] ?? 0); ?>
                                        <?php if ($pid): ?>
                                          <a href="#" class="text-decoration-none" data-family-guardian-id="<?= $pid ?>">
                                            <?= esc($group['parent_name']) ?>
                                          </a>
                                        <?php else: ?>
                                          <?= esc($group['parent_name']) ?>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= $studentsCell ?></td>
                                    <td><?= esc($contact['emergency_contact_name']) ?></td>
                                    <td><?= esc($contact['relation']) ?></td>
                                    <td>
                                        <?php
                                          $phone = trim((string)($contact['cellphone'] ?? ''));
                                          if ($phone === '' && !empty($group['parent_phones']) && is_array($group['parent_phones'])) {
                                              $phone = implode(' / ', array_map('esc', $group['parent_phones']));
                                          }
                                          echo $phone !== '' ? esc($phone) : 'N/A';
                                        ?>
                                    </td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal"
                                            data-bs-target="#editContactModal<?= (int)$contact['id'] ?>">
                                            Edit
                                        </button>
                                        <a href="<?= base_url('administrator/emergency_contact/delete/' . (int)$contact['id']) ?>"
                                           class="btn btn-sm btn-danger"
                                           onclick="return confirm('Are you sure?')">Delete</a>
                                    </td>
                                </tr>

                                <?php
                                $modalId = (int)$contact['id'];
                                $modals .= '
                                <div class="modal fade"
                                     id="editContactModal' . $modalId . '"
                                     tabindex="-1"
                                     aria-labelledby="editContactLabel' . $modalId . '"
                                     aria-hidden="true"
                                     data-bs-backdrop="static"
                                     data-bs-keyboard="false">
                                    <div class="modal-dialog" role="document">
                                        <form action="' . base_url('administrator/emergency_contact/update/' . $modalId) . '"
                                              method="post"
                                              class="modal-content">
                                            ' . csrf_field() . '
                                            <div class="modal-header">
                                                <h5 class="modal-title" id="editContactLabel' . $modalId . '">Edit Emergency Contact</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                            </div>
                                            <div class="modal-body">
                                                <div class="mb-3">
                                                    <label for="name_' . $modalId . '" class="form-label">Name</label>
                                                    <input type="text" class="form-control"
                                                           name="emergency_contact_name"
                                                           id="name_' . $modalId . '"
                                                           value="' . esc($contact['emergency_contact_name']) . '"
                                                           required>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="phone_' . $modalId . '" class="form-label">Phone</label>
                                                    <input type="text" class="form-control"
                                                           name="cellphone"
                                                           id="phone_' . $modalId . '"
                                                           value="' . esc($contact['cellphone']) . '"
                                                           required>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="relation_' . $modalId . '" class="form-label">Relation</label>
                                                    <input type="text" class="form-control"
                                                           name="relation"
                                                           id="relation_' . $modalId . '"
                                                           value="' . esc($contact['relation']) . '"
                                                           required>
                                                </div>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                <button type="submit" class="btn btn-primary">Update</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>';
                                ?>
                            <?php endforeach; ?>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- All modals rendered outside the table -->
    <?= $modals ?>
</div>
<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
    $(document).ready(function() {
        $('#emergencyTable').DataTable({
            pageLength: 100,
            lengthMenu: [5, 10, 25, 50, 100],
            columnDefs: [
                { orderable: false, targets: [1, 5] } // Students + Actions columns not sortable
            ]
        });
    });
</script>
<?= $this->endSection() ?>
