<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
       /* --- Compliance Card --- */
        .compliance-card {
            background-color: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            margin-bottom: 25px;
            box-shadow: var(--shadow);
            transition: box-shadow 0.3s;
        }
        
        .compliance-card:hover {
             box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px;
            border-bottom: 1px solid var(--border-color);
        }

        .card-title h2 {
            font-size: 1.1rem;
            font-weight: 600;
            margin-bottom: 4px;
        }

        .card-title p {
            color: var(--text-light);
            font-size: 0.9rem;
        }
        
        .status-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.8rem;
            color: #fff;
        }
        
        .status-incomplete {
            background-color: var(--status-incomplete);
        }
        .status-complete {
            background-color: var(--status-complete);
        }

        .card-body {
            padding: 20px;
        }

        .progress-bar {
            margin-bottom: 20px;
        }
        
        .progress-bar p {
            font-size: 0.9rem;
            font-weight: 500;
            margin-bottom: 8px;
            color: var(--text-light);
        }

        .progress-track {
            width: 100%;
            height: 8px;
            background-color: #e9ecef;
            border-radius: 4px;
        }
        
        .progress-fill {
            height: 100%;
            width: 0%; /* JS will update this */
            background-color: var(--status-complete);
            border-radius: 4px;
            transition: width 0.4s ease-in-out;
        }

        /* --- File Upload Grid --- */
        .file-upload-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 15px;
        }

        /* --- Drag and Drop Zone Styles --- */
        .drop-zone {
            position: relative;
            border: 2px dashed var(--border-color);
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 140px; /* Ensure sufficient height */
            background-color: #fdfdfd;
        }

        .drop-zone:hover {
            border-color: var(--primary-accent);
            background-color: #f0f4f9;
        }

        .drop-zone.drag-over {
            border-color: var(--drag-hover-border);
            background-color: #e6f0fa;
            transform: scale(1.02);
        }

        .drop-zone i {
            font-size: 2.2rem;
            color: var(--text-light);
            margin-bottom: 10px;
            transition: color 0.3s;
        }

        .drop-zone p {
            font-weight: 500;
            font-size: 0.9rem;
            color: var(--text-dark);
            margin-bottom: 5px;
        }
        
        .drop-zone .file-upload-info {
            font-size: 0.8rem;
            color: var(--text-light);
            word-break: break-all;
            line-height: 1.4;
        }

        .drop-zone input[type="file"] {
            display: none;
        }
        
        /* Uploaded state */
        .drop-zone.uploaded {
            border-style: solid;
            border-color: var(--status-complete);
            background-color: var(--file-uploaded-bg);
        }
        
        .drop-zone.uploaded i {
            color: var(--status-complete);
        }
        .drop-zone.uploaded p {
             color: var(--status-complete);
        }

        .drop-zone .file-details {
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;
            width: 100%;
            padding-top: 5px;
        }

        .drop-zone .file-details .file-name {
            font-weight: 500;
            color: var(--text-dark);
            margin-bottom: 5px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 90%;
        }

        .drop-zone .file-details .file-size,
        .drop-zone .file-details .status {
            font-size: 0.8rem;
            color: var(--text-light);
            margin-bottom: 5px;
        }

        .drop-zone .file-details .remove-btn {
            background: none;
            border: none;
            color: var(--status-error);
            font-size: 0.8rem;
            cursor: pointer;
            margin-top: 5px;
            transition: color 0.2s;
        }
        .drop-zone .file-details .remove-btn:hover {
            color: #cc0000;
        }

        /* Progress within drop zone (simulated) */
        .drop-zone .uploading-progress {
            width: calc(100% - 20px); /* Adjust for padding */
            height: 4px;
            background-color: #e0e0e0;
            border-radius: 2px;
            margin-top: 10px;
            overflow: hidden;
            display: none; /* Hidden by default, shown during upload */
        }
        .drop-zone .uploading-progress-fill {
            height: 100%;
            width: 0%;
            background-color: var(--primary-accent);
            border-radius: 2px;
            transition: width 0.3s ease-in-out;
        }
        .drop-zone.uploading .uploading-progress {
            display: block;
        }

    </style>
<div class="content-wrapper">
    <section class="content pt-3">
        <div class="container-fluid">
            <div class="card card-outline card-primary">
                <div class="card-header">
                    <h3 class="card-title">Upload Documents</h3>
                </div>

                <form method="post" action="<?= 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="<?= $business['id']; ?>"><?= $business['company_name']; ?></option>
                                    <?php } ?>
                                </select>
                            </td>
                        </tr>
                    </table>

                    <table class="table table-bordered" id="dynamic_table">
                        <thead>
                            <tr>
                                <th>Authority</th>
                                <th>Type</th>
                                <th>Frequency</th>
                                <th>Documents</th>
                                <th><button type="button" id="addRow" class="btn btn-success btn-sm">Add Row</button></th>
                            </tr>
                        </thead>
                        <tbody id="tableBody"></tbody>
                    </table>

                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>
    </section>
</div>

<script src="<?= site_url(); ?>public/assets/js/jquery-1.11.1.min.js"></script>

<script>
let rowCount = 0;

// Create 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>
        
    </tr>
	<tr>
		<td class="doc-container" id="doc-container-${rowCount}"></td>
        <td><button type="button" class="btn btn-danger btn-sm removeRow">X</button></td>
	</tr>`;
}

// Handle file selection
function handleFileSelect(input) {
    let file = input.files[0];
    if (!file) return;

    let ext = file.name.split('.').pop().toLowerCase();
    if (ext !== 'pdf') {
        Swal.fire({
            icon: 'error',
            title: 'Invalid File',
            text: 'Only PDF files are allowed.'
        });
        input.value = ''; // reset
        return;
    }

    let dropZone = input.closest('.drop-zone');
    dropZone.querySelector('.file-name').innerText = file.name;
    dropZone.querySelector('.file-size').innerText = (file.size / 1024).toFixed(2) + ' KB';
    dropZone.querySelector('.file-details').style.display = 'block';
}

// Remove file
function removeFile(e, btn) {
    e.stopPropagation();
    let zone = btn.closest('.drop-zone');
    zone.querySelector('input[type=file]').value = '';
    zone.querySelector('.file-details').style.display = 'none';
}

// Load documents for type
function getDocumentsForType(typeId, row) {
    $.ajax({
        url: '<?= base_url("company/getDocumentsByType") ?>',
        type: 'POST',
        data: { type_id: typeId },
        dataType: 'json',
        success: function (res) {
            let container = $(`#doc-container-${row}`);
            container.html('');
            if (res.success) {
                res.documents.forEach(function (doc) {
					
                    let dropZoneHtml = `
                        <div class="drop-zone" onclick="this.querySelector('input').click()">
                            <i class="fa-solid fa-building-columns"></i>
                            <p>${doc.document_name} <span class="required">*</span></p>
                            <span class="file-upload-info">Drag & drop files here or click to browse</span>
                            <input type="file" 
                                   name="document_file[${row}][]" 
                                   data-docid="${doc.id}" 
                                   accept="application/pdf"
                                   onchange="handleFileSelect(this)">
                            <div class="file-details" style="display: none;">
                                <span class="file-name"></span>
                                <span class="file-size"></span>
                                <span class="status">Uploaded</span>
                                <button type="button" class="remove-btn" onclick="removeFile(event, this)">Remove</button>
                            </div>
                            <div class="uploading-progress"><div class="uploading-progress-fill"></div></div>
                        </div>`;
                    container.append(dropZoneHtml);
                });
            }
        }
    });
}

$(document).ready(function () {
    // Add first row
    $('#tableBody').append(createRow());

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

    // Remove row
    $(document).on('click', '.removeRow', function () {
        $(this).closest('tr').remove();
    });

    // 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('');
        $(`#doc-container-${row}`).html('');

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

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

        $freqLabel.text('');
        $(`#doc-container-${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);
                    }
                }
            });
        }
    });
});
</script>
