<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>

<div class="container-fluid">
  <div class="wrapper">
    <div class="content">
      <h2 class="mb-4">Generate Student Stickers</h2>
      <?= $this->include('partials/academic_filter') ?>

      <div class="d-flex gap-2 mb-3">
        <!-- Auto-count & Print All -->
        <button id="btnAutoCountPrintAll" type="button" class="btn btn-primary">
          <i class="bi bi-calculator"></i> Auto-count & Print All
        </button>

        <!-- Auto-count for selected class -->
        <button id="btnAutoCountClass" type="button" class="btn btn-outline-primary">
          <i class="bi bi-collection"></i> Auto-count Selected Class
        </button>
      </div>

      <!-- Hidden form used by "Auto-count" flow -->
      <form id="autoPrintForm" action="<?= base_url('stickers/generate') ?>" method="post" target="_blank" class="d-none">
        <?= csrf_field() ?>

        <!-- Carry the same layout fields as the visible form -->
        <input type="hidden" name="sticker_size" id="ap_size">
        <input type="hidden" name="sticker_width" id="ap_w">
        <input type="hidden" name="sticker_height" id="ap_h">
        <input type="hidden" name="stickers_per_page" id="ap_ppg">

        <input type="hidden" name="page_size" id="ap_page_size">
        <input type="hidden" name="orientation" id="ap_orientation">

        <input type="hidden" name="margin_left" id="ap_ml">
        <input type="hidden" name="margin_top" id="ap_mt">
        <input type="hidden" name="margin_right" id="ap_mr">
        <input type="hidden" name="margin_bottom" id="ap_mb">
        <input type="hidden" name="gap_x" id="ap_gx">
        <input type="hidden" name="gap_y" id="ap_gy">

        <!-- Decide print mode -->
        <input type="hidden" name="print_all" id="ap_print_all" value="1">
        <input type="hidden" name="class_id" id="ap_class_id" value="">
        <!-- copies[ID] are injected dynamically -->
      </form>

      <!-- Totals preview modal -->
      <div class="modal fade" id="previewTotalsModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-sm modal-dialog-centered">
          <div class="modal-content">
            <div class="modal-header">
              <h6 class="modal-title">Sticker Totals</h6>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
              <div id="previewTotalsBody" class="small"></div>
            </div>
            <div class="modal-footer">
              <button id="btnProceedPrint" type="button" class="btn btn-success">Proceed to Print</button>
            </div>
          </div>
        </div>
      </div>

      <!-- MAIN FORM (posts to generator) -->
      <form method="post" action="<?= base_url('stickers/generate') ?>" target="_blank" id="stickerForm">
        <?= csrf_field() ?>

        <!-- Sticker settings -->
        <div class="row g-3 mb-4">
          <div class="col-md-4">
            <label class="form-label" for="sticker_size">Sticker Size</label>
            <select name="sticker_size" id="sticker_size" class="form-select" required>
              <option value="60x30">Xsmall — 100×24.5 mm</option>
              <option value="60x30">Small — 60×30 mm</option>
              <option value="102x34" selected>Medium — 102×34 mm</option>
              <option value="90x45">Large — 90×45 mm</option>
              <option value="custom">Custom (enter mm below)</option>
            </select>
            <div class="row g-2 mt-2" id="customSizeRow" style="display:none;">
              <div class="col-6">
                <input type="number" min="1" step="0.1" class="form-control" id="sticker_width" name="sticker_width" placeholder="Width (mm)">
              </div>
              <div class="col-6">
                <input type="number" min="1" step="0.1" class="form-control" id="sticker_height" name="sticker_height" placeholder="Height (mm)">
              </div>
            </div>
            <div class="form-text">Choose your label’s physical size. Use “Custom” to type exact mm.</div>
          </div>

          <div class="col-md-4">
            <label class="form-label" for="stickers_per_page">Stickers per Page</label>
            <input type="number" min="1" max="200" value="20" class="form-control" id="stickers_per_page" name="stickers_per_page" required>
            <div class="form-text">Optional cap (e.g., Avery sheets). Grid still derives from size & margins.</div>
          </div>

          <div class="col-md-4">
            <label class="form-label" for="page_size">Paper / Orientation</label>
            <div class="input-group">
              <select name="page_size" id="page_size" class="form-select">
                <option value="A4" selected>A4</option>
                <option value="Letter">Letter</option>
              </select>
              <select name="orientation" id="orientation" class="form-select" style="max-width:140px;">
                <option value="P" selected>Portrait</option>
                <option value="L">Landscape</option>
              </select>
            </div>
            <div class="form-text">Paper size & print orientation.</div>
          </div>
        </div>

        <!-- Layout: margins & gaps -->
        <div class="row g-3 mb-4">
          <div class="col-md-6">
            <label class="form-label">Margins (mm)</label>
            <div class="row g-2">
              <div class="col-6 col-lg-3">
                <input type="number" min="0" step="0.1" class="form-control" id="margin_left" name="margin_left" value="3" placeholder="Left">
                <div class="form-text">Left</div>
              </div>
              <div class="col-6 col-lg-3">
                <input type="number" min="0" step="0.1" class="form-control" id="margin_top" name="margin_top" value="12" placeholder="Top">
                <div class="form-text">Top</div>
              </div>
              <div class="col-6 col-lg-3">
                <input type="number" min="0" step="0.1" class="form-control" id="margin_right" name="margin_right" value="3" placeholder="Right">
                <div class="form-text">Right</div>
              </div>
              <div class="col-6 col-lg-3">
                <input type="number" min="0" step="0.1" class="form-control" id="margin_bottom" name="margin_bottom" value="12" placeholder="Bottom">
                <div class="form-text">Bottom</div>
              </div>
            </div>
          </div>

          <div class="col-md-6">
            <label class="form-label">Gaps Between Stickers (mm)</label>
            <div class="row g-2">
              <div class="col-6">
                <input type="number" min="0" step="0.1" class="form-control" id="gap_x" name="gap_x" value="3" placeholder="Horizontal gap">
                <div class="form-text">Horizontal (X)</div>
              </div>
              <div class="col-6">
                <input type="number" min="0" step="0.1" class="form-control" id="gap_y" name="gap_y" value="3" placeholder="Vertical gap">
                <div class="form-text">Vertical (Y)</div>
              </div>
            </div>
          </div>
        </div>

        <!-- Selectors -->
        <div class="row g-3 align-items-end">
          <!-- Class picker -->
          <div class="col-md-6">
            <label class="form-label" for="class_id">Select a Class</label>
            <select name="class_id" id="class_id" class="form-select">
              <option value="">-- Select Class --</option>
              <?php foreach ($classes as $class): ?>
                <option value="<?= esc($class['class_section_id']) ?>">
                  <?= esc($class['class_section_name']) ?>
                </option>
              <?php endforeach; ?>
            </select>
            <div class="form-text">Pick a class to load its students below.</div>
          </div>

          <!-- Single student picker -->
          <div class="col-md-3">
            <label class="form-label" for="student_id">Or Select a Specific Student (optional)</label>
            <select name="student_id" id="student_id" class="form-select">
              <option value="">-- None (generate by class) --</option>
              <?php foreach ($students as $student): ?>
                <option value="<?= esc($student['id']) ?>">
                  <?= esc($student['firstname'] . ' ' . $student['lastname']) ?>
                </option>
              <?php endforeach; ?>
            </select>
            <div class="form-text">Leave blank to generate stickers for the whole class.</div>
          </div>

          <!-- Copies input -->
          <div class="col-md-3">
            <label class="form-label" for="single_copies">Copies (if a student is selected)</label>
            <input type="number" min="0" max="100" value="1" class="form-control" name="single_copies" id="single_copies">
            <div class="form-text">Set how many stickers to print.</div>
          </div>
        </div>

        <div class="mb-4 d-flex gap-2 align-items-center">
          <button type="submit" class="btn btn-primary">Generate Stickers</button>

          <!-- Optional helper to fill all quantities in the class table -->
          <div class="input-group" style="max-width:260px;">
            <span class="input-group-text">Set all Qty</span>
            <input type="number" min="0" max="100" value="1" id="fillAllQty" class="form-control">
            <button type="button" class="btn btn-outline-secondary" id="btnFillAll">Apply</button>
          </div>

          <small class="text-muted ms-2" id="settingsSummary"></small>
        </div>

        <!-- Live preview of students in the selected class -->
        <div id="student-list-section" class="mt-2" style="display:none;">
          <div class="table-responsive">
            <table class="table table-bordered table-striped mb-0">
              <thead>
                <tr>
                  <th style="width:50%;">Name</th>
                  <th>Grade</th>
                  <th>Gender</th>
                  <th style="width:120px;">Qty</th>
                </tr>
              </thead>
              <tbody id="student-list-body">
                <!-- Filled dynamically -->
              </tbody>
            </table>
          </div>
        </div>
      </form>

      <!-- ===== Optional: Rendered Sheet (only if $stickers provided) ===== -->
      <?php if (!empty($stickers) && is_array($stickers)): ?>
        <style>
          /* Page + print */
          @page { size: A4; margin: 10mm; } /* Adjust as needed or map to page_size/orientation server-side */

          :root{
            --gap: 4mm;            /* space between stickers */
            --h: 34mm;             /* default sticker height (fits 102x34 nicely) */
          }

          /* PDF-safe baseline (2-up) */
          .sheet{ font-size:0; } /* collapse inline-block whitespace */
          .sticker{
            display:inline-block;
            vertical-align:top;
            width: calc(50% - var(--gap)/2); /* always two columns */
            height: var(--h);
            box-sizing:border-box;
            padding:4mm;
            margin:0 var(--gap) var(--gap) 0; /* right & bottom spacing */
            outline:0.2mm dashed #ccc;       /* cut guide (optional) */
            page-break-inside:avoid;
            break-inside: avoid-page;
          }
          .sticker:nth-child(2n){ margin-right:0; }

          .sticker h4{ margin:0 0 2mm; font-size:14pt; }
          .sticker p{ margin:0; font-size:11pt; }

          /* Screen upgrade: grid when available (not used by PDF engines) */
          @media screen {
            .sheet{
              display:grid;
              grid-template-columns: repeat(2, 1fr);
              gap: var(--gap);
              font-size: initial;
            }
            .sticker{
              display:block;
              width:auto;
              margin:0;
            }
          }
        </style>

        <div class="sheet mt-4">
          <?php foreach ($stickers as $s):
            $title = $s['title'] ?? '';
            $line1 = $s['line1'] ?? '';
            $line2 = $s['line2'] ?? '';
          ?>
            <div class="sticker">
              <?php if ($title !== ''): ?><h4><?= esc($title) ?></h4><?php endif; ?>
              <?php if ($line1 !== ''): ?><p><?= esc($line1) ?></p><?php endif; ?>
              <?php if ($line2 !== ''): ?><p><?= esc($line2) ?></p><?php endif; ?>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
      <!-- ===== End optional sheet ===== -->

    </div>
  </div>
</div>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
  (function() {
    const classSelect = document.getElementById('class_id');
    const studentSelect = document.getElementById('student_id');
    const listSection = document.getElementById('student-list-section');
    const listBody = document.getElementById('student-list-body');

    const sizeSelect = document.getElementById('sticker_size');
    const customSizeRow = document.getElementById('customSizeRow');
    const inW = document.getElementById('sticker_width');
    const inH = document.getElementById('sticker_height');

    const perPageInput = document.getElementById('stickers_per_page');
    const pageSize = document.getElementById('page_size');
    const orientation = document.getElementById('orientation');

    const mL = document.getElementById('margin_left');
    const mT = document.getElementById('margin_top');
    const mR = document.getElementById('margin_right');
    const mB = document.getElementById('margin_bottom');
    const gX = document.getElementById('gap_x');
    const gY = document.getElementById('gap_y');

    const settingsSummary = document.getElementById('settingsSummary');

    // Keep student vs class mutually exclusive
    classSelect.addEventListener('change', () => {
      if (classSelect.value) {
        studentSelect.value = '';
      }
    });
    studentSelect.addEventListener('change', () => {
      if (studentSelect.value) {
        classSelect.value = '';
        listSection.style.display = 'none';
        listBody.innerHTML = '';
        updateSettingsSummary();
      }
    });

    // Custom size toggling
    function toggleCustomSize() {
      const isCustom = sizeSelect.value === 'custom';
      customSizeRow.style.display = isCustom ? '' : 'none';
      if (!isCustom) {
        inW.value = '';
        inH.value = '';
      }
    }
    sizeSelect.addEventListener('change', () => { toggleCustomSize(); updateSettingsSummary(); });
    toggleCustomSize();

    function updateSettingsSummary() {
      const sizeText = (sizeSelect.value === 'custom' && inW.value && inH.value)
        ? `Custom ${inW.value}×${inH.value} mm`
        : sizeSelect.options[sizeSelect.selectedIndex].textContent;
      const per = `${perPageInput.value} per page`;
      const paper = `${pageSize.value} ${orientation.value === 'P' ? 'Portrait' : 'Landscape'}`;
      const margins = `margins L:${mL.value} T:${mT.value} R:${mR.value} B:${mB.value} mm`;
      const gaps = `gaps X:${gX.value} Y:${gY.value} mm`;
      settingsSummary.textContent = `Layout: ${sizeText}, ${per}, ${paper}, ${margins}, ${gaps}`;
    }
    [perPageInput, pageSize, orientation, mL, mT, mR, mB, gX, gY].forEach(el => {
      el.addEventListener('input', updateSettingsSummary);
      el.addEventListener('change', updateSettingsSummary);
    });
    updateSettingsSummary();

    // Load students for class
    classSelect.addEventListener('change', function() {
      const classId = this.value;

      listBody.innerHTML = '';
      listSection.style.display = 'none';

      if (!classId) return;

      fetch('<?= base_url('api/students/by_class') ?>/' + encodeURIComponent(classId))
        .then(res => res.json())
        .then(data => {
          if (!Array.isArray(data) || data.length === 0) {
            listSection.style.display = 'block';
            listBody.innerHTML = '<tr><td colspan="4" class="text-center text-muted">No students found for this class.</td></tr>';
            updateSettingsSummary();
            return;
          }

          const fragRows = document.createDocumentFragment();
          data.forEach(stu => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
              <td>${escapeHtml(stu.firstname)} ${escapeHtml(stu.lastname)}</td>
              <td>${stu.registration_grade ?? ''}</td>
              <td>${stu.gender ?? ''}</td>
              <td>
                <input type="number"
                       class="form-control form-control-sm"
                       name="copies[${stu.id}]"
                       min="0" max="100" value="1"
                       aria-label="Quantity for ${escapeHtml(stu.firstname)} ${escapeHtml(stu.lastname)}">
              </td>
            `;
            fragRows.appendChild(tr);
          });

          listBody.appendChild(fragRows);
          listSection.style.display = 'block';
          updateSettingsSummary();
        })
        .catch(() => {
          listSection.style.display = 'block';
          listBody.innerHTML = '<tr><td colspan="4" class="text-center text-danger">Failed to load students. Please try again.</td></tr>';
        });
    });

    // "Set all Qty" helper
    document.getElementById('btnFillAll').addEventListener('click', () => {
      const v = parseInt(document.getElementById('fillAllQty').value || '1', 10);
      listBody.querySelectorAll('input[name^="copies["]').forEach(inp => {
        inp.value = Math.max(0, Math.min(100, v));
      });
    });

    function escapeHtml(s) {
      return String(s)
        .replaceAll('&', '&amp;')
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;')
        .replaceAll('"', '&quot;')
        .replaceAll("'", '&#039;');
    }
  })();
</script>

<!-- Auto-count scripting -->
<script>
  (() => {
    const btnAll = document.getElementById('btnAutoCountPrintAll');
    const btnClass = document.getElementById('btnAutoCountClass');
    const form = document.getElementById('autoPrintForm');

    // Hidden fields in auto form
    const apSize = document.getElementById('ap_size');
    const apW = document.getElementById('ap_w');
    const apH = document.getElementById('ap_h');
    const apPPG = document.getElementById('ap_ppg');
    const apAll = document.getElementById('ap_print_all');
    const apClass = document.getElementById('ap_class_id');

    const apPage = document.getElementById('ap_page_size');
    const apOrient = document.getElementById('ap_orientation');
    const apML = document.getElementById('ap_ml');
    const apMT = document.getElementById('ap_mt');
    const apMR = document.getElementById('ap_mr');
    const apMB = document.getElementById('ap_mb');
    const apGX = document.getElementById('ap_gx');
    const apGY = document.getElementById('ap_gy');

    // Visible inputs to mirror
    const inSize = document.getElementById('sticker_size');
    const inW = document.getElementById('sticker_width');
    const inH = document.getElementById('sticker_height');
    const inPPG = document.getElementById('stickers_per_page');
    const selClass = document.getElementById('class_id');

    const inPage = document.getElementById('page_size');
    const inOrient = document.getElementById('orientation');
    const inML = document.getElementById('margin_left');
    const inMT = document.getElementById('margin_top');
    const inMR = document.getElementById('margin_right');
    const inMB = document.getElementById('margin_bottom');
    const inGX = document.getElementById('gap_x');
    const inGY = document.getElementById('gap_y');

    const totalsModal = new bootstrap.Modal(document.getElementById('previewTotalsModal'));
    const totalsBody = document.getElementById('previewTotalsBody');
    const btnProceed = document.getElementById('btnProceedPrint');

    async function fetchCounts(classId = null) {
      const url = new URL('<?= base_url('stickers/preview') ?>', window.location.origin);
      if (classId) url.searchParams.set('class_id', classId);

      const res = await fetch(url.toString(), {
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
      });
      if (!res.ok) throw new Error('Preview failed: ' + res.status);
      const json = await res.json();
      if (json.status !== 'ok') throw new Error('Preview failed: bad status');
      return json.data; // { students:[{student_id, primary_count}], totals:{stickers, students} }
    }

    function carryLayoutToHidden() {
      // Size / custom size
      apSize.value = inSize ? inSize.value : '';
      apW.value = (inSize.value === 'custom' && inW.value) ? inW.value : '';
      apH.value = (inSize.value === 'custom' && inH.value) ? inH.value : '';

      // Cap per page
      apPPG.value = inPPG ? (inPPG.value || '') : '';

      // Paper & orientation
      apPage.value = inPage ? inPage.value : 'A4';
      apOrient.value = inOrient ? inOrient.value : 'P';

      // Margins & gaps
      apML.value = inML ? inML.value : '6';
      apMT.value = inMT ? inMT.value : '6';
      apMR.value = inMR ? inMR.value : apML.value;
      apMB.value = inMB ? inMB.value : '10';
      apGX.value = inGX ? inGX.value : '0';
      apGY.value = inGY ? inGY.value : '0';
    }

    function fillHiddenCopies(students) {
      // Clean previous copies
      [...form.querySelectorAll('input[name^="copies["]')].forEach(n => n.remove());

      // Use primary_count only
      for (const s of students) {
        const copies = Number(s.primary_count) || 0;
        if (copies <= 0) continue;
        const inp = document.createElement('input');
        inp.type = 'hidden';
        inp.name = `copies[${s.student_id}]`;
        inp.value = String(copies);
        form.appendChild(inp);
      }
    }

    function showTotals(data) {
      let totalStickers = data?.totals?.stickers;
      if (typeof totalStickers !== 'number') {
        totalStickers = (data?.students ?? []).reduce(
          (sum, s) => sum + (Number(s.primary_count) || 0), 0
        );
      }
      const ns = data?.totals?.students ?? (data?.students?.length ?? 0);

      totalsBody.innerHTML =
        `<div><strong>Students:</strong> ${ns}</div>` +
        `<div><strong>Total stickers:</strong> ${totalStickers}</div>`;

      totalsModal.show();
    }

    // Print All
    btnAll?.addEventListener('click', async () => {
      btnAll.disabled = true;
      try {
        const data = await fetchCounts(null); // all students
        showTotals(data);
        fillHiddenCopies(data.students);
        carryLayoutToHidden();
        apClass.value = '';
        apAll.value = '1';
      } catch (e) {
        alert(e.message || e);
      } finally {
        btnAll.disabled = false;
      }
    });

    // Print Selected Class
    btnClass?.addEventListener('click', async () => {
      const classId = selClass && selClass.value ? Number(selClass.value) : 0;
      if (!classId) {
        alert('Please select a class first.');
        return;
      }

      btnClass.disabled = true;
      try {
        const data = await fetchCounts(classId);
        showTotals(data);
        fillHiddenCopies(data.students);
        carryLayoutToHidden();
        apClass.value = String(classId);
        apAll.value = '0';
      } catch (e) {
        alert(e.message || e);
      } finally {
        btnClass.disabled = false;
      }
    });

    // Proceed to print (submits hidden form; opens in new tab)
    btnProceed?.addEventListener('click', () => {
      totalsModal.hide();
      form.submit();
    });
  })();
</script>
<?= $this->endSection() ?>
