@extends('layouts.app')

@section('content')
@php
  // query พก agency_id ไปกับลิงก์ทุกตัว
  $qs = [];
  if (!empty($selectedAgencyId)) {
      $qs['agency_id'] = $selectedAgencyId;
  }
@endphp

<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>
            {{ __('รายการผลิตภัณฑ์') }}
          </h2>

          {{-- ผู้ใช้ทั่วไป: โชว์บริษัทเดียวของตัวเอง --}}
          @if(Auth::user()->Agency_ID && strtolower(Auth::user()->Level) !== 'consult')
            <p class="text-muted mb-0">
              <i class="fas fa-building me-1"></i>
              {{ __('บริษัท: ') . (optional(Auth::user()->agency)->Agency_Name ?? '-') }}
            </p>
          
          {{-- consult: เลือกบริษัทได้จาก dropdown --}}
          @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">{{ __('บริษัท:') }}</label>
              <select id="agency-select" class="form-select form-select-sm" onchange="changeAgency(this.value)">
                <option value="">{{ __('เลือกบริษัท') }}</option>
                @if(isset($userAgencies))
                  @foreach($userAgencies as $agency)
                    <option value="{{ $agency->Agency_ID }}" {{ $selectedAgencyId == $agency->Agency_ID ? 'selected' : '' }}>
                      {{ $agency->Agency_Name }}
                    </option>
                  @endforeach
                @endif
              </select>
            </div>
          @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>
            {{ __('ย้อนกลับ') }}
          </a>

          {{-- ปุ่มตัวกรองรายการ --}}
          @if(Auth::user()->Agency_ID || strtolower(Auth::user()->Level) === 'consult')
            <div class="btn-group" role="group">
              @if(strtolower(Auth::user()->Level) === 'consult')
                <a href="{{ route('products.index', $qs) }}"
                   class="btn btn-outline-primary {{ request()->routeIs('products.index') && !request()->has('filter') ? 'active' : '' }}">
                  <i class="fas fa-building me-1"></i>{{ __('ทั้งหมดในบริษัท') }}
                </a>
                <a href="{{ route('products.index', array_merge($qs, ['filter' => 'my'])) }}"
                   class="btn btn-outline-primary {{ request()->get('filter') == 'my' ? 'active' : '' }}">
                  <i class="fas fa-user me-1"></i>{{ __('ของฉัน') }}
                </a>
              @else
                <a href="{{ route('products.index') }}"
                   class="btn btn-outline-primary {{ request()->routeIs('products.index') && !request()->has('filter') ? 'active' : '' }}">
                  <i class="fas fa-building me-1"></i>{{ __('ทั้งหมดในบริษัท') }}
                </a>
                <a href="{{ route('products.index', ['filter' => 'my']) }}"
                   class="btn btn-outline-primary {{ request()->get('filter') == 'my' ? 'active' : '' }}">
                  <i class="fas fa-user me-1"></i>{{ __('ของฉัน') }}
                </a>
              @endif
            </div>
          @endif

          {{-- ปุ่มเพิ่มผลิตภัณฑ์ ต้องพก agency_id สำหรับ consult --}}
          <a href="{{ 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>{{ __('เพิ่มผลิตภัณฑ์') }}
          </a>
        </div>
      </div>

      {{-- Flash messages --}}
      @if(session('success'))
        <div class="alert alert-success alert-dismissible fade show" role="alert" id="auto-dismiss-alert">
          {{ session('success') }}
          <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
      @elseif(session('error') && !session('success'))
        <div class="alert alert-danger alert-dismissible fade show" role="alert" id="auto-dismiss-alert">
          {{ session('error') }}
          <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        @php session()->forget('error'); @endphp
      @endif

      {{-- Empty state --}}
      @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">{{ __('ไม่มีผลิตภัณฑ์') }}</h4>
          <p class="text-muted">
            @if(Auth::user()->Agency_ID)
              {{ __('บริษัทของคุณยังไม่มีผลิตภัณฑ์') }}
            @else
              {{ __('คุณยังไม่มีผลิตภัณฑ์') }}
            @endif
          </p>
          <a href="{{ 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>{{ __('เพิ่มผลิตภัณฑ์แรก') }}
          </a>
        </div>
      @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>
                @foreach($products as $index => $product)
                  <tr class="clickable-row" data-product-id="{{ $product->id }}">
                    <td class="text-center">{{ $index + 1 }}</td>
                    <td>
                      <strong>{{ $product->name }}</strong>
                      @if($product->description)
                        <br><small class="text-muted">{{ \Illuminate\Support\Str::limit($product->description, 50) }}</small>
                      @endif
                    </td>
                    <td>{{ $product->model ?? 'ไม่ระบุ' }}</td>
                    <td>
                      @switch($product->log_receive_method)
                        @case('syslog_udp')
                          <span class="badge bg-primary">syslog UDP</span>
                          @break
                        @case('syslog_tcp')
                          <span class="badge bg-info">syslog TCP</span>
                          @break
                        @case('syslog_both')
                          <span class="badge bg-success">syslog UDP & TCP</span>
                          @break
                        @default
                          <span class="badge bg-secondary">{{ $product->log_receive_method }}</span>
                      @endswitch
                    </td>
                    <td>
                      @if($product->product_type == 'hw_sw_log_server')
                        <span class="badge bg-warning">Hardware + Software</span>
                      @else
                        <span class="badge bg-info">Software Only</span>
                      @endif
                    </td>

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

                    <td>{{ optional($product->DtmIns)->format('d/m/Y') }}</td>

                    <td class="text-center">
                      <div class="btn-group" role="group">
                        {{-- ทำต่อ (draft) ควรพก agency_id สำหรับ consult --}}
                        @if($latestAssessment && $latestAssessment->status == 'draft')
                          <a href="{{ 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>
                        @endif

                        <a href="{{ 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;
                        @endphp
                        @if($canDelete)
                          <form action="{{ route('products.destroy', $product->id) }}" method="POST" style="display:inline" class="delete-form">
                            @csrf @method('DELETE')
                            <button type="submit" class="btn btn-sm btn-outline-danger delete-btn" data-product-name="{{ $product->name }}">
                              <i class="fas fa-trash me-1"></i>ลบ
                            </button>
                          </form>
                        @endif
                      </div>
                    </td>
                  </tr>
                @endforeach
                </tbody>
              </table>
            </div>
          </div>
        </div>
      @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 = `{{ 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>
@endsection
