<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Compliance Upload</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
.compliance-box { border: 2px dashed #007bff; border-radius:10px; padding:15px; margin-bottom:20px; background:#fdfdfd; }
.compliance-box:hover{ box-shadow:0 5px 15px rgba(0,0,0,0.1); transform:scale(1.02);}
.compliance-box-header{ display:flex; justify-content:space-between; margin-bottom:10px; }
.file-upload-grid{ display:grid; grid-template-columns:repeat(auto-fill,minmax(180px,1fr)); gap:15px; }
.drop-zone{border:2px dashed #999; border-radius:8px; padding:15px; text-align:center; cursor:pointer; min-height:120px; display:flex; flex-direction:column; align-items:center; justify-content:center; transition:all 0.3s;}
.drop-zone:hover{border-color:#007bff; background:#f0f4f9;}
.drop-zone input[type="file"]{display:none;}
.progress-bar{margin-top:10px;}
.progress-track{width:100%; height:8px; background:#e9ecef; border-radius:4px;}
.progress-fill{height:100%; width:0%; background:#007bff; border-radius:4px; transition:width 0.4s;}
</style>
</head>
<body>

<h2>Compliance Upload</h2>
<form id="uploadForm" method="post" action="<?= base_url('company/submit'); ?>" enctype="multipart/form-data">
    <div id="dynamicBoxes"></div>
    <button type="button" id="addRowBtn">Add Authority</button>
    <button type="submit">Submit</button>
</form>

<script>
let rowCount = 0;

// Create new box
function createBox(){
    rowCount++;
    let box = $(`
        <div class="compliance-box" data-row="${rowCount}">
            <div class="compliance-box-header">
                <select name="authority_id[]" class="authority" data-row="${rowCount}">
                    <option value="">Select Authority</option>
                    <?php foreach($authority_data as $aut){ ?>
                    <option value="<?= $aut['id']; ?>"><?= $aut['authority_name']; ?></option>
                    <?php } ?>
                </select>
                <select name="type_id[]" class="type" data-row="${rowCount}">
                    <option value="">Select Type</option>
                </select>
                <span class="frequency" data-row="${rowCount}"></span>
            </div>
            <div class="file-upload-grid doc-container" data-row="${rowCount}"></div>
            <div class="progress-bar">
                <div class="progress-track"><div class="progress-fill" data-row="${rowCount}"></div></div>
            </div>
        </div>
    `);
    return box;
}

// First box
$('#dynamicBoxes').append(createBox());

// Add box
$('#addRowBtn').click(function(){ $('#dynamicBoxes').append(createBox()); });

// Authority -> load types
$(document).on('change','.authority',function(){
    let row=$(this).data('row');
    let authorityId=$(this).val();
    let $typeSelect=$(`.type[data-row="${row}"]`);
    $typeSelect.html('<option value="">Select Type</option>');
    $(`.doc-container[data-row="${row}"]`).html('');
    $(`.progress-fill[data-row="${row}"]`).css('width','0%');

    if(authorityId!==''){
        $.post('<?= base_url("company/getTypeByAuthority") ?>',{authority_id:authorityId},function(res){
            res=JSON.parse(res);
            if(res.success){
                $.each(res.types,function(i,item){ $typeSelect.append(`<option value="${item.id}">${item.type_name}</option>`); });
            }
        });
    }
});

// Type -> load documents and frequency
$(document).on('change','.type',function(){
    let row=$(this).data('row');
    let typeId=$(this).val();
    let $docContainer=$(`.doc-container[data-row="${row}"]`);
    $docContainer.html('');
    $(`.progress-fill[data-row="${row}"]`).css('width','0%');

    if(typeId!==''){
        // Frequency
        $.post('<?= base_url("company/getFrequencyByType") ?>',{type_id:typeId},function(res){
            res=JSON.parse(res);
            if(res.success){ $(`.frequency[data-row="${row}"]`).text(res.frequency); }
        });

        // Documents
        $.post('<?= base_url("company/getDocumentsByType") ?>',{type_id:typeId,row:row},function(res){
            $docContainer.html(res);
            updateProgress(row);
        });
    }
});

// Upload each document
$(document).on('change','.document-file',function(){
    let fileInput=this;
    let file=fileInput.files[0];
    let $dropZone=$(this).closest('.drop-zone');
    let $details=$dropZone.find('.file-details');

    if(file){
        let formData=new FormData();
        formData.append('document',file);
        formData.append('doc_id',$(this).data('doc'));

        $.ajax({
            url:'<?= base_url("company/uploadDocument") ?>',
            type:'POST',
            data:formData,
            contentType:false,
            processData:false,
            success:function(res){
                $dropZone.addClass('uploaded');
                $details.show();
                $details.find('.file-name').text(file.name);
                updateProgress($dropZone.closest('.compliance-box').data('row'));
            }
        });
    }
});

// Progress bar
function updateProgress(row){
    let total=$(`.doc-container[data-row="${row}"] .drop-zone`).length;
    let uploaded=$(`.doc-container[data-row="${row}"] input[type="file"]`).filter(function(){ return $(this).val()!=''; }).length;
    let percent=total>0?(uploaded/total)*100:0;
    $(`.progress-fill[data-row="${row}"]`).css('width',percent+'
