<!doctype html>
<html lang="en">
  <head>
    {{template "backend_head" .}}
    <style>
      /* รูปภาพสินค้า – กำหนดขนาดตั้งแต่แรกเพื่อป้องกันการกระตุกขณะโหลด */
      .pd-image-container { position: relative; width: 60px; margin: 0 auto; transition: all 0.3s; }
      .pd-img-preview { max-width: 100%; max-height: 100%; width: 60px; height: auto; border-radius: 4px; border: 1px solid #ddd; display: block; }
      .no-pd-img { width: 60px; height: 40px; background: #f0f0f0; border: 1px solid #ddd; border-radius: 4px; display: flex; align-items: center; justify-content: center; font-size: 10px; color: #aaa; }
      /* Edit Mode */
      .edit-mode .pd-image-container { border: 2px dashed #007bff; border-radius: 4px; padding: 2px; background: rgba(0,123,255,0.05); width: 70px; height: 50px; display: flex; align-items: center; justify-content: center; overflow: hidden; }
      .drop-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,123,255,0.8); color: white; display: flex; align-items: center; justify-content: center; font-size: 10px; z-index: 10; pointer-events: none; border-radius: 4px; }
      .drag-over .drop-overlay { display: flex !important; }
    </style>
  </head>
  <body class="layout-fixed sidebar-expand-lg sidebar-open bg-body-tertiary">
    <div class="app-wrapper">
      {{template "backend_header" .}}
      {{template "backend_menu" .}}
      <main class="app-main">
        <div class="app-content-header">
          <div class="container-fluid">
            <div class="row">
              <div class="col-sm-6"><h3 class="mb-0">รถจักรยานยนต์มือสอง (ไฟฟ้า)</h3></div>
              <div class="col-sm-6">
                <ol class="breadcrumb float-sm-end">
                  <li class="breadcrumb-item"><a href="main">หน้าหลัก</a></li>
                  <li class="breadcrumb-item active" aria-current="page">รถจักรยานยนต์มือสอง (ไฟฟ้า)</li>
                </ol>
              </div>
            </div>
          </div>
        </div>

        <div class="app-content">
          <div class="container-fluid">

            <!-- Brand Filter -->
            <div class="row">
              <div class="col-md-12">

                <!-- Brand Filter -->
                <div class="card mb-4 mt-2">
                  <div class="card-body">
                    <h6 class="fw-bold mb-3"><i class="bi bi-funnel"></i> เลือกแบรนด์</h6>
                    <div class="d-flex flex-wrap gap-2 align-items-center justify-content-between">
                      <div class="d-flex flex-wrap gap-2">
                        <button type="button" class="btn btn-outline-primary active brand-filter-btn" data-brand="">ทั้งหมด</button>
                        {{range .Brands}}
                        <button type="button" class="btn btn-outline-primary brand-filter-btn" data-brand="{{.}}">{{.}}</button>
                        {{end}}
                      </div>
                      <div class="d-flex align-items-center gap-2">
                        <button type="button" class="btn btn-outline-primary" id="btn_toggle_edit_mode">
                          <i class="bi bi-image"></i> โหมดจัดการรูปภาพ: <span id="edit_mode_status">ปิด</span>
                        </button>
                        <div class="d-flex align-items-center gap-2 d-none" id="group_bulk_actions">
                          <div class="btn-group">
                            <button type="button" class="btn btn-success text-white dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                              <i class="bi bi-eye-fill"></i> แสดงผล
                            </button>
                            <ul class="dropdown-menu">
                              <li><a class="dropdown-item btn-bulk-visibility" href="#" data-type="family" data-status="O">แสดงตระกูล</a></li>
                              <li><a class="dropdown-item btn-bulk-visibility" href="#" data-type="model" data-status="O">แสดงรุ่น</a></li>
                            </ul>
                          </div>
                          <div class="btn-group">
                            <button type="button" class="btn btn-danger dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                              <i class="bi bi-eye-slash-fill"></i> ซ่อน
                            </button>
                            <ul class="dropdown-menu">
                              <li><a class="dropdown-item btn-bulk-visibility" href="#" data-type="family" data-status="C">ซ่อนตระกูล</a></li>
                              <li><a class="dropdown-item btn-bulk-visibility" href="#" data-type="model" data-status="C">ซ่อนรุ่น</a></li>
                            </ul>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- Table -->
                <div class="card mb-4 mt-2">
                  <div class="card-body">
                    <table id="table_ev" class="table table-bordered table-hover table-striped w-100">
                      <thead style="white-space:nowrap;">
                        <tr class="align-middle bg-light">
                          <th style="width:40px; text-align:center;">เลือก <input type="checkbox" id="select_all_products">
                          </th>
                          <th style="width:50px; text-align:center;">ลำดับ</th>
                          <th>แบรนด์</th><!-- col index 2 – hidden -->
                          <th>ตระกูลรถ</th><!-- col index 3 – hidden -->
                          <th class="text-center">สถานะ</th>
                          <th style="text-align:center; width:100px;">คงเหลือ</th>
                          <th class="text-center">รหัสรุ่น</th>
                          <th class="text-center">ชื่อรุ่น / รายละเอียด</th>
                          <th class="text-center">รูปภาพ</th>
                          <th style="text-align:center;">ราคาขาย</th>
                        </tr>
                      </thead>
                      <tbody style="white-space:nowrap;">
                        {{if .Motorcycles}}
                          {{range .Motorcycles}}
                             <tr class="motor-data-row align-middle product-row" 
                                 data-tech="{{.ProductTechName}}" 
                                 data-brand="{{.BrandNo}}" 
                                 data-serie="{{.SerieNo}}" 
                                 data-fml="{{.FmlNo}}"
                                 data-model="{{.ModelName}}">
                               <td class="text-center">
                                 <input type="checkbox" class="product-select">
                               </td>
                               <td class="text-center first-col-no"><div class="mb-1">{{if le .Count 0}}<span class="badge bg-danger text-white">หมด</span>{{end}}</div></td><!-- index 1: Sequence (filled by drawCallback) -->
                               <td>{{.BrandName}}</td><!-- col index 2 hidden -->
                               <td>{{.ModelFName}}</td><!-- col index 3 hidden -->
                               <td class="text-center"><!-- index 4 -->
                                 {{if eq .PdStatus "O"}}
                                   <button type="button" class="btn btn-outline-success btn-model-toggle" 
                                            data-brand="{{.BrandNo}}" data-fml="{{.FmlNo}}" data-tech="{{.ProductTechName}}" data-serie="{{.SerieNo}}" data-status="O">
                                            รุ่น: แสดง</button>
                                 {{else}}
                                   <button type="button" class="btn btn-outline-danger btn-model-toggle" 
                                            data-brand="{{.BrandNo}}" data-fml="{{.FmlNo}}" data-tech="{{.ProductTechName}}" data-serie="{{.SerieNo}}" data-status="C">
                                            รุ่น: ซ่อน</button>
                                 {{end}}
                                 <div class="d-none fml-status-hidden">{{.FmlStatus}}</div> 
                                 <div class="d-none fml-no-hidden">{{.FmlNo}}</div>
                                 <div class="d-none brand-no-hidden">{{.BrandNo}}</div> 
                                 <div class="d-none serie-no-hidden">{{.SerieNo}}</div>
                               </td>
                               <td class="text-center {{if le .Count 0}}text-danger fw-bold{{end}}">{{.Count}}</td><!-- index 5 -->
                               <td class="{{if le .Count 0}}text-danger fw-bold{{end}}">{{.ProductTechName}}</td><!-- index 6 -->
                               <td class="{{if le .Count 0}}text-danger fw-bold{{end}}">{{.ModelName}}</td><!-- index 7 -->
                               <td class="text-center"><!-- index 9 -->
                                 <div class="pd-image-container" 
                                      data-tech="{{.ProductTechName}}" 
                                      data-brand="{{.BrandNo}}" 
                                      data-serie="{{.SerieNo}}" 
                                      data-fml="{{.FmlNo}}"
                                    data-model="{{.ModelName}}">
                                   {{if .PdImg}}
                                     <a href="/images/{{.PdImg}}" target="_blank"><img src="/images/{{.PdImg}}" alt="{{.ModelName}}" class="pd-img-preview"></a>
                                   {{else}}
                                     <div class="no-pd-img">No Image</div>
                                   {{end}}
                                   <div class="drop-overlay d-none">วางที่นี่</div>
                                 </div>
                               </td>
                               <td class="text-end text-success fw-bold pe-4"><!-- index 10 -->
                                 {{if gt .Price 0.0}}{{formatNumber .Price}}{{else}}-{{end}}
                               </td>
                             </tr>
                          {{end}}
                        {{else}}
                          <tr><td colspan="8" class="text-center text-muted py-5">ไม่พบข้อมูล</td></tr>
                        {{end}}
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>

          </div>
        </div>
      </main>
      <footer class="app-footer">{{template "backend_footer" .}}</footer>
    </div>

    <!-- Modal Select Product Type -->
    <div class="modal fade" id="modal_select_type" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">เลือกประเภทรถ</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="row g-3">
              {{range .ProductTypes}}
              <div class="col-md-4">
                <button type="button" class="btn btn-outline-info w-100 py-3 btn-type-option" 
                        data-no="{{.PtNo}}" data-name="{{.PtName}}">
                  {{.PtName}}
                </button>
              </div>
              {{end}}
            </div>
          </div>
        </div>
      </div>
    </div>


    {{template "backend_js" .}}
    {{template "datatable_code" .}}

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

      var openFamilies = {}; // track which families are open: "BrandName||FamilyName" -> true/false
      var isImageEditMode = false;
      var selectionMap = {}; // key: "brand||serie||tech" -> bool

      function getRowKey($row) {
        return String($row.data('brand')) + '||' + String($row.data('serie')) + '||' + String($row.data('tech'));
      }

      // CSS for image sizing moved to <head> <style> to prevent flash of large images on load

      var table = $('#table_ev').DataTable({
        scrollY: '590px',
        scrollX: true,
        scrollCollapse: true,
        paging: false,
        autoWidth: false,
        order: [[2, 'asc'], [3, 'asc']],
        language: { url: 'https://cdn.datatables.net/plug-ins/1.13.8/i18n/th.json' },
        columnDefs: [
          { targets: [2, 3], visible: false }, // hide Brand and Family helper columns
          { orderable: false, targets: [0, 1, 8] }  // Disable sorting for checkbox, no, and image
        ],
        drawCallback: function (settings) {
          var api = this.api();
          var rows = api.rows({ page: 'current' }).nodes();
          var lastBrand = null;
          var lastFamily = null;
          var rowCounter = 1;

          // Remove previously injected group rows
          $(api.table().body()).find('.brand-group-row, .family-group-row').remove();

          // Pre-calculate family totals from current visible rows
          var familyTotals = {};
          var familyCounts = {};
          var familyStatus = {};
          var familyIds    = {};
          var familySelectedCounts = {};
          api.rows({ page: 'current' }).every(function () {
            var d = this.data();
            var brand = d[2];
            var fam   = d[3];
            var cnt   = parseInt(d[5]) || 0;
            var key   = brand + '||' + fam;
            familyTotals[key] = (familyTotals[key] || 0) + cnt;
            familyCounts[key] = (familyCounts[key] || 0) + 1;
            if (selectionMap[getRowKey($(this.node()))]) {
                familySelectedCounts[key] = (familySelectedCounts[key] || 0) + 1;
            }
            
            // Read metadata from the status cell's HTML directly from internal data d[4]
            var $htmlCell = $('<div>').html(d[4]);
            var statusVal = $htmlCell.find('.fml-status-hidden').text().trim();
            var fmlNoVal  = $htmlCell.find('.fml-no-hidden').text().trim();
            var brandNoVal = $htmlCell.find('.brand-no-hidden').text().trim();
            var serieNoVal = $htmlCell.find('.serie-no-hidden').text().trim();

            if (statusVal) familyStatus[key] = statusVal;
            if (fmlNoVal && brandNoVal) {
                familyIds[key] = { fmlNo: fmlNoVal, brandNo: brandNoVal, serieNo: serieNoVal };
            }
          });

          api.column(2, { page: 'current' }).data().each(function (brand, i) {
            var fam  = api.cell($(rows).eq(i), 3).data();
            var key  = brand + '||' + fam;
            // Default to TRUE if not explicitly set to FALSE, so rows start OPEN
            var isOpen = openFamilies[key] === undefined ? true : openFamilies[key];
            var $row = $(rows).eq(i);
            var $brandHeader = null;

            // ---- Brand header ----
            if (lastBrand !== brand) {
              $brandHeader = $(
                '<tr class="brand-group-row">' +
                  '<td colspan="8" class="bg-primary text-white fw-bold"><i class="bi bi-tag-fill me-1"></i> แบรนด์: ' + brand + '</td>' +
                '</tr>'
              );
              $row.before($brandHeader);
              lastBrand = brand;
              lastFamily = null;
              rowCounter = 1;
            }

            // ---- Family header ----
            if (lastFamily !== fam) {
              var total  = familyTotals[key] || 0;
              var mCount = familyCounts[key] || 0;
              var selectedCount = familySelectedCounts[key] || 0;
              var isGroupChecked = (mCount > 0 && selectedCount === mCount) ? 'checked' : '';
              var $famHeader = $(
                '<tr class="family-group-row group-header align-middle bg-light" style="cursor:pointer;" data-key="' + key.replace(/"/g, '&quot;') + '" data-brand="' + familyIds[key].brandNo + '" data-fml="' + familyIds[key].fmlNo + '">' +
                  '<td style="width:40px;" class="text-center"><input type="checkbox" class="group-select" ' + isGroupChecked + '></td>' +
                  '<td style="width:50px;" class="text-center">' + (rowCounter++) + '.</td>' +
                  '<td class="text-center">' +
                    '<button type="button" class="btn ' + (familyStatus[key] === "O" ? "btn-success" : "btn-danger") + ' btn-fml-toggle" ' +
                            'data-brand="' + familyIds[key].brandNo + '" ' +
                            'data-fml="'   + familyIds[key].fmlNo   + '" ' +
                            'data-serie="' + familyIds[key].serieNo + '" ' +
                            'data-status="' + familyStatus[key] + '">ตระกูล: ' + (familyStatus[key] === "O" ? "แสดง" : "ซ่อน") + '</button>' +
                  '</td>' +
                  '<td class="text-center"><button type="button" class="btn btn-primary" style="min-width:100px;">' + total + ' คัน</button></td>' +
                  '<td colspan="4" class="ps-3 py-3">' +
                    '<div class="d-flex align-items-center w-100">' +
                      '<span class="toggle-btn me-2">' + (isOpen ? '▼' : '▶') + '</span>' +
                      '<div class="d-flex justify-content-between align-items-center w-100 pe-3">' +
                        '<div>' +
                          '<strong class="fs-6 text-primary">' + brand + ' ' + '</strong>' +
                          ' <span class="text-primary small">(' + mCount + ' รุ่น)</span>' +
                        '</div>' +
                      '</div>' +
                    '</div>' +
                  '</td>' +
                '</tr>'
              );
              $row.before($famHeader);
              lastFamily = fam;
            }

            // ---- Show/hide detail rows ----
            $row.addClass('detail-row');
            if (!isOpen) {
              $row.addClass('d-none');
            } else {
              $row.removeClass('d-none');
            }

            // Set indentation/placeholder for sequence column
            var seqCell = $row.find('td:eq(1)');
            if (seqCell.text().trim() === '') {
              seqCell.addClass('ps-4 text-muted').text('');
            }
            // Restore checkbox state from selectionMap
            var rowKey = getRowKey($row);
            $row.find('.product-select').prop('checked', !!selectionMap[rowKey]);
          });
        }
      });

      function updateBulkActionsUI() {
          var count = 0;
          Object.keys(selectionMap).forEach(function(k) { if (selectionMap[k]) count++; });
          $('#selected_count').text(count);
          if (count > 0) {
              $('#group_bulk_actions').removeClass('d-none');
          } else {
              $('#group_bulk_actions').addClass('d-none');
          }
      }

      // Checkbox Logic (Robust Selection & Persistence via selectionMap)
      $('#select_all_products').on('change', function() {
          var checked = this.checked;
          table.rows({ filter: 'applied' }).every(function() {
              selectionMap[getRowKey($(this.node()))] = checked;
          });
          table.draw(false);
          updateBulkActionsUI();
      });

      $('#table_ev tbody').on('change', '.product-select', function() {
          var $row = $(this).closest('tr');
          var key = getRowKey($row);
          var isChecked = this.checked;
          selectionMap[key] = isChecked;
          $(this).prop('checked', isChecked);
          updateBulkActionsUI();

          var allVisibleChecked = true;
          table.rows({ filter: 'applied' }).every(function() {
              if (!selectionMap[getRowKey($(this.node()))]) allVisibleChecked = false;
          });
          $('#select_all_products').prop('checked', allVisibleChecked);
      });

      $('#table_ev tbody').on('change', '.group-select', function() {
          var checked = this.checked;
          var groupHeader = $(this).closest('tr');
          var brand = String(groupHeader.data('brand'));
          var fml = String(groupHeader.data('fml'));

          table.rows().every(function() {
              var $node = $(this.node());
              if (String($node.data('brand')) === brand && String($node.data('fml')) === fml) {
                  selectionMap[getRowKey($node)] = checked;
              }
          });
          table.draw(false);
          updateBulkActionsUI();
      });

      // Bulk Visibility
      $('.btn-bulk-visibility').on('click', function(e) {
        e.preventDefault();
        var type = $(this).data('type'); 
        var status = $(this).data('status');
        var statusLabel = (status === 'O' ? 'แสดง' : 'ซ่อน');
        var typeLabel = (type === 'family' ? 'ตระกูล' : 'รุ่น');

        var selected = [];
        table.rows().every(function() {
            var $node = $(this.node());
            if (selectionMap[getRowKey($node)]) {
                selected.push({
                    tech:  String($node.data('tech')),
                    brand: String($node.data('brand')),
                    serie: String($node.data('serie')),
                    fml:   String($node.data('fml'))
                });
            }
        });

        if (selected.length === 0) return;

        if (!confirm('ยืนยัน' + statusLabel + typeLabel + ' ทั้งหมด ' + selected.length + ' รายการที่เลือก?')) return;

        var apiUrl = (type === 'family' ? '/api/bulk_update_family_status' : '/api/bulk_update_model_status');

        $.ajax({
          url: apiUrl,
          method: 'POST',
          contentType: 'application/json',
          data: JSON.stringify({ status: status, products: selected }),
          success: function(res) {
            if (res.success) {
              if (type === 'family') {
                  table.rows().every(function() {
                      var d = this.data();
                      var $h = $('<div>').html(d[4]);
                      var bHidden = $h.find('.brand-no-hidden').text().trim();
                      var fHidden = $h.find('.fml-no-hidden').text().trim();
                      var match = selected.some(function(s) {
                          return String(s.brand) === bHidden && String(s.fml) === fHidden;
                      });
                      if (match) {
                          $h.find('.fml-status-hidden').text(status);
                          d[4] = $h.html();
                          this.data(d);
                      }
                  });
              } else {
                  $('.product-select:checked').each(function() {
                      var rowIdx = table.row($(this).closest('tr')).index();
                      var d = table.row(rowIdx).data();
                      var $h = $('<div>').html(d[4]);
                      var $btn = $h.find('.btn-model-toggle');
                      $btn.data('status', status);
                      if (status === 'O') {
                          $btn.removeClass('btn-outline-danger').addClass('btn-outline-success').text('รุ่น: แสดง').attr('data-status', 'O');
                      } else {
                          $btn.removeClass('btn-outline-success').addClass('btn-outline-danger').text('รุ่น: ซ่อน').attr('data-status', 'C');
                      }
                      d[4] = $h.html();
                      table.row(rowIdx).data(d);
                  });
              }
               table.draw(false);
               // Clear selection state after success
               selectionMap = {};
               $('#select_all_products').prop('checked', false);
               updateBulkActionsUI();
              alert('ดำเนินการสำเร็จ');
            } else {
              alert('เกิดข้อผิดพลาด: ' + res.message);
            }
          },
          error: function(xhr) {
            console.error('Bulk Visibility Error:', xhr);
            alert('ไม่สามารถเชื่อมต่อ Server ได้ (Status: ' + xhr.status + ') ' + (xhr.responseJSON ? xhr.responseJSON.message : ''));
          }
        });
      });

      // Recalculate column widths on initialization to ensure alignment
      setTimeout(function() {
          table.columns.adjust();
      }, 500);

      // Recalculate column widths when sidebar is toggled
      $(document).on('click', '[data-lte-toggle="sidebar"]', function() {
        setTimeout(function() {
          table.columns.adjust();
        }, 300);
      });
      
      // Recalculate column widths on window resize and orientation change (for mobile)
      $(window).on('resize orientationchange', function() {
        table.columns.adjust();
      });

      // Toggle family rows on click
      $('#table_used_ev tbody').on('click', '.family-group-row', function (e) {
        if ($(e.target).closest('.btn-fml-toggle').length || $(e.target).closest('.group-select').length) return; // ignore if button or checkbox clicked
        var key = $(this).data('key');
        openFamilies[key] = (openFamilies[key] === undefined ? true : openFamilies[key]); // ensure it's set
        openFamilies[key] = !openFamilies[key];
        table.draw(false);
      });

      // Update Family Status logic
      $('#table_ev tbody').on('click', '.btn-fml-toggle', function (e) {
        e.stopPropagation();
        var $btn      = $(this);
        var brandNo   = $btn.data('brand');
        var fmlNo     = $btn.data('fml');
        var curStatus = $btn.data('status');
        var nextStatus = (curStatus === 'O' ? 'C' : 'O');

        if (!confirm('ยืนยันการเปลี่ยนสถานะการมองเห็นของตระกูลนี้?')) return;

        $.post('/api/update_family_status', {
           BRAND_NO: brandNo,
           FML_NO: fmlNo,
           SERIE_NO: $btn.data('serie'),
           NEW_STATUS: nextStatus
        }, function(res) {
           if (res.success) {
              console.log('Update success, refreshing UI for:', brandNo, fmlNo, nextStatus);
              // Update ALL matching underlying rows in DataTables internal memory
              table.rows().every(function() {
                 var d = this.data();
                 var $h = $('<div>').html(d[4]);
                 var bHidden = $h.find('.brand-no-hidden').text().trim();
                 var fHidden = $h.find('.fml-no-hidden').text().trim();
                 
                 if (bHidden === String(brandNo) && fHidden === String(fmlNo)) {
                    $h.find('.fml-status-hidden').text(nextStatus);
                    d[4] = $h.html();
                    this.data(d); // Force update row memory
                 }
              });
              // Force redraw without reset
              table.draw(false); 
           } else {
              alert('เกิดข้อผิดพลาด: ' + res.message);
           }
        }).fail(function(err) {
           console.error('AJAX Error:', err);
           alert('ไม่สามารถเชื่อมต่อ Server ได้');
         });
      });

      // Update Model Status logic
      $('#table_ev tbody').on('click', '.btn-model-toggle', function (e) {
        e.stopPropagation();
        var $btn      = $(this);
        var brandNo   = $btn.data('brand');
        var fmlNo     = $btn.data('fml');
        var techName  = $btn.data('tech');
        var curStatus = $btn.data('status');
        var nextStatus = (curStatus === 'O' ? 'C' : 'O');

        if (!confirm('ยืนยันการเปลี่ยนสถานะการมองเห็นของรุ่นนี้?')) return;

        $.post('/api/update_model_status', {
           BRAND_NO: brandNo,
           FML_NO: fmlNo,
           PRODUCT_TECHNAME: techName,
           SERIE_NO: $btn.data('serie'),
           NEW_STATUS: nextStatus
        }, function(res) {
           if (res.success) {
              console.log('Model update success:', techName, nextStatus);
              // Update button UI instantly
              $btn.data('status', nextStatus);
               if (nextStatus === 'O') {
                  $btn.removeClass('btn-outline-danger').addClass('btn-outline-success').text('รุ่น: แสดง');
               } else {
                  $btn.removeClass('btn-outline-success').addClass('btn-outline-danger').text('รุ่น: ซ่อน');
               }
              // Also update DataTables internal memory for this specific row so it persists on redraw
              var rowIdx = table.row($btn.closest('tr')).index();
              var d = table.row(rowIdx).data();
              var $h = $('<div>').html(d[4]);
              $h.find('.btn-model-toggle').data('status', nextStatus); 
              if (nextStatus === 'O') {
                 $h.find('.btn-model-toggle').removeClass('btn-outline-danger').addClass('btn-outline-success').text('รุ่น: แสดง').attr('data-status', 'O');
              } else {
                 $h.find('.btn-model-toggle').removeClass('btn-outline-success').addClass('btn-outline-danger').text('รุ่น: ซ่อน').attr('data-status', 'C');
              }
              d[4] = $h.html();
              table.row(rowIdx).data(d); 
           } else {
              alert('เกิดข้อผิดพลาด: ' + res.message);
           }
        }).fail(function(err) {
           alert('ไม่สามารถเชื่อมต่อ Server ได้');
        });
      });

      // Brand filter buttons
      $('.brand-filter-btn').on('click', function () {
        var brand = $(this).data('brand');
        $('.brand-filter-btn').removeClass('active');
        $(this).addClass('active');

        if (brand === '') {
          table.column(2).search('').draw(false);
        } else {
          table.column(2).search('^' + brand + '$', true, false).draw(false);
        }
        
        // Recalculate columns after filtering to ensure alignment
        setTimeout(function() {
          table.columns.adjust();
        }, 100);

        // Re-expand all when switching brand
        openFamilies = {};
      });

      // Toggle Image Edit Mode
      $('#btn_toggle_edit_mode').on('click', function() {
          isImageEditMode = !isImageEditMode;
          $(this).toggleClass('btn-outline-primary btn-primary');
          $('#edit_mode_status').text(isImageEditMode ? 'เปิด' : 'ปิด');
          $('#table_ev').toggleClass('edit-mode', isImageEditMode);
      });

      // Drag & Drop Handlers
      $(document).on('dragover', '.edit-mode .pd-image-container', function(e) {
          e.preventDefault();
          $(this).addClass('drag-over');
      });

      $(document).on('dragleave', '.edit-mode .pd-image-container', function(e) {
          e.preventDefault();
          $(this).removeClass('drag-over');
      });

      $(document).on('drop', '.edit-mode .pd-image-container', function(e) {
          e.preventDefault();
          var $container = $(this);
          $container.removeClass('drag-over');
          
          var files = e.originalEvent.dataTransfer.files;
          if (files.length === 0) return;
          
          var file = files[0];
          if (!file.type.match('image.*')) {
              alert('กรุณาเลือกไฟล์รูปภาพเท่านั้น');
              return;
          }

          var formData = new FormData();
          formData.append('image', file);
          formData.append('tech',  String($container.data('tech')));
          formData.append('brand', String($container.data('brand')));
          formData.append('serie', String($container.data('serie')));
          formData.append('fml',   String($container.data('fml')));
          formData.append('model', String($container.data('model')));

          // Visual feedback - loading
          $container.find('.drop-overlay').removeClass('d-none').text('กําลังบันทึก...');

          $.ajax({
              url: '/api/upload_product_image',
              type: 'POST',
              data: formData,
              processData: false,
              contentType: false,
              success: function(res) {
                  if (res.status === 'success') {
                      var newSrc = '/images/' + res.filename + '?t=' + new Date().getTime();
                      if ($container.find('img').length > 0) {
                          $container.find('img').attr('src', newSrc);
                          $container.find('a').attr('href', newSrc);
                      } else {
                          $container.find('.no-pd-img').remove();
                          $container.prepend('<a href="' + newSrc + '" target="_blank"><img src="' + newSrc + '" class="pd-img-preview"></a>');
                      }
                      $container.find('.drop-overlay').addClass('d-none').text('วางที่นี่');
                  } else {
                      alert('บันทึกรูปภาพไม่สําเร็จ');
                      $container.find('.drop-overlay').addClass('d-none');
                  }
              },
              error: function() {
                  alert('เกิดข้อผิดพลาดในการเชื่อมต่อ');
                  $container.find('.drop-overlay').addClass('d-none');
              }
          });
      });


    });
    </script>
  </body>
</html>
