<?php echo view ('common/top_header_backdesk.php') ?>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/dataTables.bootstrap4.min.css"
    integrity="sha512-PT0RvABaDhDQugEbpNMwgYBCnGCiTZMh9yOzUsJHDgl/dMhD9yjHAwoumnUk3JydV3QTcIkNDuN40CJxik5+WQ=="
    crossorigin="anonymous" referrerpolicy="no-referrer" />
<style>
    select.form-select, select.form-control, .form-control {outline: 1px solid #67676b;}
    select.form-select {color: #67676b;}
    input[type="number"], input[type="date"], input[type="text"] {border-radius: 5px; padding: 5px 10px;}
    .error {color: red; text-align: right; width: 100%; padding-top: 15px; margin-bottom: 0px !important;}
    .form-group {margin-bottom: 20px;}
</style>
</head>

<?php $session = session(); ?>

<body>

    <div class="container-scroller">

        <!--Top navbar-->
        <?= view('common/top_navbar') ?>
        <!-- partial -->
        <div class="container-fluid page-body-wrapper">

            <!--sidenavbar starts-->
            <?= view('common/side_navbar') ?>
            <!--sidenavbar ends-->

            <div class="main-panel">
                <div class="content-wrapper">
                    <div class="card">
                        <form id="department_add_form" method="post" class="card-body" enctype="multipart/form-data" novalidate>
                            <h4 class="card-title">Add Department</h4>
                            <hr>

                            <div class="row">
                                <!-- Department Name -->
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="font-weight-bold">Department Name</label>
                                        <input type="text" id="department_name" name="department_name" class="form-control" required>
                                    </div>
                                </div>

                                <!-- Department Mobile No -->
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="font-weight-bold">Department Mobile No</label>
                                        <input type="number" id="department_mobile" name="department_mobile" class="form-control" required>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <!-- Department Email -->
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="font-weight-bold">Department Email</label>
                                        <input type="email" id="department_email" name="department_email" class="form-control" required>
                                    </div>
                                </div>

                                <!-- HOD Name -->
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="font-weight-bold">HOD Name</label>
                                        <input type="text" id="hod_name" name="hod_name" class="form-control" required>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <!-- HOD Designation -->
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="font-weight-bold">HOD Designation</label>
                                        <input type="text" id="hod_designation" name="hod_designation" class="form-control" required>
                                    </div>
                                </div>

                                <!-- HOD Photo -->
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="font-weight-bold">HOD Image</label>
                                        <input type="file" id="hod_photo" name="hod_photo" class="form-control" required>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <!-- Department Info -->
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="font-weight-bold">Department Info</label>
                                        <textarea id="department_info" name="department_info" class="form-control" rows="5" required></textarea>
                                    </div>
                                </div>
                                <!-- Department Vision -->
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="font-weight-bold">Department Vision</label>
                                        <textarea id="department_vision" name="department_vision" class="form-control" rows="5" required></textarea>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <!-- Courses -->
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="font-weight-bold">Courses</label>
                                        <select class="form-control" name="courses[]" id="courses" multiple required>
                                            <option value="">Select</option>
                                            <?php
                                            if (!empty($courses)) {
                                                foreach ($courses as $row) {
                                                    echo '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
                                                }
                                            }
                                            ?>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <!-- Infrastructure -->
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="font-weight-bold">Infrastructure</label>
                                        <textarea id="infrastructure" name="infrastructure" class="form-control" rows="5" required></textarea>
                                    </div>
                                </div>
                                <!-- Equipment -->
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="font-weight-bold">Equipment</label>
                                        <textarea id="equipment" name="equipment" class="form-control" rows="5" required></textarea>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <!-- Library Resources -->
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="font-weight-bold">Library Resources</label>
                                        <textarea id="library_resources" name="library_resources" class="form-control" rows="5" required></textarea>
                                    </div>
                                </div>
                            </div>

                            <button type="submit" name="author_add" class="btn btn-success btn-sm mt-4">
                                <i class="mdi mdi-table-row-plus-after"></i>&nbsp;&nbsp;Create
                            </button>
                        </form>
                    </div>
                    <!-- content-wrapper ends -->
                    <!-- partial:../../partials/_footer.html -->
                    <footer class="footer">
                        <div class="d-sm-flex justify-content-center justify-content-sm-between">
                            <span class="text-muted text-center text-sm-left d-block d-sm-inline-block">Copyright ©
                                <?= date('Y') . ' ' . COMPANY_FULL_NAME ?> . All rights reserved.</span>
                            <span class="float-none float-sm-right d-block mt-1 mt-sm-0 text-center">With gratitude from
                                <i class="mdi mdi-heart text-danger"></i><a href="<?= CREDIT_LINK ?>"
                                    target="_blank"><?= CREDIT_TITLE ?></a></span>
                        </div>
                    </footer>
                    <!-- partial -->
                </div>
                <!-- main-panel ends -->
            </div>
            <!-- page-body-wrapper ends -->
        </div>
        <!-- container-scroller -->
        <?php echo view('common/footer_backdesk.php') ?>
        <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
        <script>
            let editors = {};

            // Sync Trumbowyg editor content to textarea before form submission
            function syncEditorsToTextarea() {
                for (let id in editors) {
                    if (editors.hasOwnProperty(id)) {
                        const data = $('#' + id).trumbowyg('html');
                        document.getElementById(id).value = data;
                    }
                }
            }

            // Custom validation function for Trumbowyg and Select2
            function isValidForm() {
                let isValid = true;

                // Validate Select2 (Courses) - at least one selection
                const selectedCourses = $('#courses').val();
                if (!selectedCourses || selectedCourses.length === 0) {
                    toast('danger', 'Please select at least one course.');
                    $('#courses').select2('open');
                    isValid = false;
                    return isValid;
                }

                // Validate Trumbowyg fields
                for (let id in editors) {
                    if (editors.hasOwnProperty(id)) {
                        const content = $('#' + id).trumbowyg('html').trim();
                        if (content === '' || content === '<p></p>') {
                            toast('danger', `Please fill the ${id.replace(/_/g, ' ')} field.`);
                            $('#' + id).trumbowyg('focus');
                            isValid = false;
                            break;
                        }
                    }
                }

                // Validate standard HTML5 form fields
                if (!document.getElementById('department_add_form').checkValidity()) {
                    document.getElementById('department_add_form').reportValidity();
                    isValid = false;
                }

                return isValid;
            }

            $(document).ready(function () {
                // ✅ Initialize Select2
                $('#courses').select2({
                    placeholder: "Select courses",
                    allowClear: true
                });

                // ✅ Initialize Trumbowyg editors
                const fields = ['department_info', 'department_vision', 'infrastructure', 'equipment', 'library_resources'];
                fields.forEach(id => {
                    $('#' + id).trumbowyg({
                        btns: [['viewHTML'], ['formatting'], 'bold', 'italic', 'underline', 'link'],
                        autogrow: true,
                        resetCss: true,
                        semantic: false
                    });
                    editors[id] = true; // simple flag to mark editor is initialized
                });

                // ✅ Handle form submission
                $('#department_add_form').on('submit', function (e) {
                    e.preventDefault();

                    syncEditorsToTextarea();

                    if (!isValidForm()) return;

                    const csrfTokenName = '<?= csrf_token() ?>';
                    const csrfTokenValue = '<?= csrf_hash() ?>';
                    const jwtToken = localStorage.getItem('jwt_token');

                    const formData = new FormData(this);
                    formData.append(csrfTokenName, csrfTokenValue);

                    $.ajax({
                        url: '<?= base_url() ?>api/departments/add-department',
                        method: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        headers: {
                            'Authorization': 'Bearer ' + jwtToken
                        },
                        success: function (response) {
                            if (response.status) {
                                toast('success', response.message || 'Department created successfully!');
                                window.location.href = '<?= base_url() ?>backdesk/departments/index';
                            } else {
                                toast('danger', response.message || 'Something went wrong!');
                            }
                        },
                        error: function () {
                            toast('danger', 'Server error occurred.');
                        }
                    });
                });
            });
        </script>
</body>

</html>
