<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
body { background: #f8f9fa; }
.upload-entry { background: #fff; border: 1px solid #ddd; border-radius: 8px; padding: 15px; margin-bottom: 15px; position: relative; }
.delete-row-btn { position: absolute; top: 10px; right: 10px; }
.upload-box { border: 2px dashed #ccc; border-radius: 10px; padding: 15px; text-align: center; background: #fafafa; position: relative; cursor:pointer; }
.upload-box:hover { background: #f1f1f1; }
.file-actions button { margin: 3px; }
#addRowBtnFloating { position: fixed; bottom: 20px; right: 20px; z-index: 9999; border-radius: 50px; padding: 12px 20px; }
#loader-overlay { position: fixed; top:0; left:0; width:100%; height:100%; background-color: rgba(255,255,255,0.7); z-index:9999; display:flex; justify-content:center; align-items:center; display:none; }
.drop-overlay { position: absolute; top:0; left:0; width:100%; height:100%; background: rgba(0,123,255,0.1); display:flex; align-items:center; justify-content:center; font-weight:bold; font-size:0.9rem; pointer-events:none; display:none; }
.upload-box.dragover { border: 2px dashed #007bff; }
</style>

  
  
<div class="content">
  <div class="card">
    <input type="hidden" id="company_id" value="<?= $details->id; ?>">
    <!--<div class="card-header d-flex justify-content-between align-items-center">
        <h4 class="card-title"><?= $details->company_name; ?> / Upload Documents</h4>
        <?php /* <button type="button" id="addRowBtn" class="btn btn-success btn-sm"><i class="fa fa-plus"></i> Add Row</button> */ ?>
    </div> -->
    <div class="card-body">
        <form id="uploadForm" enctype="multipart/form-data">
            <div id="rowsContainer"></div>
        </form>
    </div>
  </div>
</div>

<button id="addRowBtnFloating" class="btn btn-primary shadow-lg">+ Add Row</button>
<div id="loader-overlay"><i class="fa fa-spinner fa-spin fa-3x"></i></div>

<script>
$(document).ready(function(){

    const now = new Date();
    $('#yearSelect').val(now.getFullYear());
    $('#monthSelect').val(("0"+(now.getMonth()+1)).slice(-2));

    let entryCount = 0;
    let company_id = "<?= $details->id ?>";

    // Enable "Add Row" buttons immediately (don't wait for year/month)
    $("#addRowBtnFloating").prop("disabled", false);

    // Automatically create the first row when page loads
    addRow();

    // Show loader functions
    function showLoader(){ $("#loader-overlay").fadeIn(200); }
    function hideLoader(){ $("#loader-overlay").fadeOut(200); }

    // ✅ Show supportive alert only if main document is uploaded
    function showSupportiveAlert(docs){
        let alerts = [];
        docs.forEach(main => {
            if(main.has_supportive_docs && main.file_name){ // only if main uploaded
                let missing = main.supportive_docs.filter(s => !s.file_name);
                if(missing.length > 0){
                    alerts.push(`<b>${main.document_name}</b>: ${missing.map(s => s.document_name).join(", ")}`);
                }
            }
        });
        if(alerts.length > 0){
            Swal.fire({
                icon:'warning',
                title:'Supportive Documents Missing',
                html: alerts.join('<br>'),
                confirmButtonText:'OK'
            });
        }
    }

    // Add a new row
    function addRow(){
        entryCount++;
        let html = `<div class="upload-entry border rounded p-3 mb-4" data-entry="${entryCount}">
                <div class="row mb-3">
                    <?php 
                        $currentYear = date("Y");   // e.g., 2025, 2026...
                        $startYear   = 2024;        // fixed starting year
                    ?>
                    <div class="col-md-6">
                        <label class="form-label">Year</label>
                        <select class="form-select yearSelect" name="year[<?= $entryCount ?>]" required>
                            <option value="">Select Year</option>
                            <?php for ($y = $currentYear; $y >= $startYear; $y--): ?>
                                <option value="<?= $y; ?>"><?= $y; ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Month</label>
                        <select class="form-select monthSelect" name="month[${entryCount}]" required>
                            <option value="">Select Month</option>
                            <?php 
                            $months = [
                                "01" => "January", "02" => "February", "03" => "March",
                                "04" => "April", "05" => "May", "06" => "June",
                                "07" => "July", "08" => "August", "09" => "September",
                                "10" => "October", "11" => "November", "12" => "December"
                            ];

                            $currentMonth = date('m');

                            foreach ($months as $num => $name):
                                if ((int)$num <= (int)$currentMonth): ?>
                                    <option value="<?= $num; ?>"><?= $name; ?></option>
                                <?php endif;
                            endforeach;
                            ?>
                        </select>
                    </div>
                </div>

                 ${entryCount > 1 ? `
                <button type="button" class="btn btn-danger btn-sm delete-row-btn mb-2">
                    <i class="fa fa-trash"></i>
                </button>` : ''}
                <div class="row mb-3">
                    <div class="col-md-6">
                        <label class="form-label">Authority</label>
                        <select class="form-select authority" name="authority[${entryCount}]">
                            <option value="">Select Authority</option>
                            <?php foreach($authorities as $a): ?>
                            <option value="<?= $a['authority_id'] ?>"><?= $a['authority_name']. '  ('.$a['alias_name'].')'  ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Document Head</label>
                        <select class="form-select type" name="type[${entryCount}]">
                            <option value="">Select Document Head</option>
                        </select>
                    </div>
                </div>
                <!--<div class="row mb-2">
                    <div class="col-12">
                        <small class="text-muted fw-semibold">
                        Allowed file type: <span class="text-danger">PDF only</span>, 
                        Maximum Upload size: <span class="text-danger">10MB</span>
                        </small>
                    </div>
                </div>-->
            <div class="documents"></div>
        </div>`;
        $("#rowsContainer").append(html);
        let now = new Date();
        let currentYear = now.getFullYear();
        let currentMonth = ("0" + (now.getMonth() + 1)).slice(-2);

        let lastRow = $("#rowsContainer .upload-entry").last();
        lastRow.find(".yearSelect").val(currentYear);
        lastRow.find(".monthSelect").val(currentMonth);

        // Smooth scroll to the new entry
        //$('html,body').animate({scrollTop: lastRow.offset().top}, 500);
        $('html,body').animate({scrollTop: $("#rowsContainer .upload-entry").last().offset().top},500);
    }

    // Load documents for a row
    function loadDocuments(entry){
        let type_id = entry.find(".type").val();
        let month = entry.find('.monthSelect').val();
        let year = entry.find('.yearSelect').val();
        let docContainer = entry.find(".documents");

        if(!type_id || !month || !year){ docContainer.html(''); return; }

        $.post("<?= site_url('upload/getDocuments'); ?>", {
            type_id, company_id, months: month, years: year
        }, function(res){
            let docs = JSON.parse(res);
            docContainer.html('');
            let row = $('<div class="row"></div>');

            docs.forEach((d,i)=>{
                let uploaded = d.file_name ? true : false;
                let mandatoryMark = d.has_supportive_docs ? ' <span class="text-danger">*</span>' : '';
                let col = $('<div class="col-md-3 mb-3"></div>');

                col.append(`<div class="upload-box border p-3 text-center rounded" data-doc-id="${d.id}">
                    <strong>${d.document_name}${mandatoryMark}</strong><br>
                    ${uploaded ? `<span class="badge bg-success mb-1">Uploaded</span><br><a href="<?= base_url() ?>${d.file_path}" target="_blank">${d.file_name}</a>` : ''}
                    <input type="file" class="file-input d-none" accept="application/pdf"/>
                    <div class="file-actions mt-2">
                        <button type="button" class="btn btn-primary btn-sm uploadNew"><i class="fa fa-upload"></i>${uploaded?" Modify":" Upload"}</button>
                    </div>
                    <div class="drop-overlay border border-primary rounded p-3 mt-2 text-muted" style="display:none;">Drag & Drop File Here</div>
                    <small class="text-muted d-block mt-3">PDF only, max 10MB</small>
                </div>`);

                row.append(col);
                if((i+1)%4==0){ docContainer.append(row); row=$('<div class="row"></div>'); }
            });

            if(row.children().length>0){ docContainer.append(row); }
            initDragDrop(docContainer);

            // ✅ Show supportive alert after rendering
            showSupportiveAlert(docs);
        });
    }

    // Drag & drop / file upload handling
    function initDragDrop(container){
        container.find(".upload-box").each(function(){
            let box = $(this), fileInput = box.find(".file-input"), overlay = box.find(".drop-overlay");
            box.find(".uploadNew").off("click").on("click", ()=>fileInput.trigger("click"));
            box.on("dragover", e=>{ e.preventDefault(); overlay.show(); });
            box.on("dragleave", e=>{ e.preventDefault(); overlay.hide(); });
            box.on("drop", e=>{
                e.preventDefault(); overlay.hide();
                let files = e.originalEvent.dataTransfer.files;
                if(files.length>0){ fileInput[0].files = files; fileInput.trigger("change"); }
            });

            fileInput.off("change").on("change", function(){
                let file = this.files[0]; if(!file) return;
                let entry = box.closest(".upload-entry");
                //let month = $('#monthSelect').val(), year = $('#yearSelect').val();
                let month = entry.find('.monthSelect').val(), year = entry.find('.yearSelect').val();
                let formData = new FormData();
                formData.append("file", file);
                formData.append("company_id", company_id);
                formData.append("type_id", entry.find(".type").val());
                formData.append("document_id", box.data("doc-id"));
                formData.append("month", month); formData.append("year", year);

                showLoader();
                $.ajax({
                    url:"<?= site_url('upload/doUpload'); ?>",
                    type:"POST",
                    data:formData,
                    processData:false,
                    contentType:false,
                    success:function(res){
                        hideLoader();
                        let response = JSON.parse(res);
                        if(response.status){
                            Swal.fire({icon:'success', title:'File uploaded!', timer:1200, showConfirmButton:false});
                            // reload documents
                            $.post("<?= site_url('upload/getDocuments'); ?>", {
                                type_id: entry.find(".type").val(),
                                company_id,
                                months: month,
                                years: year
                            }, function(r){
                                let updatedDocs = JSON.parse(r);
                                loadDocuments(entry); // re-render
                                setTimeout(()=>showSupportiveAlert(updatedDocs), 500);
                            });
                        } else { Swal.fire("❌ Error", response.error, "error"); }
                    },
                    error:function(){ hideLoader(); Swal.fire("❌ Error", "Upload failed.", "error"); }
                });
            });
        });
    }

    // Event bindings
    $("#addRowBtn, #addRowBtnFloating").on("click", addRow);

    $("#monthSelect, #yearSelect").on("change", function(){
        //let month = $('#monthSelect').val(), year = $('#yearSelect').val();
        let month =  entry.find('.monthSelect').val(), year = entry.find(".yearSelect").val();
        if(month && year){
            $("#addRowBtn, #addRowBtnFloating").prop("disabled", false);
            if(entryCount===0){ $("#addRowBtn").trigger("click"); }
            $("#rowsContainer .upload-entry").each(function(){ loadDocuments($(this)); });
        }
    });

    $(document).on("change", ".authority", function(){
        let authority_id = $(this).val(), entry = $(this).closest(".upload-entry"), typeSelect = entry.find(".type"),
           company_id = $("#company_id").val(); // 👈 assuming you have a hidden/input field for company
        let month =  entry.find('.monthSelect').val(), year = entry.find(".yearSelect").val();
        if(authority_id){
            $.post("<?= site_url('upload/getTypes'); ?>", {authority_id: authority_id,company_id: company_id,month:month,year:year}, function(res){
                let types = JSON.parse(res);
                typeSelect.html('<option value="">Select Document Head</option>');
                types.forEach(t=>typeSelect.append('<option value="'+t.id+'">'+t.type_name+'</option>'));
            });
        } else { typeSelect.html('<option value="">Select Document Head</option>'); }
    });

    $(document).on("change", ".type", function(){ loadDocuments($(this).closest(".upload-entry")); });

    $(document).on("click", ".delete-row-btn", function(){
        let row = $(this).closest(".upload-entry");
        Swal.fire({
            title:'Are you sure?', 
            text:"This row will be removed!", 
            icon:'warning', 
            showCancelButton:true, 
            confirmButtonText:'Yes, delete it!'
        }).then(result=>{ if(result.isConfirmed){ row.fadeOut(400, ()=>row.remove()); }});
    });

});
</script>
