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

<?php
// Prepare initial editor content:
// Prefer $body_html if provided; else fall back to $body_text (escaped)
$initialEditorContent = (string)(
    isset($body_html) && $body_html !== ''
        ? $body_html
        : (isset($body_text) ? htmlspecialchars((string)$body_text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') : '')
);
?>

<div class="container my-4">
  <h2 class="text-center mb-3">Compose Attendance Email</h2>

  <?php if ($err = session()->getFlashdata('error')): ?>
    <div class="alert alert-danger"><?= esc($err) ?></div>
  <?php endif; ?>
  <?php if ($msg = session()->getFlashdata('message')): ?>
    <div class="alert alert-success"><?= esc($msg) ?></div>
  <?php endif; ?>

  <div class="card shadow-sm">
    <div class="card-header d-flex justify-content-between align-items-center">
      <div>
        <strong><?= esc($student_name ?? '') ?></strong>
        <span class="badge bg-secondary ms-2">
          <?= esc($code) ?><?= $variant ? ' • ' . esc($variant) : '' ?>
        </span>
      </div>
      <div>
        <span class="badge bg-primary">School Year: <?= esc($school_year ?? '') ?></span>
        <?php if (!empty($semester)): ?>
          <span class="badge bg-info text-dark ms-1">Semester: <?= esc($semester) ?></span>
        <?php endif; ?>
      </div>
    </div>

    <div class="card-body">
      <form method="post" action="<?= site_url('attendance/send-email-manual') ?>">
        <?= csrf_field() ?>
        <input type="hidden" name="student_id" value="<?= esc($student_id) ?>">
        <input type="hidden" name="code" value="<?= esc($code) ?>">
        <input type="hidden" name="variant" value="<?= esc($variant) ?>">
        <input type="hidden" name="incident_date" value="<?= esc($incident_date ?? local_date(utc_now(), 'Y-m-d')) ?>">

        <!-- This hidden field is what your controller validates (body_html) -->
        <input type="hidden" name="body_html" id="body_html" value="<?= htmlspecialchars($initialEditorContent, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?>">

        <div class="mb-3">
          <label class="form-label">To</label>
          <input type="email" name="to" class="form-control" value="<?= esc($parent_email) ?>" required>
          <div class="form-text">Primary parent email (you can change it here).</div>
        </div>

        <?php
          $secEmail = (string)($secondary_email ?? '');
          $secName  = (string)($secondary_name  ?? '');
        ?>
        <?php if ($secEmail !== ''): ?>
          <div class="alert alert-light border d-flex align-items-start">
            <div class="me-2"><i class="fas fa-copy"></i></div>
            <div>
              <div><strong>Second Parent (CC):</strong> <?= esc($secEmail) ?><?= $secName ? ' — ' . esc($secName) : '' ?></div>
            </div>
          </div>
        <?php endif; ?>

        <div class="mb-3">
          <label class="form-label">Subject</label>
          <input type="text" name="subject" class="form-control" value="<?= esc($subject) ?>" required>
        </div>

        <!-- Rich Text Editor -->
        <div class="mb-3">
          <label class="form-label">Body (Rich Text)</label>
          <textarea id="editor" class="form-control" rows="12"><?= $initialEditorContent ?></textarea>
          <div class="form-text">
            Use the toolbar to format your message. Links/images/tables are supported.
          </div>
          <noscript>
            <div class="alert alert-warning mt-2">
              JavaScript is disabled. The message will be sent as-is from the hidden <code>body_html</code> field.
            </div>
          </noscript>
        </div>

        <div class="d-flex gap-2">
          <a href="<?= site_url('attendance/violations') ?>" class="btn btn-outline-secondary">Cancel</a>
          <button type="submit" class="btn btn-primary">
            <i class="fas fa-paper-plane me-1"></i> Send Email
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

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

<?= $this->section('scripts') ?>
<!-- TinyMCE self-hosted -->
<script src="<?= base_url('assets/tinymce/tinymce.min.js') ?>"></script>
<script>
(function () {
  const form = document.querySelector('form[action$="attendance/send-email-manual"]');
  const hiddenHtml = document.getElementById('body_html');

  tinymce.init({
    selector: '#editor',

    // CRUCIAL for self-host:
    base_url: '<?= base_url('assets/tinymce') ?>',
    suffix: '.min',

    // Optional: explicitly mark GPL mode (suppresses license nags in some builds)
    license_key: 'gpl',

    height: 420,
    menubar: true,
    branding: false,
    promotion: false,

    // ONLY use OSS plugins here. Remove any premium/cloud ones (e.g., powerpaste, a11ychecker, tinycomments, spellchecker, linkchecker, checklist, premium table plugins).
    plugins: 'advlist autolink lists link image charmap preview anchor ' +
             'searchreplace visualblocks code fullscreen insertdatetime media table ' +
             'help wordcount emoticons codesample',
    toolbar:  'undo redo | blocks fontfamily fontsize | bold italic underline strikethrough forecolor backcolor | ' +
              'alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | ' +
              'link image media table | emoticons codesample | removeformat | preview code',

    convert_urls: false,
    paste_data_images: true,
    image_caption: true,
    content_style: 'body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif; font-size: 14px; }',

    setup(editor) {
      editor.on('keyup change undo redo SetContent', function () {
        if (hiddenHtml) hiddenHtml.value = editor.getContent({ format: 'html' });
      });
      if (form) {
        form.addEventListener('submit', function () {
          if (hiddenHtml) hiddenHtml.value = editor.getContent({ format: 'html' });
        });
      }
    }
  });
})();
</script>
<?= $this->endSection() ?>
