<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex align-items-center justify-content-between">
                <h5 class="card-title mb-0">
                    <i class="mdi mdi-email-edit-outline me-2 text-primary"></i>
                    Email Notification Settings
                </h5>
                <span class="badge bg-info">Manage department-wise email recipients</span>
            </div>
            <div class="card-body">
                <!-- <div class="alert alert-info mb-4">
                    <i class="mdi mdi-information-outline me-2"></i>
                    <strong>Note:</strong> These settings control which email address receives notifications when a form is submitted on the website. If left blank, the system will use the default email.
                </div> -->

                <div class="table-responsive">
                    <table class="table table-hover table-bordered dt-responsive nowrap dataTable" id="datatable-fixedheader">
                        <thead class="table-dark">
                            <tr>
                                <th style="width:5%">No.</th>
                                <th>Form Name</th>
                                <th>Department</th>
                                <th>From Email (Sender)</th>
                                <th>To Email(s) (Recipients)</th>
                                <th style="width:10%" class="text-center">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($settings)): ?>
                                <?php foreach ($settings as $i => $row): ?>
                                <tr>
                                    <td class="text-center"><?= $i + 1 ?></td>
                                    <td>
                                        <strong><?= htmlspecialchars($row->form_name) ?></strong>
                                        <!--<br>-->
                                        <!--<small class="text-muted"><?= htmlspecialchars($row->form_key) ?></small>-->
                                    </td>
                                    <td>
                                        <span class="badge bg-secondary"><?= htmlspecialchars($row->department) ?></span>
                                    </td>
                                    <td>
                                        <span class="text-primary"><?= htmlspecialchars($row->from_email) ?></span>
                                    </td>
                                    <td>
                                        <?php foreach (explode(',', $row->to_emails) as $email): ?>
                                            <span class="badge bg-success mb-1"><?= htmlspecialchars(trim($email)) ?></span><br>
                                        <?php endforeach; ?>
                                    </td>
                                    <td class="text-center">
                                        <button class="btn btn-sm btn-primary edit-btn"
                                            data-id="<?= $row->id ?>"
                                            data-form_name="<?= htmlspecialchars($row->form_name) ?>"
                                            data-department="<?= htmlspecialchars($row->department) ?>"
                                            data-from_email="<?= htmlspecialchars($row->from_email) ?>"
                                            data-to_emails="<?= htmlspecialchars($row->to_emails) ?>">
                                            <i class="mdi mdi-pencil"></i> 
                                        </button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6" class="text-center text-muted py-4">
                                        No settings found. Please run the SQL setup script first.
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header text-white">
                <h5 class="modal-title">
                    <i class="mdi mdi-email-edit-outline me-2"></i> Edit Email Notification Settings
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="editForm">
                    <input type="hidden" id="edit_id" name="id">

                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">Form Name <span class="text-danger">*</span></label>
                            <input type="text" name="form_name" id="edit_form_name" class="form-control" placeholder="e.g. Health Checkup" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">Department <span class="text-danger">*</span></label>
                            <input type="text" name="department" id="edit_department" class="form-control" placeholder="e.g. Front Office" required>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label fw-semibold">From Email (Sender)</label>
                            <input type="email" name="from_email" id="edit_from_email" class="form-control" placeholder="system@synergyhospital.co.in">
                            <small class="text-muted">This will appear as the sender in email. Leave default for system email.</small>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label fw-semibold">To Email(s) (Recipients) <span class="text-danger">*</span></label>
                            <textarea name="to_emails" id="edit_to_emails" class="form-control" rows="3" 
                                placeholder="frontoffice@synergyhospital.co.in&#10;For multiple emails, separate with comma: email1@domain.com,email2@domain.com" required></textarea>
                            <small class="text-muted">
                                <i class="mdi mdi-information-outline"></i>
                                Multiple emails: use comma <code>email1@domain.com,email2@domain.com</code>
                            </small>
                        </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="saveBtn">
                    <i class="mdi mdi-content-save me-1"></i> Save Settings
                </button>
            </div>
        </div>
    </div>
</div>

<script>


const BASE = "<?= base_url() ?>";

// Open edit modal and populate fields
document.querySelectorAll('.edit-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        document.getElementById('edit_id').value       = this.dataset.id;
        document.getElementById('edit_form_name').value = this.dataset.form_name;
        document.getElementById('edit_department').value = this.dataset.department;
        document.getElementById('edit_from_email').value = this.dataset.from_email;
        document.getElementById('edit_to_emails').value  = this.dataset.to_emails;
        new bootstrap.Modal(document.getElementById('editModal')).show();
    });
});

// Save settings via AJAX
document.getElementById('saveBtn').addEventListener('click', function() {
    const form = document.getElementById('editForm');
    if (!form.checkValidity()) { form.reportValidity(); return; }

    const btn = this;
    btn.disabled = true;
    btn.innerHTML = '<i class="mdi mdi-loading mdi-spin me-1"></i> Saving...';

    const fd = new FormData(form);

    fetch(BASE + 'email-notification-settings/update', {
        method: 'POST',
        body: fd
    })
    .then(r => r.json())
    .then(res => {
        if (res.status === 'success') {
            // Show success alert at top
            document.querySelector('.alert-success-msg').innerText = res.message;
            document.querySelector('.alert-success').style.display = 'flex';
            setTimeout(() => { location.reload(); }, 1200);
        } else {
            document.querySelector('.alert-danger-msg').innerText = res.message;
            document.querySelector('.alert-danger').style.display = 'flex';
        }
    })
    .catch(() => {
        document.querySelector('.alert-danger-msg').innerText = 'Network error. Please try again.';
        document.querySelector('.alert-danger').style.display = 'flex';
    })
    .finally(() => {
        btn.disabled = false;
        btn.innerHTML = '<i class="mdi mdi-content-save me-1"></i> Save Settings';
    });
});
</script>

<?php $this->load->view('includes/footer'); ?>
<script>
    $(".alert-dismissible").fadeOut(0);
</script>
</body>
</html>
