{% load static %}
<!DOCTYPE html>
<html lang="en"> <!--begin::Head-->

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Upload</title><!--begin::Primary Meta Tags-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="title" content="CQT | Upload">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fontsource/source-sans-3@5.0.12/index.css"
        integrity="sha256-tXJfXfp6Ewt1ilPzLDtQnJV4hclT9XuaZUKyUvmyr+Q=" crossorigin="anonymous">
    <!--end::Fonts--><!--begin::Third Party Plugin(OverlayScrollbars)-->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/overlayscrollbars@2.3.0/styles/overlayscrollbars.min.css"
        integrity="sha256-dSokZseQNT08wYEWiz5iLI8QPlKxG+TswNRD8k35cpg=" crossorigin="anonymous">
    <!--end::Third Party Plugin(OverlayScrollbars)--><!--begin::Third Party Plugin(Bootstrap Icons)-->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.min.css"
        integrity="sha256-Qsx5lrStHZyR9REqhUF8iQt73X06c8LGIUPzpOhwRrI=" crossorigin="anonymous">
    <!--end::Third Party Plugin(Bootstrap Icons)--><!--begin::Required Plugin(AdminLTE)-->
    <link rel="stylesheet" href="{% static './css/adminlte.css' %}"><!--end::Required Plugin(AdminLTE)--><!-- apexcharts -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/apexcharts@3.37.1/dist/apexcharts.css"
        integrity="sha256-4MX+61mt9NVvvuPjUWdUdyfZfxSB1/Rf9WtqRHgG5S0=" crossorigin="anonymous">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="{% static './css/select2-bootstrap4.min.css' %}">
    <link rel="stylesheet" href="{% static './css/custom.css' %}">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/datatables@1.10.18/media/css/jquery.dataTables.min.css">
    <style>
        .select2-container .select2-search--inline .select2-search__field {
            position: absolute;
            top: 3px;
            font-size: 14px;
        }
        #full-page-loader {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.6); /* semi-transparent black */
            z-index: 9999;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .loader-overlay .spinner-border {
            width: 3rem;
            height: 3rem;
        }

    </style>
</head>

<body class="layout-fixed sidebar-expand-lg sidebar-mini app-loaded sidebar-collapse">
    <!--begin::App Wrapper-->
    <div class="app-wrapper"> <!--begin::Header-->
        {% include 'header.html' %}
        {% include 'sidebar.html' %}
        <main class="app-main"> <!--begin::App Content Header-->
            <div class="app-content-header"> <!--begin::Container-->
                <div class="container-fluid"> <!--begin::Row-->
                    <div class="row">
                        <div class="col-sm-6">
                            <h3 class="mb-0">🏷️ Product Attributes &nbsp;<span><a href="./../media/examples/product_attribute_template.xlsx"    title="Example file" download><i class="bi bi-download"></i></a></span></h3> 
                            
                        </div>
                        <div class="col-sm-6">
                            <ol class="breadcrumb float-sm-end">
                                <li class="breadcrumb-item"><a href="{% url 'file-upload' %}">Home</a></li>
                                <li class="breadcrumb-item active" aria-current="page"><a href="{% url 'product-attributes' %}"></a>
                                   🏷️ Product Attributes</a>
                                </li>
                            </ol>
                        </div>
                    </div> <!--end::Row-->
                </div> <!--end::Container-->
            </div>
            <div class="app-content"> <!--begin::Container-->
                <div class="container-fluid"> <!-- Info boxes -->
                    <div id="full-page-loader" style="display: none;">
                    <div class="loader-overlay">
                        <div class="spinner-border text-light" role="status">
                            <!-- <span class="sr-only">Loading...</span> -->
                        </div>
                    </div>
                </div>
                <div class="row">
                    <!-- upload attributes -->
                    <div class="col-md-12">
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5 class="card-title">Upload Attributes</h5>
                            </div> 
                            <div class="card-body p-0">
                                <form id="uploadForm" method="POST"  enctype="multipart/form-data"> <!--begin::Body-->
                                    {% csrf_token %}
                                    <div class="card-body">
                                        
                                        <div class="form-group row mb-3">
                                            <label for="file" class="col-sm-2 col-form-label">Select Input
                                                File <span class="text-danger">*</span></label>
                                            <div class="col-sm-6">
                                                <div class="input-group mb-3"> 
                                                    <input type="file" class="form-control"
                                                        id="fileInput" name="file" required
                                                        >
                                            </div>
                                        </div>

                                        <div class="form-group row mb-3 ">
                                            <label for="file" class="col-sm-2 col-form-label"></label>
                                            <div class="col-sm-6">
                                                <button type="submit" class="btn btn-primary" id="submitBtn" disabled>Upload</button>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                                
                                <div id="responseMessage" class="mt-3"></div>

                            </div>
                        </div> <!-- /.card -->
                    </div>
                     <!-- upload attributes end -->
                    <div class="col-md-12">
                        <div class="card mb-4">
                             <div class="card-header">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <h3>Manage Attributes</h3>
                                    <!-- <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addProductTypeModal">Add New Product Type</button>
                                    <button class="btn btn-info" data-bs-toggle="modal" data-bs-target="#addProductAttributeModal">Add New Attribute</button> -->
                                </div>
                            </div>
                            <div class="card-body">
                                <table class="table table-bordered table-striped" cellspacing="0" width="100%" id="product-attribute-list">
                                    <thead class="table-dark" >
                                    <tr>
                                        <th>ID</th>
                                        <th>Product Type</th>
                                        <th>Product Attribute List</th>
                                        <!-- <th>Actions</th> -->
                                    </tr>
                                    </thead>
                                    <tbody id="dataBody">
                                    <!-- <tr>
                                        <td>1</td>
                                        <td>Canvas Art Prints</td>
                                        <td><ul>
                                                <li>color</li>
                                                <li>Shade</li>
                                            </ul>
                                        </td>
                                        <td>
                                        <button class="btn btn-sm btn-warning" data-bs-toggle="modal"  data-bs-target="#editModal">Edit</button>
                                        </td>
                                    </tr> -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>


                <div class="modal fade" id="addProductTypeModal" tabindex="-1" aria-labelledby="addProductTypeModal" aria-hidden="true">
                <div class="modal-dialog">
                    <form class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addTypeModalLabel">Add Product Type</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                        <label for="addProductTypeName" class="form-label">Name</label>
                        <input type="text" class="form-control" id="addName" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-success">Save</button>
                    </div>
                    </form>
                </div>
                </div>

                <div class="modal fade" id="addProductAttributeModal" tabindex="-1" aria-labelledby="addProductAttributeModal" aria-hidden="true">
                <div class="modal-dialog">
                    <form class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addAttributeModalLabel">Add Product Attribute</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="addProductType" class="form-label">Product Type</label>
                            <select name="productType" class="form-control" id="productType" aria-describedby="Select Product Type">
                                <option value="">Select Product Type</option>
                                <option value="color">Color</option>
                                <option value="shade">Shade</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="addAttributeName" class="form-label">Name</label>
                            <input type="text" class="form-control" id="addAttributeName" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-success">Save</button>
                    </div>
                    </form>
                </div>
                </div>

                <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <form class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="editModalLabel">Edit Product Attribute</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" id="editId">
                        <div class="mb-3">
                        <label for="editProductType" class="form-label">Product Type</label>
                            <select name="editProductType[]" class="form-control" id="editProductType" aria-describedby="Select Product Type" multiple>
                                <option value="">Select Product Type</option>
                                <option value="color">Color</option>
                                <option value="shade">Shade</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="editAttributeName" class="form-label">Name</label>
                            <input type="text" class="form-control" id="editAttributeName" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary">Update</button>
                    </div>
                    </form>
                </div>
                </div>

 </div> <!--end::Container-->
            </div> <!--end::App Content-->
        </main> <!--end::App Main--> <!--begin::Footer-->
        {% include 'footer.html' %}

    </div> 
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"
        integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/overlayscrollbars@2.3.0/browser/overlayscrollbars.browser.es6.min.js"
        integrity="sha256-H2VM7BKda+v2Z4+DRy69uknwxjyDRhszjXFhsL4gD3w=" crossorigin="anonymous"></script>
    <!--end::Third Party Plugin(OverlayScrollbars)--><!--begin::Required Plugin(popperjs for Bootstrap 5)-->
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js"
        integrity="sha256-whL0tQWoY1Ku1iskqPFvmZ+CHsvmRWx/PIoEvIeWh4I=" crossorigin="anonymous"></script>
    <!--end::Required Plugin(popperjs for Bootstrap 5)--><!--begin::Required Plugin(Bootstrap 5)-->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js"
        integrity="sha256-YMa+wAM6QkVyz999odX7lPRxkoYAan8suedu4k2Zur8=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <!--end::Required Plugin(Bootstrap 5)--><!--begin::Required Plugin(AdminLTE)-->
    <script src="{% static './js/adminlte.js' %}"></script>
    <script src="https://cdn.jsdelivr.net/npm/datatables@1.10.18/media/js/jquery.dataTables.min.js"></script>
    <!--end::Required Plugin(AdminLTE)--><!--begin::OverlayScrollbars Configure-->
    <script>
        const SELECTOR_SIDEBAR_WRAPPER = ".sidebar-wrapper";
        const Default = {
            scrollbarTheme: "os-theme-light",
            scrollbarAutoHide: "leave",
            scrollbarClickScroll: true,
        };
        document.addEventListener("DOMContentLoaded", function () {
            const sidebarWrapper = document.querySelector(SELECTOR_SIDEBAR_WRAPPER);
            if (
                sidebarWrapper &&
                typeof OverlayScrollbarsGlobal?.OverlayScrollbars !== "undefined"
            ) {
                OverlayScrollbarsGlobal.OverlayScrollbars(sidebarWrapper, {
                    scrollbars: {
                        theme: Default.scrollbarTheme,
                        autoHide: Default.scrollbarAutoHide,
                        clickScroll: Default.scrollbarClickScroll,
                    },
                });
            }
        });
        $(document).ready(function () {
            // $('#product-attribute-list').DataTable();
        });
    </script> <!--end::OverlayScrollbars Configure--> <!-- OPTIONAL SCRIPTS --> <!-- apexcharts -->
    
      
</script>

</body><!--end::Body-->
<script>
$(document).ready(function () {
    $('#product-attribute-list').on('click', '.btn-warning', function () {
        var $row = $(this).closest('tr');
        
        // Extract the Product Attribute List (list items inside <ul>)
        var selectedAttributes = [];
        $row.find('td:nth-child(3) ul li').each(function () {
            selectedAttributes.push($(this).text().trim().toLowerCase());
        });

        // Clear previous selection
        $('#editProductType option').prop('selected', false);

        // Select the ones that match
        $('#editProductType option').each(function () {
            if (selectedAttributes.includes($(this).val().toLowerCase())) {
                $(this).prop('selected', true);
            }
        });

        // Also update attribute name if needed
        var attributeName = selectedAttributes.length ? selectedAttributes[0] : '';
        $('#editAttributeName').val(attributeName);
    });
});
</script>

<script>
    $(document).ready(function () {
        $('#editProductType').select2({
            dropdownParent: $('#editModal'), // important for modal
            placeholder: 'Select product attributes'
        });
    });

    var API_DATA = []
    let product_types = [];
    
    
    document.addEventListener('DOMContentLoaded', function () {
        const form = document.getElementById('uploadForm');
        const fileInput = document.getElementById('fileInput');
        const submitBtn = document.getElementById('submitBtn');
        const responseDiv = document.getElementById('responseMessage');

        // Enable submit button when file is selected
        fileInput.addEventListener('change', function () {
            submitBtn.disabled = fileInput.files.length === 0;
        });

        // Handle form submission
        form.addEventListener('submit', function (e) {
            e.preventDefault();
            $('#full-page-loader').show();
            // Disable button during upload
            submitBtn.disabled = true;
            submitBtn.textContent = 'Uploading...';

            const formData = new FormData(form);

            fetch('/attr/products/upload-attributes/', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                }
            })
            .then(response => response.json())
            .then(data => {
                // if (data.success) {
                    responseDiv.innerHTML = `<div class="alert alert-success">✅ ${data.message}</div>`;
                    fileInput.value = ''; // Clear file input
                    submitBtn.disabled = true; // Keep disabled until new file selected
                    $('#full-page-loader').hide();
                // } else {
                //     responseDiv.innerHTML = `<div class="alert alert-danger">❌ ${data.error}</div>`;
                //     submitBtn.disabled = false;
                //     $('#full-page-loader').hide();
                // }
            })
            .catch(error => {
                responseDiv.innerHTML = `<div class="alert alert-danger">❌ Upload failed: ${error}</div>`;
                submitBtn.disabled = false;
                $('#full-page-loader').hide();
            })
            .finally(() => {
                submitBtn.textContent = 'Upload';
                $('#full-page-loader').hide();

                // Remove message after 5 seconds
                setTimeout(() => {
                    responseDiv.innerHTML = '';
                }, 3000);
            });
        });
    });
    document.addEventListener('DOMContentLoaded', () => {
        jQuery('#full-page-loader').show();  
            try{
            fetch('/attr/products/attributes', {
                method: 'GET', // or 'POST' if your API expects POST
                headers: {
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || ''
                }
            })
            .then(response => response.json())
            .then(data => {
                console.log("data",data);
                API_DATA = data;
                renderAttributeTable(API_DATA);
                // 2. ONLY THEN, initialize DataTables
                if (jQuery.fn.DataTable) { // Optional safety check
                    jQuery('#product-attribute-list').DataTable({
                        // Ensure the table structure is maintained if you re-render
                        destroy: true 
                    });
                } else {
                    console.error("DataTables plugin not loaded.");
                }
                jQuery('#full-page-loader').hide();
            });
        }catch(err){
            console.log("err",err);
            jQuery('#full-page-loader').hide();

        }
    });

    // Function to generate the data and populate the table
function renderAttributeTable(apiData) {
    const $dataBody = jQuery('#dataBody');
    $dataBody.empty(); // Clear existing rows

    if (!apiData || apiData.length === 0) {
        $dataBody.append('<tr><td colspan="4">No product attributes found.</td></tr>');
        return;
    }

    // 1. Iterate directly over the flat API data
    apiData.forEach((item, index) => {
        // Prepare the content for the third column (Attribute List)
        const attributeName = item.attribute_name;
        const isMandatory = item.is_mandatory;
        const possibleValues = item.possible_values;
        const productType = item.product_type;
        
        // --- Column 3: Product Attribute List (UL/LI) ---
        const $attributeList = jQuery('<ul></ul>');
        
        let className = isMandatory === 'Yes' ? 'mandatory-attr' : 'optional-attr';
        let status = isMandatory === 'Yes' ? ' (Mandatory)' : ' (Optional)';

        // Create a single <li> for this attribute
        const liContent = `<strong>${attributeName}</strong>${status}: ${possibleValues}`;
        const $listItem = jQuery(`<li class="${className}"></li>`).html(liContent);
        $attributeList.append($listItem);

        // --- Create the Table Row ---
        const $newRow = jQuery('<tr></tr>');

        // Column 1: ID (Using index + 1 for simple row numbering)
        $newRow.append(`<td>${index + 1}</td>`);

        // Column 2: Product Type
        $newRow.append(`<td>${productType}</td>`);

        // Column 3: Product Attribute List
        // Note: Each row now contains only one attribute name in the list
        const $listCell = jQuery('<td></td>').append($attributeList);
        $newRow.append($listCell);

        // Column 4: Actions (Edit Button)
        const $actionsCell = jQuery('<td></td>');
        // const $editButton = jQuery('<button class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#editModal">Edit</button>');
        
        // Attach data specific to this attribute for modal editing
        // $editButton.data('attributeData', item); 

        // $actionsCell.append($editButton);
        // $newRow.append($actionsCell);

        // Append the row to the table body
        $dataBody.append($newRow);
    });
    
}
</script>
</html>

