@extends('layouts.app')


@section('title','Brand')
@section('content')
 <style>
.select2-container {
    width: 100% !important;
    position: relative;
}
/* Main box */
.select2-container--default .select2-selection--multiple {
    min-height: 40px;
    padding: 6px  10px; /* right space for arrow */
    border-radius: 10px;
    border: 1px solid #dee2e6;
    font-size: 14px;
    display: flex;
    align-items: center;
    /* 🔽 Custom dropdown arrow */
    appearance: none;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23667eea' d='M6 9L1 4h10z'/%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 15px center;
    background-size: 12px;
}
</style>
<div class="page-container">
    <div class="form-container">
        @if(session('success'))
        <div class="alert-success-custom">
            <i class="fas fa-check-circle"></i>
            <span>{{session('success')}}</span>
        </div>
        @endif
        <form method="POST" action="/brands" enctype="multipart/form-data">
            @csrf
            <div class="form-section">
               <div class="form-section-title d-flex justify-content-between align-items-center">
                                  <div>
                                      <i class="fas fa-layer-group"></i> Add New Brand
                                         </div>
                                 <button class="btn btn-sm btn-primary"
                                     data-bs-toggle="modal"
                                     data-bs-target="#brandsModal"
                                      onclick="loadBrands()">
                                      <i class="fas fa-eye"></i> View Brands
                                       </button>
                                  </div>



                                  
                                     <div class="form-row-3">
                                        <div class="form-group">
                                     <label for="sub_category">
<i class="fas fa-folder-open"></i>
Brand RmName
</label>
<select name="brand_rm_name" id="brand_rm_name" class="form-select-custom" required>
<option value="">Select Brand RM Name</option>
<option value="Manav Kapila">Manav Kapila</option>
<option value="Kunal Pandey">Kunal Pandey</option>
<option value="Rajan Malik">Rajan Malik</option>
<option value="Krishna Nagar">Krishna Nagar</option>
<option value="Mohammad Sarim">Mohammad Sarim</option>
<option value="Maneeshima Ray">Maneeshima Ray</option>
</select>
</div>

                                    <div class="form-group">
                                     <label for="sector">
                                  <i class="fas fa-map-marker-alt"></i>
                                    Sector
                                 </label>
                                  <select name="sector" id="sector" class="form-select-custom" required>
<option value="">Select Sector</option>
<option value="Fashion & Lifestyle">Fashion & Lifestyle</option>
<option value="Food & Beverages">Food & Beverages</option>
<option value="Entertainment & Leisure">Entertainment & Leisure</option>
<option value="Electronics & Consumer Durables">Electronics & Consumer Durables</option>
<option value="Convinince Retail">Convinince Retail</option>
<option value="Health, Beauty & Wellness">Health, Beauty & Wellness</option>
<option value="Home & Living">Home & Living</option>
<option value="Kids, Toys & Education">Kids, Toys & Education</option>
<option value="Diagnostic & Clinical Services">Diagnostic & Clinical Services</option>
<option value="Automobile and Mobility Retail">Automobile and Mobility Retail</option>
</select>
                                     </div>

                    <div class="form-group">
                        <label for="category">
                            <i class="fas fa-folder"></i>
                            Store Type
                        </label>
                          <select name="brand_storetype" id="brand_storetype" class="form-select-custom" required>
                          <option value="">Select Store Type</option>
<option value="Exclusive Brand Outlet (EBO)">Exclusive Brand Outlet (EBO)</option>
<option value="Multi Brand Outlet (MBO)">Multi Brand Outlet (MBO)</option>
<option value="Anchor Store">Anchor Store</option>
<option value="Speciality Store">Speciality Store</option>
<option value="Department Store">Department Store</option>
<option value="Discount Store">Discount Store</option>
<option value="Factory Outlet">Factory Outlet</option>
<option value="QSR">QSR</option>
<option value="Cafe">Cafe</option>
                      
                            
                        </select>
                    </div>






                   
                                     <div class="form-group">
                                       <label>
                                   <i class="fas fa-briefcase"></i> Business Model
                                       </label>
                                      <select name="business_model[]"
                                         id="business_model" class="form-select-custom"  
                                         multiple required>
                                           <option value="COCO">COCO</option>
<option value="FOCO">FOCO</option>
<option value="FOFO">FOFO</option>
<option value="COFO">COFO</option>
                                                   </select>
                                                    </div>

              
                  <div class="form-group">
                    <label for="name">
                        <i class="fas fa-tag"></i>
                        Brand Name
                    </label>
                    <input type="text" 
                           name="name" 
                           id="name" 
                           class="form-control-custom" 
                           placeholder="Enter brand name"
                           required>
                </div>
                <div class="form-group">
                    <label for="website">
                        <i class="fas fa-globe"></i>
                        Website URL 
                        <span class="required">*</span>
                    </label>
                    <input type="url" 
                           name="website" 
                           id="website" 
                           class="form-control-custom" 
                           placeholder="https://example.com"required>
                </div>
                 <div class="form-group">
                    <label for="deck">
                        <i class="fas fa-upload"></i>
                        Brand Deck (PDF)
                        <span class="required">*</span>
                    </label>
                    <div class="file-input-wrapper">
                        <input type="file" 
                               name="deck" 
                               id="deck" 
                               accept=".pdf"
                               onchange="updateFileName(this)" required>
                        <label for="deck" class="file-input-label">
                            <i class="fas fa-cloud-upload-alt"></i>
                            <span>Click to upload PDF file</span>
                        </label>
                    </div>
                    <div class="file-name" id="fileName">
                        <i class="fas fa-file-pdf"></i>
                        <span></span>
                    </div>
                </div>
            </div>
          
          
            <button type="submit" class="btn-submit">
                <i class="fas fa-save"></i>
                Save Brand
            </button>
        </form>
    </div>
</div>



<!-- Brands List Modal (Popup) -->
 <div class="modal fade" id="brandsModal" tabindex="-1">
    <div class="modal-dialog modal-xl modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5><i class="fas fa-list"></i> All Brands</h5>
                <button class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>SR.No.</th>
                            <th>Name</th>
                            <th>Store Type</th>
                            <th>Business Model</th>
                            <th>Brand RM Name</th>
                            <th>Sector</th>
                            <th>Actions</th>
                        </tr>                   
                    </thead>
                    <tbody id="brandsTable"></tbody>
                </table>
              <div id="brandsPagination" class="mt-3 d-flex justify-content-end"></div>

        </div>
    </div>
</div>

<!-- View Brand  -->
 <div class="modal fade" id="viewBrandModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5><i class="fas fa-eye"></i> Brand Details</h5>
                <button class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="viewBrandBody"></div>
        </div>
    </div>
</div>
<div class="modal fade" id="editBrandModal" tabindex="-1">
    <div class="modal-dialog modal-xl modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5><i class="fas fa-edit"></i> Edit Brand</h5>
                <button class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editBrandForm" method="POST" enctype="multipart/form-data">
                @csrf
                @method('PUT')
                <div class="modal-body">
                    <!-- Brand Information-->
                    <div class="form-section">
                        <div class="form-section-title">
                            <i class="fas fa-layer-group"></i> Brand Information
                        </div>
                        <div class="form-row-3">
                            
                            <div class="form-group">
                                <label>Brand RM Name</label>
                                     <select id="edit_brand_rm_name" name="brand_rm_name" class="form-select-custom"  required>
                                      <option value="">Select Brand RM Name</option>
<option value="Manav Kapila">Manav Kapila</option>
<option value="Kunal Pandey">Kunal Pandey</option>
<option value="Rajan Malik">Rajan Malik</option>
<option value="Krishna Nagar">Krishna Nagar</option>
<option value="Mohammad Sarim">Mohammad Sarim</option>
<option value="Maneeshima Ray">Maneeshima Ray</option>
                                            </select>
                            </div>



                            
                            <div class="form-group">
                                <label>Sector</label>
                               <select id="edit_sector"
        name="sector"
        class="form-select-custom"
        required>
    <option value="">Select Sector</option>
<option value="Fashion & Lifestyle">Fashion & Lifestyle</option>
<option value="Food & Beverages">Food & Beverages</option>
<option value="Entertainment & Leisure">Entertainment & Leisure</option>
<option value="Electronics & Consumer Durables">Electronics & Consumer Durables</option>
<option value="Convinince Retail">Convinince Retail</option>
<option value="Health, Beauty & Wellness">Health, Beauty & Wellness</option>
<option value="Home & Living">Home & Living</option>
<option value="Kids, Toys & Education">Kids, Toys & Education</option>
<option value="Diagnostic & Clinical Services">Diagnostic & Clinical Services</option>
<option value="Automobile and Mobility Retail">Automobile and Mobility Retail</option>
</select>
</div>
                            <div class="form-group">
                                <label>Store Type</label>
                                <select id="edit_brand_storetype" name="brand_storetype" class="form-select-custom"  required>
                                   <option value="">Select Store Type</option>
<option value="Exclusive Brand Outlet (EBO)">Exclusive Brand Outlet (EBO)</option>
<option value="Multi Brand Outlet (MBO)">Multi Brand Outlet (MBO)</option>
<option value="Anchor Store">Anchor Store</option>
<option value="Speciality Store">Speciality Store</option>
<option value="Department Store">Department Store</option>
<option value="Discount Store">Discount Store</option>
<option value="Factory Outlet">Factory Outlet</option>
<option value="QSR">QSR</option>
<option value="Cafe">Cafe</option>
                                </select>
                            </div>
                            <div class="form-group">
    <label>Business Model</label>
   <select id="edit_business_model"
        name="business_model[]"
        class="form-select-custom"
        multiple
        required>
   <option value="COCO">COCO</option>
<option value="FOCO">FOCO</option>
<option value="FOFO">FOFO</option>
<option value="COFO">COFO</option>
</select>
</div>








                             <div class="form-group">
                                <label>Brand Name</label>
                                <input type="text" id="edit_name"
                                       name="name"
                                       class="form-control-custom" required>
                            </div>
                            <div class="form-group">
                                <label>Website</label>
                                <input type="url" id="edit_website"
                                       name="website"
                                       class="form-control-custom">
                            </div>
                            <div class="form-group">
                                <label>Brand Deck (PDF)</label>
                                <!-- ✅ REQUIRED -->
                                <div id="edit_deck_preview" class="mb-2"></div>
                                <div class="file-input-wrapper">
                                    <input type="file" id="edit_deck"
                                           name="deck" accept=".pdf">
                                    <label for="edit_deck"
                                           class="file-input-label">
                                        <i class="fas fa-cloud-upload-alt"></i>
                                        Upload PDF
                                    </label>
                                </div>
                            </div>
                            
                      
                        </div>
                    </div>
                
                </div>
                <div class="modal-footer">
                 <button class="btn btn-success" type="button" onclick="submitEditBrand()">
    <i class="fas fa-save"></i> Update Brand
</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function updateFileName(input) {
    const fileNameDiv = document.getElementById('fileName');
    const fileNameSpan = fileNameDiv.querySelector('span');
    if (input.files && input.files[0]) {
        const file = input.files[0];
        const maxSize = 2048 * 2048; // ✅ 1 B
        if (file.size > maxSize) {
            alert('❌ PDF size must be less than 1 MB');
            // reset input
            input.value = '';
            // hide filename
            fileNameDiv.style.display = 'none';
            fileNameSpan.textContent = '';
            return;
        }
        // ✅ valid pdf
        fileNameSpan.textContent = file.name;
        fileNameDiv.style.display = 'block';
    } else {
        fileNameDiv.style.display = 'none';
        fileNameSpan.textContent = '';
    }
}
</script>
<!-- load brand list -->
 <script>
function loadBrands(page = 1)
{
    $('#brandsTable').html('<tr><td colspan="5">Loading...</td></tr>');
    $('#brandsPagination').html('');
    $.get(`/brands/list?page=${page}`, function(res){
        if(!res.data || res.data.length === 0){
            $('#brandsTable').html(
                '<tr><td colspan="5" class="text-center">No Brands Found</td></tr>'
            );
            return;
        }
        let rows = '';
        // 🔢 SR NUMBER (reverse order)
        let srStart = res.total - ((res.current_page - 1) * res.per_page);
        res.data.forEach((brand, index) => {
            rows += `
                <tr>
                    <td>${srStart - index}</td>
                    <td>${brand.name}</td>
                    <td>${brand.brand_storetype}</td>
                    <td>${brand.business_model}</td>
                      <td>${brand.brand_rm_name}</td>
                    <td>${brand.sector}</td>
                    <td>
                        <button class="btn btn-info btn-sm"
                            onclick="viewBrand(${brand.id})">View</button>
                        <button class="btn btn-warning btn-sm"
                            onclick="openEditBrand(${brand.id})">Edit</button>
                        <button class="btn btn-danger btn-sm"
                            onclick="deleteBrand(${brand.id})">Delete</button>
                    </td>
                </tr>
            `;
        });
        $('#brandsTable').html(rows);
        /* ===========================
           PAGINATION (Prev / Next)
        ============================ */
        if (res.total <= res.per_page) {
    $('#brandsPagination').html('');
    return;
}
        let pagination = '<div class="btn-group">';
        // PREV
        pagination += `
        <button class="btn btn-sm btn-outline-primary"
            ${res.current_page === 1 ? 'disabled' : ''}
            onclick="loadBrands(${res.current_page - 1})">
            &laquo; Prev
        </button>`;
        // PAGE NUMBERS (max 5)
        let pageStart = Math.max(1, res.current_page - 2);
        let pageEnd   = Math.min(res.last_page, res.current_page + 2);
        for(let i = pageStart; i <= pageEnd; i++){
            pagination += `
            <button class="btn btn-sm ${res.current_page == i ? 'btn-primary' : 'btn-outline-primary'}"
                onclick="loadBrands(${i})">
                ${i}
            </button>`;
        }
        // NEXT
        pagination += `
        <button class="btn btn-sm btn-outline-primary"
            ${res.current_page === res.last_page ? 'disabled' : ''}
            onclick="loadBrands(${res.current_page + 1})">
            Next &raquo;
        </button>`;
        pagination += '</div>';
        $('#brandsPagination').html(pagination);
    }); // ✅ $.get closed properly
}
</script>

<script>
function viewBrand(id){
    $.get(`/brands/${id}`, function(data){
        let pdfHtml = `<span class="text-muted">-</span>`;
        if(data.deck){
            pdfHtml = `
                <a href="/storage/${data.deck}" target="_blank"
                   class="btn btn-sm btn-outline-primary">
                    📄 View PDF
                </a>
            `;
        }
        $('#viewBrandBody').html(`
            <div class="row g-3">
                <div class="col-md-4">
                    <div class="info-box">
                        <span>Brand Name</span>
                        <strong>${data.name}</strong>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="info-box">
                        <span>StoreType</span>
                        <strong>${data.brand_storetype}</strong>
                    </div>
                </div>
         

                <div class="col-md-4">
                    <div class="info-box">
                        <span>Brand RM Name</span>
                         <strong>${data.brand_rm_name}</strong>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="info-box">
                        <span>Sector</span>
                        <strong>${data.sector}</strong>
                    </div>
                </div>




                            <div class="col-md-4">
                             <div class="info-box">
                               <span>Business Model</span>
                                <strong>
                          ${data.business_model 
                     ? data.business_model.split(',').join(' , ') 
                              : '-'}
                                  </strong>
                              </div>
                                   </div>

                <div class="col-md-4">
                    <div class="info-box">
                        <span>Website</span>
                        <strong>
                            ${data.website 
                                ? `<a href="${data.website}" target="_blank">${data.website}</a>` 
                                : '-'}
                        </strong>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="info-box">
                        <span>Brand Deck</span>
                        ${pdfHtml}
                    </div>
                </div>
            </div>
        `);
        $('#viewBrandModal').modal('show');
    });
}
</script>
<script>
// Delete Brand//
function deleteBrand(id){
    if(!confirm('Delete this brand?')) return;
    $.ajax({
        url: `/brands/${id}`,
        type: 'POST',
        data: {
            _method: 'DELETE',
            _token: '{{ csrf_token() }}'
        },
        success: function(){
            alert('Brand deleted');
            loadBrands();
        }
    });
}
</script>
<script>
function openEditBrand(id){
    $.get(`/brands/${id}`, function(data){
        $('#editBrandForm').attr('action', `/brands/${id}`);
        $('#edit_name').val(data.name);
        $('#edit_brand_storetype').val(data.brand_storetype);
        $('#edit_brand_rm_name').val(data.brand_rm_name);
        $('#edit_sector').val(data.sector);
        $('#edit_website').val(data.website);
        // ✅ BUSINESS MODEL
        let models = data.business_model
            ? data.business_model.split(',')
            : [];
        // 🔥 Destroy old Select2
        if ($('#edit_business_model').hasClass("select2-hidden-accessible")) {
            $('#edit_business_model').select2('destroy');
        }
        // 🔥 Re-init Select2 AFTER modal open
        $('#editBrandModal').on('shown.bs.modal', function () {
            $('#edit_business_model').select2({
                placeholder: "Select Business Model",
                width: '100%',
                dropdownParent: $('#editBrandModal') // ⭐ VERY IMPORTANT
            });
            // 🔥 Set selected values
            $('#edit_business_model').val(models).trigger('change');
        });
        // PDF Preview
        if(data.deck){
            $('#edit_deck_preview').html(`
                <a href="/storage/${data.deck}" target="_blank"
                   class="btn btn-sm btn-outline-primary">
                   <i class="fas fa-file-pdf"></i> View Current PDF
                </a>
            `);
        } else {
            $('#edit_deck_preview').html(
                '<small class="text-muted">No PDF uploaded</small>'
            );
        }
        $('#editBrandModal').modal('show');
    });
}

</script>

<script>
    // edit brand//
function submitEditBrand(){
    let form = $('#editBrandForm')[0];
    let formData = new FormData(form);
    $.ajax({
        url: $('#editBrandForm').attr('action'),
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        success: function(res){
            if(res.success){
                alert(res.message);
                // close modal
                $('#editBrandModal').modal('hide');
                // refresh list
                loadBrands();
            }
        },
        error: function(){
            alert('Something went wrong');
        }
    });
}
</script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0/dist/js/select2.min.js"></script>

<script>
$(document).ready(function () {
    $('#business_model').select2({
        placeholder: "Select Business Model",
        width: '100%'
    });
    $('#edit_business_model').select2({
        placeholder: "Select Business Model",
        width: '100%'
    });
});
</script>
<script>
document.getElementById('edit_deck').addEventListener('change', function () {
    const file = this.files[0];
    const previewBox = document.getElementById('edit_deck_preview');
    const maxSize = 2048 * 2048; // 1 MB
    if (!file) return;
    if (file.size > maxSize) {
        alert('❌ PDF size must be less than 1 MB');
        this.value = '';
        previewBox.innerHTML = '';
        return;
    }
    previewBox.innerHTML = `
        <div class="text-success fw-semibold">
            <i class="fas fa-file-pdf"></i>
            ${file.name}
        </div>
    `;
});
</script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const brandForm = document.querySelector('form[action="/brands"]');
    if (brandForm) {
        brandForm.addEventListener('submit', function () {
            const submitBtn = brandForm.querySelector('.btn-submit');
            if (submitBtn) {
                submitBtn.disabled = true;   // 🔒 disable button
                submitBtn.innerHTML = `
                    <i class="fas fa-spinner fa-spin"></i> Saving...
                `;
            }
        });
    }
});
</script>

@endsection