<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/js/bootstrap.bundle.min.js" integrity="sha384-ndDqU0Gzau9qJ1lfW4pNLlhNTkCfHzAVBReH9diLvGRem5+R9g2FzA8ZGN954O5Q" crossorigin="anonymous"></script>
<div class="content-wrapper">
    <section class="content pt-3">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-12">

                    <div class="card card-outline card-primary">
                        <div class="card-header">
                            <div class="d-flex align-items-center">
                                <div>
                                    <h3 class="card-title">Upload Documents</h3>
                                </div>
                            </div>
                        </div>

                        <!-- Form -->
                        <form id="uploadForm" method="post" action="<?php echo base_url('company/submit'); ?>" enctype="multipart/form-data">
                            <table class="table table-bordered">
                                <tr>
                                    <td>Select Company</td>
                                    <td>
                                        <select name="company_id" class="form-control">
                                            <?php foreach($company_list as $business) { ?>
                                            <option value="<?php echo $business['id'];?>"><?php echo $business['company_name'];?></option>
                                            <?php } ?>
                                        </select>
                                    </td>
                                </tr>
                            </table>
                            <input type="hidden" name="id" value="<?php echo $company_list[0]['id'];?>">

                            <table class="table table-bordered" id="dynamic_table">
                                <thead>
                                    <tr>
                                        <th>Authority</th>
                                        <th>Type</th>
                                        <th>Frequency</th>
                                        <th>
                                            <button type="button" id="addRow" class="btn btn-success btn-sm">Add Row</button>
                                        </th>
                                    </tr>
                                </thead>
                                <tbody id="tableBody">
                                    <!-- Rows will be added dynamically -->
                                </tbody>
                            </table>

                            <button type="submit" class="btn btn-primary">Submit</button>
                        </form>
                        <!-- End Form -->

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

<!-- Scripts -->
<script src="<?php echo site_url(); ?>public/assets/js/jquery-1.11.1.min.js"></script>
<script src="<?php echo site_url(); ?>public/assets/js/dataTables.js"></script>
<script src="<?php echo site_url(); ?>public/assets/js/dataTables.bootstrap5.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
let rowCount = 0;

// Create a new row
function createRow() {
    rowCount++;
    return `
    <tr data-row="${rowCount}">
        <td>
            <select name="authority_id[]" class="form-control authority" data-row="${rowCount}">
                <option value="">Select</option>
                <?php foreach($authority_data as $aut) { ?>
                <option value="<?= $aut['id']; ?>"><?= $aut['authority_name']; ?></option>
                <?php } ?>
            </select>
        </td>
        <td>
            <select name="type_id[]" class="form-control type" data-row="${rowCount}">
                <option value="">Select Type</option>
            </select>
        </td>
        <td>
            <label class="frequency" data-row="${rowCount}" style="font-weight:bold;"></label>
        </td>
        <td class="doc-container" data-row="${rowCount}">
            <!-- Documents will appear here -->
        </td>
    </tr>`;
}

$(document).ready(function () {

    // Add first row
    $('#tableBody').html(createRow());

    // Add new row
    $('#addRow').click(function () {
        $('#tableBody').append(createRow());
    });

    // Load types based on authority
    $(document).on('change', '.authority', function () {
        let row = $(this).data('row');
        let authorityId = $(this).val();
        let $typeSelect = $(`.type[data-row="${row}"]`);
        let $freqLabel = $(`.frequency[data-row="${row}"]`);

        $typeSelect.html('<option value="">Select Type</option>');
        $freqLabel.text('');

        if (authorityId !== '') {
            $.ajax({
                url: '<?= base_url("company/getTypeByAuthority") ?>',
                type: 'POST',
                data: { authority_id: authorityId },
                dataType: 'json',
                success: function (res) {
                    if (res.success) {
                        $.each(res.types, function (i, item) {
                            $typeSelect.append(`<option value="${item.id}">${item.type_name}</option>`);
                        });
                    }
                }
            });
        }
    });

    // Load frequency based on type and fetch documents
    $(document).on('change', '.type', function() {
        let row = $(this).data('row');
        let typeId = $(this).val();
        let $freqLabel = $(`.frequency[data-row="${row}"]`);
        $freqLabel.text('');
        $(`.doc-container[data-row="${row}"]`).html('');

        if (typeId !== '') {
            $.ajax({
                url: '<?= base_url("company/getFrequencyByType") ?>',
                type: 'POST',
                data: { type_id: typeId },
                dataType: 'json',
                success: function(res) {
                    if(res.success){
                        $freqLabel.text(res.frequency);
                        getDocumentsForType(typeId, row);
                    }
                }
            });
        }
    });

    // Validate PDF before submitting
    
});

// Fetch documents for selected type
function getDocumentsForType(typeId, row) {
    $.ajax({
        url: '<?= base_url("company/getDocumentsByType") ?>',
        type: 'POST',
        data: { type_id: typeId },
        dataType: 'json',
        success: function(res) {
            if(res.success){
                let docHtml = '';
                res.documents.forEach(function(doc) {
                    // Label with asterisk for mandatory
                    let label = doc.mandatory == 1 ? `${doc.document_name} <span class="text-danger">*</span>` : doc.document_name;

                    docHtml += `
                        <div class="mb-2">
                            <label><strong>${label}</strong></label>
                            <input type="hidden" name="document_id[${row}][]" value="${doc.id}">
                            <input type="file" name="document_file[${row}][]" 
                                   class="form-control mt-1 ${doc.mandatory == 1 ? 'mandatory-file' : ''}">
                        </div>
                    `;
                });
                $(`.doc-container[data-row="${row}"]`).html(docHtml);
            }
        }
    });
}
$('#uploadForm').submit(function(e) {
    let isValid = true;

    // Loop through all mandatory file inputs
    $('.mandatory-file').each(function() {
        if ($(this).val() === '') {
            isValid = false;
            $(this).addClass('is-invalid'); // Bootstrap highlight
            if (!$(this).next('.invalid-feedback').length) {
                $(this).after('<div class="invalid-feedback">This file is required.</div>');
            }
        } else {
            $(this).removeClass('is-invalid');
            $(this).next('.invalid-feedback').remove();
        }
    });

    if (!isValid) {
        e.preventDefault(); // prevent form submission
        $('html, body').animate({ scrollTop: $(".is-invalid:first").offset().top - 100 }, 500);
        alert('Please upload all mandatory files.');
    }
});
</script>
