@extends('admin.layouts.main-layout')

<?php $title = 'Add/Update Assignment Files'; ?>

@section('title', $title)

@section('content')
    <!-- Content wrapper -->
    <div class="content-wrapper">
        <!-- Content -->
        <div class="container-xxl flex-grow-1 container-p-y">
            <form action="{{ route('manage.assignment.files', ['assignment' => $assignmentId]) }}" method="POST"
                enctype="multipart/form-data">
                @csrf
                <!-- Hoverable Table rows -->
                <h5 class="card-header"><?= $title ?><span class="float-end"><a href="{{ route('manage.assignments') }}"
                            class="btn btn-icon rounded-pill btn-outline-secondary float-end"><i class='bx bx-left-arrow-alt'
                                style="font-size: 1.7rem;"></i></a></span></h5>
                <div class="row">
                    <div class="col-12">
                        @if (session('success'))
                            <div class="alert alert-success alert-dismissible" role="alert">
                                {{ session('success') }}
                                <button type="button" class="btn-close" data-bs-dismiss="alert"
                                    aria-label="Close"></button>
                            </div>
                        @elseif (session('error'))
                            <div class="alert alert-danger alert-dismissible" role="alert">
                                {{ session('error') }}
                                <button type="button" class="btn-close" data-bs-dismiss="alert"
                                    aria-label="Close"></button>
                            </div>
                        @endif
                        <div class="row">
                            <div class="col-12">
                                <div class="card mb-3">
                                    <h5 class="card-header">
                                        {{ $assignment->assignment_subject_name }}<br />
                                        <small>{{ ' (Code: ' . $assignment->assignment_code . ')' }}</small>
                                    </h5>
                                    <div class="card-body">
                                        <div id="assignment-files"></div>
                                        <span class="float-end"><button type="button" id="add-file-row"
                                                class="btn rounded-pill btn-icon btn-primary float-end"
                                                style="font-size: 1.7em;">+</button></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="demo-inline-spacing">
                            <input type="submit" value="Update Files Content" class="btn btn-primary" />
                            <a href="{{ route('manage.assignments') }}" class="btn btn-outline-secondary">Back</a>
                        </div>
                    </div>
                </div>
                <!--/ Hoverable Table rows -->
            </form>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {

            let assignmentFile = 0;

            const fileTypes = @json($types);
            const languages = @json($languages);
            const sessions = @json($sessions);

            function addAssignmentFileRow(item = {}) {

                const row = document.createElement('div');
                row.className = 'row mb-3 align-items-end';

                // Hidden ID
                const idInput = document.createElement('input');
                idInput.type = 'hidden';
                idInput.name = 'rule_ids[]';
                idInput.value = item.rule_id || '';
                row.appendChild(idInput);

                /* ---------- FILE TYPE ---------- */
                const colType = document.createElement('div');
                colType.className = 'col-md-2';

                const typeSelect = document.createElement('select');
                typeSelect.className = 'form-select';
                typeSelect.name = 'file_types[]';
                typeSelect.required = true;

                let typeOptions = `<option value="">-- Select File Type --</option>`;
                fileTypes.forEach(t => {
                    const selected = item.file_type_id == t.id ? 'selected' : '';
                    typeOptions += `<option value="${t.encrypted_id}" ${selected}>${t.type_name}</option>`;
                });

                typeSelect.innerHTML = typeOptions;
                colType.appendChild(typeSelect);

                /* ---------- LANGUAGE ---------- */
                const colLang = document.createElement('div');
                colLang.className = 'col-md-2';

                const langSelect = document.createElement('select');
                langSelect.className = 'form-select';
                langSelect.name = 'file_languages[]';
                langSelect.required = true;

                let langOptions = `<option value="">-- Select Language --</option>`;
                languages.forEach(l => {
                    const selected = item.language_id == l.id ? 'selected' : '';
                    langOptions +=
                        `<option value="${l.encrypted_id}" ${selected}>${l.language_name}</option>`;
                });

                langSelect.innerHTML = langOptions;
                colLang.appendChild(langSelect);

                /* ---------- SESSION ---------- */
                const colSess = document.createElement('div');
                colSess.className = 'col-md-2';

                const sessSelect = document.createElement('select');
                sessSelect.className = 'form-select';
                sessSelect.name = 'file_sessions[]';
                sessSelect.required = true;

                let sessOptions = `<option value="">-- Select Session --</option>`;
                sessions.forEach(s => {
                    const selected = item.session_id == s.id ? 'selected' : '';
                    sessOptions +=
                        `<option value="${s.encrypted_id}" ${selected}>${s.session_name}</option>`;
                });

                sessSelect.innerHTML = sessOptions;
                colSess.appendChild(sessSelect);

                /* ---------- FILE INPUT ---------- */
                const colFile = document.createElement('div');
                colFile.className = 'col-md-3';

                if (item.file_url && item.file_name) {
                    const fileLabel = document.createElement('div');
                    fileLabel.className = 'mb-1';

                    fileLabel.innerHTML = `
                        <a href="${item.file_url}" target="_blank" class="text-primary fw-semibold">
                            <i class="bx bx-file"></i> ${item.file_name}
                        </a>
                    `;

                    colFile.appendChild(fileLabel);
                }

                const fileInput = document.createElement('input');
                fileInput.type = 'file';
                fileInput.className = 'form-control';
                fileInput.name = 'files[]';
                fileInput.accept = 'application/pdf';

                if (!item.rule_id) {
                    fileInput.required = true;
                }

                colFile.appendChild(fileInput);

                /* ---------- PASSWORD PROTECTION TOGGLE ---------- */
                // const colProtect = document.createElement('div');
                // colProtect.className = 'col-md-2';

                // const protectWrapper = document.createElement('div');
                // protectWrapper.className = 'form-check';

                // const protectCheckbox = document.createElement('input');
                // protectCheckbox.type = 'checkbox';
                // protectCheckbox.className = 'form-check-input';
                // protectCheckbox.name = 'is_protected[]';
                // protectCheckbox.value = '1';
                // protectCheckbox.checked = item.is_protected == 1;

                // const protectLabel = document.createElement('label');
                // protectLabel.className = 'form-check-label';
                // protectLabel.innerText = 'Password Protect';

                // protectWrapper.appendChild(protectCheckbox);
                // protectWrapper.appendChild(protectLabel);
                // colProtect.appendChild(protectWrapper);

                /* ---------- PRICE FIELD ---------- */
                const colPrice = document.createElement('div');
                colPrice.className = 'col-md-2';

                const priceInput = document.createElement('input');
                priceInput.type = 'number';
                priceInput.step = '0.01';
                priceInput.min = '0';
                priceInput.className = 'form-control';
                priceInput.name = 'file_prices[]';
                priceInput.placeholder = 'Enter Price';
                priceInput.value = item.price || '';
                priceInput.required = true;

                colPrice.appendChild(priceInput);

                /* ---------- PASSWORD FIELD ---------- */
                // const colPassword = document.createElement('div');
                // colPassword.className = 'col-md-3';

                // const passwordInput = document.createElement('input');
                // passwordInput.type = 'text';
                // passwordInput.className = 'form-control';
                // passwordInput.name = 'file_passwords[]';
                // passwordInput.placeholder = 'Enter Password';
                // passwordInput.value = item.file_password || '';
                // passwordInput.required = true;

                // // if (item.is_protected == 1) {
                // //     passwordInput.required = true;
                // //     colPassword.style.display = 'block';
                // // } else {
                // //     colPassword.style.display = 'none';
                // // }

                // colPassword.appendChild(passwordInput);

                // protectCheckbox.addEventListener('change', function() {
                //     if (this.checked) {
                //         colPassword.style.display = 'block';
                //         passwordInput.required = true;
                //     } else {
                //         colPassword.style.display = 'none';
                //         passwordInput.required = false;
                //         passwordInput.value = '';
                //     }
                // });

                /* ---------- DOWNLOAD BUTTON ---------- */
                // const colDownload = document.createElement('div');
                // colDownload.className = 'col-md-1';

                // if (item.file_url) {
                //     const downloadBtn = document.createElement('a');
                //     downloadBtn.href = item.file_url;
                //     downloadBtn.target = '_blank';
                //     downloadBtn.className = 'btn btn-outline-success w-100';
                //     downloadBtn.innerHTML = `<i class="bx bx-download"></i>`;
                //     colDownload.appendChild(downloadBtn);
                // }

                /* ---------- REMOVE BUTTON ---------- */
                const colRemove = document.createElement('div');
                colRemove.className = 'col-md-1 text-end';

                const removeBtn = document.createElement('button');
                removeBtn.type = 'button';
                removeBtn.className = 'btn btn-danger btn-icon rounded-pill';
                removeBtn.innerHTML = `<i class="bx bx-trash"></i>`;

                removeBtn.onclick = function() {
                    if (item.rule_id) {
                        $.ajax({
                            url: "{{ route('delete.assignment.file') }}",
                            method: "POST",
                            data: {
                                rule_id: item.rule_id,
                                _token: '{{ csrf_token() }}'
                            },
                            success: function() {
                                row.remove();
                            }
                        });
                    } else {
                        row.remove();
                    }
                };

                colRemove.appendChild(removeBtn);

                row.appendChild(colType);
                row.appendChild(colLang);
                row.appendChild(colSess);
                row.appendChild(colFile);
                // row.appendChild(colProtect);
                // row.appendChild(colPassword);
                row.appendChild(colPrice);
                // row.appendChild(colDownload);
                row.appendChild(colRemove);

                document.getElementById('assignment-files').appendChild(row);

                assignmentFile++;
            }

            /* ---------- LOAD EXISTING FILE RULES ---------- */
            fetch("{{ route('get.assignment.files', $assignmentId) }}")
                .then(res => res.json())
                .then(data => {
                    data.forEach(item => addAssignmentFileRow(item));
                });

            /* ---------- ADD NEW ROW ---------- */
            document.getElementById('add-file-row')
                .addEventListener('click', () => addAssignmentFileRow());

        });
    </script>

@endsection
