<?php $__env->startSection('content'); ?>
<?php
  // query พก agency_id ไปกับลิงก์ทุกตัว
  $qs = [];
  if (!empty($selectedAgencyId)) {
      $qs['agency_id'] = $selectedAgencyId;
  }
?>

<div class="container mt-4">
  <div class="row">
    <div class="col-12">
      <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
          <h2 class="mb-0">
            <i class="fas fa-boxes me-2"></i>
            <?php echo e(__('รายการผลิตภัณฑ์')); ?>

          </h2>

          
          <?php if(Auth::user()->Agency_ID && strtolower(Auth::user()->Level) !== 'consult'): ?>
            <p class="text-muted mb-0">
              <i class="fas fa-building me-1"></i>
              <?php echo e(__('บริษัท: ') . (optional(Auth::user()->agency)->Agency_Name ?? '-')); ?>

            </p>
          
          
          <?php elseif(strtolower(Auth::user()->Level) === 'consult'): ?>
            <div class="d-flex align-items-center">
              <i class="fas fa-user-tie me-2"></i>
              <label for="agency-select" class="form-label mb-0 me-2"><?php echo e(__('บริษัท:')); ?></label>
              <select id="agency-select" class="form-select form-select-sm" onchange="changeAgency(this.value)">
                <option value=""><?php echo e(__('เลือกบริษัท')); ?></option>
                <?php if(isset($userAgencies)): ?>
                  <?php $__currentLoopData = $userAgencies; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $agency): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <option value="<?php echo e($agency->Agency_ID); ?>" <?php echo e($selectedAgencyId == $agency->Agency_ID ? 'selected' : ''); ?>>
                      <?php echo e($agency->Agency_Name); ?>

                    </option>
                  <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                <?php endif; ?>
              </select>
            </div>
          <?php endif; ?>
        </div>

        <div class="d-flex gap-2">
          <a href="http://203.185.101.206/ServTrack/indexUser.php" class="btn btn-outline-secondary me-2">
            <i class="fas fa-arrow-left me-1"></i>
            <?php echo e(__('ย้อนกลับ')); ?>

          </a>

          
          <?php if(Auth::user()->Agency_ID || strtolower(Auth::user()->Level) === 'consult'): ?>
            <div class="btn-group" role="group">
              <?php if(strtolower(Auth::user()->Level) === 'consult'): ?>
                <a href="<?php echo e(route('products.index', $qs)); ?>"
                   class="btn btn-outline-primary <?php echo e(request()->routeIs('products.index') && !request()->has('filter') ? 'active' : ''); ?>">
                  <i class="fas fa-building me-1"></i><?php echo e(__('ทั้งหมดในบริษัท')); ?>

                </a>
                <a href="<?php echo e(route('products.index', array_merge($qs, ['filter' => 'my']))); ?>"
                   class="btn btn-outline-primary <?php echo e(request()->get('filter') == 'my' ? 'active' : ''); ?>">
                  <i class="fas fa-user me-1"></i><?php echo e(__('ของฉัน')); ?>

                </a>
              <?php else: ?>
                <a href="<?php echo e(route('products.index')); ?>"
                   class="btn btn-outline-primary <?php echo e(request()->routeIs('products.index') && !request()->has('filter') ? 'active' : ''); ?>">
                  <i class="fas fa-building me-1"></i><?php echo e(__('ทั้งหมดในบริษัท')); ?>

                </a>
                <a href="<?php echo e(route('products.index', ['filter' => 'my'])); ?>"
                   class="btn btn-outline-primary <?php echo e(request()->get('filter') == 'my' ? 'active' : ''); ?>">
                  <i class="fas fa-user me-1"></i><?php echo e(__('ของฉัน')); ?>

                </a>
              <?php endif; ?>
            </div>
          <?php endif; ?>

          
          <a href="<?php echo e(strtolower(Auth::user()->Level) === 'consult' ? route('products.create-new', $qs) : route('products.create-new')); ?>"
             class="btn btn-primary">
            <i class="fas fa-plus me-1"></i><?php echo e(__('เพิ่มผลิตภัณฑ์')); ?>

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

      
      <?php if(session('success')): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert" id="auto-dismiss-alert">
          <?php echo e(session('success')); ?>

          <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
      <?php elseif(session('error') && !session('success')): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert" id="auto-dismiss-alert">
          <?php echo e(session('error')); ?>

          <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php session()->forget('error'); ?>
      <?php endif; ?>

      
      <?php if($products->isEmpty()): ?>
        <div class="text-center py-5">
          <i class="fas fa-box-open fa-3x text-muted mb-3"></i>
          <h4 class="text-muted"><?php echo e(__('ไม่มีผลิตภัณฑ์')); ?></h4>
          <p class="text-muted">
            <?php if(Auth::user()->Agency_ID): ?>
              <?php echo e(__('บริษัทของคุณยังไม่มีผลิตภัณฑ์')); ?>

            <?php else: ?>
              <?php echo e(__('คุณยังไม่มีผลิตภัณฑ์')); ?>

            <?php endif; ?>
          </p>
          <a href="<?php echo e(strtolower(Auth::user()->Level) === 'consult' ? route('products.create-new', $qs) : route('products.create-new')); ?>"
             class="btn btn-primary">
            <i class="fas fa-plus me-1"></i><?php echo e(__('เพิ่มผลิตภัณฑ์แรก')); ?>

          </a>
        </div>
      <?php else: ?>

        <div class="card shadow-sm">
          <div class="card-body p-0">
            <div class="table-responsive">
              <table class="table table-hover mb-0">
                <thead class="table-dark">
                  <tr>
                    <th class="text-center" style="width: 50px;">ลำดับ</th>
                    <th style="width: 200px;">ชื่อผลิตภัณฑ์</th>
                    <th style="width: 150px;">โมเดล/รุ่น</th>
                    <th style="width: 150px;">วิธีรับข้อมูล</th>
                    <th style="width: 150px;">ประเภทผลิตภัณฑ์</th>
                    <th style="width: 120px;">สถานะการประเมิน</th>
                    <th style="width: 100px;">วันที่สร้าง</th>
                    <th class="text-center" style="width: 200px;">การดำเนินการ</th>
                  </tr>
                </thead>
                <tbody>
                <?php $__currentLoopData = $products; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $product): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                  <tr class="clickable-row" data-product-id="<?php echo e($product->id); ?>">
                    <td class="text-center"><?php echo e($index + 1); ?></td>
                    <td>
                      <strong><?php echo e($product->name); ?></strong>
                      <?php if($product->description): ?>
                        <br><small class="text-muted"><?php echo e(\Illuminate\Support\Str::limit($product->description, 50)); ?></small>
                      <?php endif; ?>
                    </td>
                    <td><?php echo e($product->model ?? 'ไม่ระบุ'); ?></td>
                    <td>
                      <?php switch($product->log_receive_method):
                        case ('syslog_udp'): ?>
                          <span class="badge bg-primary">syslog UDP</span>
                          <?php break; ?>
                        <?php case ('syslog_tcp'): ?>
                          <span class="badge bg-info">syslog TCP</span>
                          <?php break; ?>
                        <?php case ('syslog_both'): ?>
                          <span class="badge bg-success">syslog UDP & TCP</span>
                          <?php break; ?>
                        <?php default: ?>
                          <span class="badge bg-secondary"><?php echo e($product->log_receive_method); ?></span>
                      <?php endswitch; ?>
                    </td>
                    <td>
                      <?php if($product->product_type == 'hw_sw_log_server'): ?>
                        <span class="badge bg-warning">Hardware + Software</span>
                      <?php else: ?>
                        <span class="badge bg-info">Software Only</span>
                      <?php endif; ?>
                    </td>

                    <td>
                      <?php $latestAssessment = $product->assessments()->latest()->first(); ?>
                      <?php if($latestAssessment): ?>
                        <?php if($latestAssessment->status == 'draft'): ?>
                          <span class="badge bg-warning"><i class="fas fa-save me-1"></i>ฉบับร่าง</span>
                        <?php elseif($latestAssessment->status == 'submitted'): ?>
                          <span class="badge bg-success"><i class="fas fa-check me-1"></i>ส่งแล้ว</span>
                        <?php else: ?>
                          <span class="badge bg-secondary"><i class="fas fa-clock me-1"></i><?php echo e($latestAssessment->status); ?></span>
                        <?php endif; ?>
                      <?php else: ?>
                        <span class="badge bg-light text-dark"><i class="fas fa-times me-1"></i>ยังไม่ประเมิน</span>
                      <?php endif; ?>
                    </td>

                    <td><?php echo e(optional($product->DtmIns)->format('d/m/Y')); ?></td>

                    <td class="text-center">
                      <div class="btn-group" role="group">
                        
                        <?php if($latestAssessment && $latestAssessment->status == 'draft'): ?>
                          <a href="<?php echo e(route('assessments.continue-draft', array_merge(['product'=>$product->id], $qs))); ?>"
                             class="btn btn-sm btn-warning">
                            <i class="fas fa-play me-1"></i>ทำต่อ
                          </a>
                        <?php endif; ?>

                        <a href="<?php echo e(route('products.report', $product->id)); ?>" class="btn btn-sm btn-outline-info">
                          <i class="fas fa-chart-bar me-1"></i>รายงาน
                        </a>

                        
                        <?php
                          $user = Auth::user();
                          $canDelete = false;
                          if($user->Customer_ID === $product->Customer_ID) $canDelete = true;
                          elseif(in_array(strtolower($user->Level), ['admin','superadmin'])) $canDelete = true;
                          elseif($user->Agency_ID && $product->user && $product->user->Agency_ID && $user->Agency_ID === $product->user->Agency_ID) $canDelete = true;
                        ?>
                        <?php if($canDelete): ?>
                          <form action="<?php echo e(route('products.destroy', $product->id)); ?>" method="POST" style="display:inline" class="delete-form">
                            <?php echo csrf_field(); ?> <?php echo method_field('DELETE'); ?>
                            <button type="submit" class="btn btn-sm btn-outline-danger delete-btn" data-product-name="<?php echo e($product->name); ?>">
                              <i class="fas fa-trash me-1"></i>ลบ
                            </button>
                          </form>
                        <?php endif; ?>
                      </div>
                    </td>
                  </tr>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<style>
  .clickable-row { cursor: pointer; transition: all .2s ease; }
  .clickable-row:hover { background-color:#f8f9fa!important; transform: translateY(-1px); box-shadow:0 2px 4px rgba(0,0,0,.1) }
  .clickable-row td { border-color:#dee2e6; transition: border-color .2s ease }
  .clickable-row:hover td { border-color:#adb5bd }
  .clickable-row:active { transform: translateY(0); box-shadow:0 1px 2px rgba(0,0,0,.1) }
</style>

<script>
  document.addEventListener('DOMContentLoaded', () => {
    const alertEl = document.getElementById('auto-dismiss-alert');
    if (alertEl) {
      setTimeout(() => {
        alertEl.classList.remove('show');
        setTimeout(() => alertEl.remove(), 500);
      }, 5000);
    }

    // confirm delete
    document.querySelectorAll('.delete-form').forEach(form => {
      form.addEventListener('submit', function(e) {
        e.preventDefault();
        const productName = this.querySelector('.delete-btn').dataset.productName;
        if (confirm(`คุณต้องการลบข้อมูลผลิตภัณฑ์ "${productName}" และผลการประเมินนี้หรือไม่?`)) {
          this.submit();
        }
      });
    });

    // คลิกทั้งแถว -> ไปหน้ารายงาน (ถ้าไม่ได้กดปุ่ม/ลิงก์ภายใน)
    document.querySelectorAll('.clickable-row').forEach(row => {
      row.addEventListener('click', function(e) {
        if (e.target.closest('a,button,form')) return;
        const id = this.dataset.productId;
        if (id) window.location.href = `<?php echo e(route('products.report', ':id')); ?>`.replace(':id', id);
      });
    });
  });

  // เปลี่ยนบริษัทแล้วรีโหลดด้วย ?agency_id=...
  function changeAgency(agencyId) {
    const url = new URL(window.location);
    if (agencyId) url.searchParams.set('agency_id', agencyId);
    else url.searchParams.delete('agency_id');
    url.searchParams.delete('filter');
    window.location.href = url.toString();
  }
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\laravel-project\resources\views/products/index.blade.php ENDPATH**/ ?>