<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>
<div class="container-fluid">
    <div class="wrapper">
        <div class="content"></div>

        <h2 class="text-center mt-4 mb-3">Parent Contacts by Class</h2>
 <a href="<?= site_url('whatsapp/') ?>" class="btn btn-outline-secondary btn-sm">
    <i class="bi bi-people"></i> WhatsApp Group Links
  </a>
        <?php if (session()->getFlashdata('message')): ?>
            <div class="alert alert-success">
                <?= session()->getFlashdata('message') ?>
            </div>
        <?php endif; ?>
        <?php if (session()->getFlashdata('error')): ?>
            <div class="alert alert-danger">
                <?= session()->getFlashdata('error') ?>
            </div>
        <?php endif; ?>

        <?php if (!empty($classSections)): ?>
            <div id="classAccordion">
                <?php foreach ($classSections as $index => $classSection): ?>
                    <div class="card">
                        <div class="card-header" id="heading<?= $index ?>">
                            <h2 class="mb-0">
                                <button class="btn btn-link w-100 text-start" type="button"
                                    data-bs-toggle="collapse"
                                    data-bs-target="#collapse<?= $index ?>"
                                    aria-expanded="<?= $index === 0 ? 'true' : 'false' ?>"
                                    aria-controls="collapse<?= $index ?>">
                                    Grade : <?= esc($classSection['class_section_name']) ?>
                                </button>
                            </h2>
                        </div>

                        <div id="collapse<?= $index ?>" class="collapse <?= $index === 0 ? 'show' : '' ?>" aria-labelledby="heading<?= $index ?>" data-bs-parent="#classAccordion">
                            <div class="card-body">

                                <!-- <h5>Semester: <?= esc($classSection['semester'] ?? '') ?></h5> -->
                                <!-- <h5>School Year: <?= esc($classSection['school_year'] ?? '') ?></h5> -->
                                <!-- <p><?= esc($classSection['description'] ?? '') ?></p> -->

                                <?php if (!empty($classSection['parents'])): ?>
                                    <div class="table-responsive">
                                        <table id="parentsTable<?= $index ?>" class="display table table-striped table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Primary Parent</th>
                                                    <th>Phone</th>
                                                    <th>
                                                        In Group (Primary)
                                                        <div class="form-check d-inline-block ms-2">
                                                            <input class="form-check-input" type="checkbox" id="selectAllPrimary<?= $index ?>" title="Set all primary parents: checked=Yes, unchecked=No">
                                                            <label for="selectAllPrimary<?= $index ?>" class="form-check-label small">All</label>
                                                        </div>
                                                    </th>
                                                    <!--th>Email</th-->
                                                    <th>Second Parent</th>
                                                    <th>Phone</th>
                                                    <!--th>Email</th-->                                        
                                                    <th>
                                                        In Group (Second)
                                                        <div class="form-check d-inline-block ms-2">
                                                            <input class="form-check-input" type="checkbox" id="selectAllSecond<?= $index ?>" title="Set all second parents: checked=Yes, unchecked=No">
                                                            <label for="selectAllSecond<?= $index ?>" class="form-check-label small">All</label>
                                                        </div>
                                                    </th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($classSection['parents'] as $rIdx => $p): ?>
                                                    <?php $formId = 'mform-' . $index . '-' . $rIdx; ?>
                                                    <tr>
                                                        <td><?= esc($p['primary_name']) ?></td>
                                                        <td>
                                                            <?php if (!empty($p['primary_phone'])): ?>
                                                                <a href="tel:<?= esc(preg_replace('/\D+/', '', $p['primary_phone'])) ?>">
                                                                    <?= esc($p['primary_phone']) ?>
                                                                </a>
                                                            <?php else: ?>
                                                                <span class="text-muted">—</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td class="text-center">
                                                            <select name="primary_member" form="<?= $formId ?>" class="form-select form-select-sm mem-select" aria-label="Primary in group">
                                                                <?php $pm = $p['primary_member'] ?? null; ?>
                                                                <option value="" <?= ($pm === null || $pm === '') ? 'selected' : '' ?>>—</option>
                                                                <option value="1" <?= ((string)$pm === '1') ? 'selected' : '' ?>>Yes</option>
                                                                <option value="0" <?= ((string)$pm === '0') ? 'selected' : '' ?>>No</option>
                                                            </select>
                                                        </td>
                                                        <!--
                                                        <td>
                                                            <?php if (!empty($p['primary_email'])): ?>
                                                                <a href="mailto:<?= esc($p['primary_email']) ?>"><?= esc($p['primary_email']) ?></a>
                                                            <?php else: ?>
                                                                <span class="text-muted">—</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        -->
                                                        <td><?= esc($p['second_name']) ?></td>
                                                        <td>
                                                            <?php if (!empty($p['second_phone'])): ?>
                                                                <a href="tel:<?= esc(preg_replace('/\D+/', '', $p['second_phone'])) ?>">
                                                                    <?= esc($p['second_phone']) ?>
                                                                </a>
                                                            <?php else: ?>
                                                                <span class="text-muted">—</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <!--
                                                        <td>
                                                            <?php if (!empty($p['second_email'])): ?>
                                                                <a href="mailto:<?= esc($p['second_email']) ?>"><?= esc($p['second_email']) ?></a>
                                                            <?php else: ?>
                                                                <span class="text-muted">—</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        -->
                                                        
                                                        <td class="text-center">
                                                            <?php if (!empty($p['second_id'])): ?>
                                                                <?php $sm = $p['second_member'] ?? null; ?>
                                                                <select name="second_member" form="<?= $formId ?>" class="form-select form-select-sm mem-select" aria-label="Second in group">
                                                                    <option value="" <?= ($sm === null || $sm === '') ? 'selected' : '' ?>>—</option>
                                                                    <option value="1" <?= ((string)$sm === '1') ? 'selected' : '' ?>>Yes</option>
                                                                    <option value="0" <?= ((string)$sm === '0') ? 'selected' : '' ?>>No</option>
                                                                </select>
                                                            <?php else: ?>
                                                                <span class="text-muted">—</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td class="text-center">
                                                            <form id="<?= $formId ?>" method="post" action="<?= site_url('whatsapp/update-membership') ?>" class="d-inline wa-membership-form">
                                                                <?= csrf_field() ?>
                                                                <input type="hidden" name="class_section_id" value="<?= (int)($p['class_section_id'] ?? $classSection['class_section_id']) ?>">
                                                                <input type="hidden" name="school_year" value="<?= esc($classSection['school_year'] ?? '') ?>">
                                                                <input type="hidden" name="semester" value="<?= esc($classSection['semester'] ?? '') ?>">
                                                                <input type="hidden" name="primary_id" value="<?= (int)($p['primary_id'] ?? 0) ?>">
                                                                <input type="hidden" name="second_id" value="<?= (int)($p['second_id'] ?? 0) ?>">
                                                                <!--button type="submit" class="btn btn-sm btn-primary wa-save-btn">Save</button-->
                                                                <span class="ms-2 small wa-status" aria-live="polite"></span>
                                                            </form>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                <?php else: ?>
                                    <p>No parents found for this class section.</p>
                                <?php endif; ?>

                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <p>No class sections available.</p>
        <?php endif; ?>
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<style>
  /* Narrow In Group columns (header + cells) */
  th.col-in-group, td.col-in-group {
    width: 72px;
    max-width: 72px;
    white-space: nowrap;
  }
  th.col-in-group {
    vertical-align: middle;
  }
  th.col-in-group .form-check-label.small { font-size: 0.7rem; }
  th.col-in-group .form-check-input { width: .9rem; height: .9rem; }

  .mem-select.form-select.form-select-sm {
    display: inline-block; /* override Bootstrap block width */
    width: auto;           /* no full-width selects */
    min-width: 52px;       /* compact but readable */
    font-size: 0.75rem; /* smaller text */
    padding-left: 4px;
    padding-right: 12px;   /* smaller chevron space */
    line-height: 1;
    border: 1px solid #adb5bd;
    transition: background-color .12s ease, border-color .12s ease, color .12s ease, box-shadow .12s ease;
  }
  .mem-select.mem-yes {
    background: #157347;
    color: #fff;
    border-color: #0f5132;
    box-shadow: 0 0 0 1px rgba(21, 115, 71, .18); /* thinner highlight */
  }
  .mem-select.mem-no {
    background: #bb2d3b;
    color: #fff;
    border-color: #842029;
    box-shadow: 0 0 0 1px rgba(187, 45, 59, .18); /* thinner highlight */
  }
  .mem-select.mem-none {
    background: #fff;
    color: #212529;
    border-color: #adb5bd;
    box-shadow: none;
  }
</style>
<script>
    $(document).ready(function() {
        <?php if (!empty($classSections)): ?>
            <?php foreach ($classSections as $index => $section): ?>
                $('#parentsTable<?= $index ?>').DataTable({
                    paging: true,
                    lengthChange: true,
                    pageLength: 50,
                    info: true,
                    autoWidth: false,
                    language: {
                        info: "Showing _START_ to _END_ of _TOTAL_ entries (Page _PAGE_ of _PAGES_)",
                        infoEmpty: "No entries to show",
                        infoFiltered: "(filtered from _MAX_ total entries)",
                        lengthMenu: "Show _MENU_ entries per page"
                    },
                    columnDefs: [
                        { targets: [2,5], width: '72px', className: 'dt-head-center dt-body-center' }
                    ],
                    order: [
                        [0, 'asc']
                    ]
                });

                // Select-all toggles for this class section's table (set Yes/No on selects)
                $('#selectAllPrimary<?= $index ?>').on('change', function() {
                    const yesNo = $(this).is(':checked') ? '1' : '0';
                    $('#parentsTable<?= $index ?> tbody select[name="primary_member"]').val(yesNo).each(function(){
                        applyMemAppearance(this);
                        $(this).trigger('change'); // auto-save per row
                    });
                });
                $('#selectAllSecond<?= $index ?>').on('change', function() {
                    const yesNo = $(this).is(':checked') ? '1' : '0';
                    $('#parentsTable<?= $index ?> tbody select[name="second_member"]').val(yesNo).each(function(){
                        applyMemAppearance(this);
                        $(this).trigger('change'); // auto-save per row
                    });
                });

            <?php endforeach; ?>
        <?php endif; ?>

        // Apply colored appearance to selects
        function applyMemAppearance(el) {
            if (!el) return;
            el.classList.remove('mem-none','mem-yes','mem-no');
            const v = (el.value || '').toString();
            if (v === '1') el.classList.add('mem-yes');
            else if (v === '0') el.classList.add('mem-no');
            else el.classList.add('mem-none');
        }
        document.querySelectorAll('.mem-select').forEach(applyMemAppearance);
        $(document).on('change', '.mem-select', function(){
            applyMemAppearance(this);
            // Auto-save this row, similar to teacher attendance page
            const $tr = $(this).closest('tr');
            const $form = $tr.find('form.wa-membership-form');
            if ($form.length) {
                $form.trigger('submit');
            }
        });

        // Bind once: ensure values are submitted with the form (for controls using the form="id" attribute)
        if (!window._waMembershipBind) {
            window._waMembershipBind = true;

            // Ensure selected values are submitted even if controls sit outside the form cell
            $(document).on('submit', 'form[id^="mform-"]', function(e) {
                const $form = $(this);
                const $tr = $form.closest('tr');
                const pVal = ($tr.find('select[name="primary_member"]').val() || '').toString();
                const sVal = ($tr.find('select[name="second_member"]').val() || '').toString();
                // Remove any previous hidden overrides
                $form.find('input[type="hidden"][name="primary_member"]').remove();
                $form.find('input[type="hidden"][name="second_member"]').remove();
                // Include explicit values to avoid browser quirks with form="id"
                $form.append('<input type="hidden" name="primary_member" value="' + pVal + '">');
                $form.append('<input type="hidden" name="second_member" value="' + sVal + '">');

                // AJAX submit for immediate feedback
                e.preventDefault();
                const $btn = $form.find('.wa-save-btn');
                const $status = $form.find('.wa-status');
                $btn.prop('disabled', true).text('Saving...');
                $status.removeClass('text-danger text-success').text('');
                $.ajax({
                    url: $form.attr('action'),
                    method: 'POST',
                    data: $form.serialize(),
                    dataType: 'json'
                }).done(function(res){
                    if (res && res.status === 'ok') {
                        $status.addClass('text-success').text('Saved');
                    } else if (res && res.status === 'noop') {
                        $status.addClass('text-danger').text(res.message || 'Nothing to save');
                    } else {
                        $status.addClass('text-danger').text('Save failed');
                    }
                }).fail(function(){
                    $status.addClass('text-danger').text('Save failed');
                }).always(function(){
                    $btn.prop('disabled', false).text('Save');
                });
            });
        }
    });
</script>
<?= $this->endSection() ?>
