<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;
}
.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;
}
.uploaded-badge {
    position: absolute;
    top: 5px;
    left: 5px;
    background: #28a745;
    color: #fff;
    padding: 2px 6px;
    font-size: 12px;
    border-radius: 4px;
}
select.form-select {
  padding: 0.4375rem 0.75rem;
  border: 0;
  outline: 1px solid #f3f3f3;
  color: #292626;
  
}
#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;
}
</style>

<div class="content">
  <div class="card">
  <div id="loader-overlay" style="display:none;">
  <div class="spinner-border text-primary" role="status">
    <span class="sr-only">Loading...</span>
  </div>
</div>
        <div class="card-header d-flex justify-content-between align-items-center">
            <h3 class="card-title"><?php echo $details->company_name;?> / Upload Documents</h3>
            <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" method="post" enctype="multipart/form-data">
                <!-- Month & Year dropdowns -->
                <div class="row mb-3">
                    <div class="col-md-6">
                        <label class="form-label">Month</label>
                        <select class="form-select" id="monthSelect" name="month" 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"
                            ];
                            foreach($months as $num=>$name): ?>
                                <option value="<?= $num; ?>"><?= $name; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Year</label>
                        <select class="form-select" id="yearSelect" name="year" required>
                            <option value="">Select Year</option>
                            <?php 
                            $currentYear = date("Y");
                            for($y=$currentYear; $y>=2000; $y--): ?>
                                <option value="<?= $y; ?>"><?= $y; ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>
                </div>

                <div id="rowsContainer"></div>
            </form>
        </div>
    </div>
</div>

<!-- Floating Add Row button -->
<button type="button" id="addRowBtnFloating" class="btn btn-primary shadow-lg">
    + Add Row
</button>

<script>
$(document).ready(function(){
    let entryCount = 0;
    let company_id = "<?= $details->id ?>"; // company from session

    // Disable Add Row buttons initially
    $("#addRowBtn, #addRowBtnFloating").prop("disabled", true);

    // Enable Add Row buttons when month & year selected
    $("#monthSelect, #yearSelect").on("change", function(){
        let month = $("#monthSelect").val();
        let year  = $("#yearSelect").val();
        if(month && year){
            $("#addRowBtn, #addRowBtnFloating").prop("disabled", false);
            if(entryCount === 0){ $("#addRowBtn").trigger("click"); }
            // Reload documents for existing rows
            $("#rowsContainer .upload-entry").each(function(){ loadDocuments($(this)); });
        }
    });

    // Add new row
    function addRow(){
        entryCount++;
        let html = `
        <div class="upload-entry" data-entry="${entryCount}">
            <button type="button" class="btn btn-danger btn-sm delete-row-btn">
                <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']; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Type</label>
                    <select class="form-select type" name="type[${entryCount}]">
                        <option value="">Select Type</option>
                    </select>
                </div>
            </div>
            <div class="documents"></div>
        </div>`;
        $("#rowsContainer").append(html);
        $('html, body').animate({ scrollTop: $("#rowsContainer .upload-entry").last().offset().top }, 500);
    }

    // Delete row
    $(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, ()=>$(this).remove()); } });
    });

    // Load types when authority changes
    $(document).on("change", ".authority", function(){
        let authority_id = $(this).val();
		 let month = $('#monthSelect').val();
        let year  = $('#yearSelect').val();
        let company_id = '<?php echo $company->id;?>';
        let entry = $(this).closest(".upload-entry");
        let typeSelect = entry.find(".type");
        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 Type</option>');
                types.forEach(t=>typeSelect.append('<option value="'+t.id+'">'+t.type_name+'</option>'));
            });
        } else {
            typeSelect.html('<option value="">Select Type</option>');
        }
    });

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

        if(type_id && month && year){
            $.post("<?= site_url('upload/getDocuments'); ?>", {
                type_id: type_id,
                company_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 col = $('<div class="col-md-3 mb-3"></div>');
                    if(d.file_name){
                        col.append(`
                            <div class="upload-box" data-doc-id="${d.id}" data-doc-name="${d.document_name}">
                                <span class="uploaded-badge">Uploaded</span>
                                <strong>${d.document_name}</strong><br>
                                <a href="<?= base_url(); ?>${d.file_path}" target="_blank">${d.file_name}</a>
                                <div class="file-actions mt-2">
                                    <button type="button" class="btn btn-warning btn-sm editFile"><i class="fa fa-edit"></i></button>
                                    <button type="button" class="btn btn-danger btn-sm deleteFile"><i class="fa fa-trash"></i></button>
                                </div>
                                <input type="file" class="file-input d-none" accept="application/pdf"/>
                            </div>`);
                    } else {
                        col.append(`
                            <div class="upload-box" data-doc-id="${d.id}" data-doc-name="${d.document_name}">
                                <strong>${d.document_name}</strong><br>
                                <input type="file" class="file-input d-none" accept="application/pdf"/>
                                <div class="file-info mt-2">
                                    <button type="button" class="btn btn-primary btn-sm uploadNew">
                                        <i class="fa fa-upload"></i> Upload
                                    </button>
                                </div>
                            </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); }
            });
        } else { docContainer.html(''); }
    }

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

    // Trigger load when month/year changes for all rows
    $("#monthSelect, #yearSelect").on("change", function(){
        $("#rowsContainer .upload-entry").each(function(){ loadDocuments($(this)); });
    });

    // Open file dialog
    $(document).on("click", ".uploadNew, .editFile", function(){
        $(this).closest(".upload-box").find(".file-input").trigger("click");
    });

    // Handle file upload
    $(document).on("change", ".file-input", function(){
        let file = this.files[0];
        if(!file) return;
        let box = $(this).closest(".upload-box");
        let entry = box.closest(".upload-entry");
        let month = $('#monthSelect').val();
        let year  = $('#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){
                    loadDocuments(entry); // Reload row to show uploaded badge
                    Swal.fire("✅ Success", "File uploaded successfully!", "success");
                } else {
                    Swal.fire("❌ Error", response.error, "error");
                }
            },
            error: function(){ Swal.fire("❌ Error", "Upload failed.", "error"); }
        });
    });

    // Delete file
    $(document).on("click", ".deleteFile", function(){
        let box = $(this).closest(".upload-box");
        let entry = box.closest(".upload-entry");
        Swal.fire({
            title: "Are you sure?",
            text: "This file will be permanently deleted.",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "Yes, delete it!"
        }).then((result)=>{
            if(result.isConfirmed){
                $.post("<?= site_url('upload/removeFile'); ?>", {
                    company_id: company_id,
                    type_id: entry.find(".type").val(),
                    document_id: box.data("doc-id"),
                    month: $('#monthSelect').val(),
                    year: $('#yearSelect').val()
                }, function(res){
                    let response = JSON.parse(res);
                    if(response.status){
                        loadDocuments(entry);
                        Swal.fire("✅ Deleted", response.message, "success");
                    } else {
                        Swal.fire("❌ Error", response.message, "error");
                    }
                });
            }
        });
    });

    // Bind Add Row buttons
    $("#addRowBtn, #addRowBtnFloating").on("click", addRow);
});
function showLoader() {
  $("#loader-overlay").fadeIn(200);
}
function hideLoader() {
  $("#loader-overlay").fadeOut(200);
}
</script>
