@extends('asset.partials.app')

@section('content')
<div class="p-6" 
     x-data="repairForm()" 
     x-init="initSelect()">   {{-- init TomSelect + bridge --}}

  <h1 class="text-2xl font-bold mb-6 text-slate-700">Repair Center</h1>

  @if(session('success'))
    <div class="mb-4 bg-green-100 border-l-4 border-green-500 text-green-700 p-3 rounded">
      {{ session('success') }}
    </div>
  @endif

  {{-- ===================== REPAIR FORM ===================== --}}
  <form method="POST" action="{{ route('asset.repairs.store') }}" enctype="multipart/form-data"
        class="bg-white shadow p-4 rounded-xl grid md:grid-cols-6 gap-3 mb-6">
    @csrf

    {{-- Employee (Searchable) --}}
    <div class="col-span-full md:col-span-2">
      <label class="block text-xs font-semibold text-slate-500 mb-1">Employee</label>
      <select x-ref="employeeSelect" id="employeeSelect" class="border rounded-lg px-3 py-2 w-full">
        <option value="">Select Employee</option>
        @foreach($employees as $e)
          <option value="{{ $e->id }}">{{ $e->name }} ({{ $e->department->name ?? '—' }})</option>
        @endforeach
      </select>
      <p class="text-[11px] text-slate-400 mt-1">Type to search employees…</p>
    </div>

    {{-- Asset (auto-filled after employee picked) --}}
    <div class="col-span-full md:col-span-2">
      <label class="block text-xs font-semibold text-slate-500 mb-1">Asset</label>
      <select name="asset_id" required class="border rounded-lg px-3 py-2 w-full">
        <option value="">Select Asset</option>
        <template x-for="a in assets" :key="a.id">
          <option :value="a.id" x-text="`${a.asset_tag} (${a.device_type})`"></option>
        </template>
      </select>
      <template x-if="loading">
        <div class="text-xs text-slate-500 mt-1">Loading assets for selected employee…</div>
      </template>
      <template x-if="!loading && employee && assets.length===0">
        <div class="text-xs text-amber-600 mt-1">No active assets assigned to this employee.</div>
      </template>
    </div>

    {{-- Issue --}}
    <div>
      <label class="block text-xs font-semibold text-slate-500 mb-1">Issue</label>
      <input type="text" name="issue" placeholder="Describe issue" required
             class="border rounded-lg px-3 py-2 w-full focus:ring-2 focus:ring-sky-500">
    </div>

    {{-- Vendor --}}
    <div>
      <label class="block text-xs font-semibold text-slate-500 mb-1">Vendor</label>
      <input type="text" name="vendor_name" placeholder="Vendor name"
             class="border rounded-lg px-3 py-2 w-full focus:ring-2 focus:ring-sky-500">
    </div>

    {{-- Cost --}}
    <div>
      <label class="block text-xs font-semibold text-slate-500 mb-1">Cost (₹)</label>
      <input type="number" name="cost" placeholder="0.00" step="0.01"
             class="border rounded-lg px-3 py-2 w-full focus:ring-2 focus:ring-sky-500">
    </div>

    {{-- Sent Date --}}
    <div>
      <label class="block text-xs font-semibold text-slate-500 mb-1">Sent Date</label>
      <input type="date" name="sent_date"
             class="border rounded-lg px-3 py-2 w-full focus:ring-2 focus:ring-sky-500">
    </div>

    {{-- Invoice --}}
    <div class="col-span-full md:col-span-2">
      <label class="block text-xs font-semibold text-slate-500 mb-1">Invoice (PDF/JPG/PNG)</label>
      <input type="file" name="invoice" accept=".pdf,.jpg,.jpeg,.png"
             class="border rounded-lg px-3 py-2 w-full focus:ring-2 focus:ring-sky-500">
    </div>

    {{-- Submit --}}
    <div class="col-span-full md:col-span-1 flex items-end">
      <button class="bg-gradient-to-r from-amber-500 to-orange-600 text-white px-5 py-2.5 rounded-lg hover:opacity-90 font-medium w-full">
        + Log Repair
      </button>
    </div>
  </form>

  {{-- ===================== REPAIR TABLE ===================== --}}
  <div class="bg-white rounded-xl shadow overflow-hidden">
    <table class="min-w-full text-sm text-slate-700">
      <thead class="bg-gradient-to-r from-amber-600 to-orange-600 text-white">
        <tr>
          <th class="px-4 py-3 text-left">#</th>
          <th class="px-4 py-3 text-left">Asset</th>
          <th class="px-4 py-3 text-left">Issue</th>
          <th class="px-4 py-3 text-left">Vendor</th>
          <th class="px-4 py-3 text-left">Cost</th>
          <th class="px-4 py-3 text-left">Sent</th>
          <th class="px-4 py-3 text-left">Return</th>
          <th class="px-4 py-3 text-left">Status</th>
          <th class="px-4 py-3 text-left">Invoice</th>
          <th class="px-4 py-3 text-right">Actions</th>
        </tr>
      </thead>
      <tbody>
        @forelse($repairs as $i => $r)
        <tr class="border-b hover:bg-slate-50">
          <td class="px-4 py-3">{{ $repairs->firstItem() + $i }}</td>
          <td class="px-4 py-3 font-medium">{{ $r->asset->asset_tag ?? '-' }}</td>
          <td class="px-4 py-3">{{ $r->issue }}</td>
          <td class="px-4 py-3">{{ $r->vendor_name }}</td>
          <td class="px-4 py-3">₹{{ number_format($r->cost,2) }}</td>
          <td class="px-4 py-3">{{ $r->sent_date }}</td>
          <td class="px-4 py-3">{{ $r->return_date ?? '-' }}</td>
          <td class="px-4 py-3">
            @if($r->status=='In Repair')
              <span class="px-2 py-1 text-xs rounded bg-amber-100 text-amber-700 font-semibold">In Repair</span>
            @else
              <span class="px-2 py-1 text-xs rounded bg-green-100 text-green-700 font-semibold">Returned</span>
            @endif
          </td>
        
          <td class="px-4 py-3">
  @if($r->invoice_path)
    <div class="flex items-center gap-3">
      <a href="{{ route('asset.repairs.invoice.view', $r->id) }}"
         target="_blank"
         class="inline-flex items-center gap-1 text-sky-700 hover:underline">
        <i class="fa-solid fa-file-pdf"></i> View
      </a>

      <a href="{{ route('asset.repairs.invoice.download', $r->id) }}"
         class="inline-flex items-center gap-1 text-slate-700 hover:underline">
        <i class="fa-solid fa-download"></i> Download
      </a>
    </div>
  @else
    <span class="text-slate-400">—</span>
  @endif
</td>

          <td class="px-4 py-3 text-right space-x-2">
            @if($r->status == 'In Repair')
              <form method="POST" action="{{ route('asset.repairs.return',$r->id) }}" class="inline">@csrf
                <button class="text-indigo-600 hover:underline">Mark Returned</button>
              </form>
            @endif
            <form method="POST" action="{{ route('asset.repairs.destroy',$r->id) }}" class="inline">
              @csrf @method('DELETE')
              <button onclick="return confirm('Delete repair record?')" class="text-red-600 hover:underline">Delete</button>
            </form>
          </td>
        </tr>
        @empty
          <tr><td colspan="10" class="text-center py-4 text-slate-500">No repair records yet.</td></tr>
        @endforelse
      </tbody>
    </table>
    <div class="p-4 border-t bg-slate-50">
      {{ $repairs->links('pagination::tailwind') }}
    </div>
  </div>
</div>

@push('scripts')
<script>
function repairForm() {
  return {
    employee: '',      // selected employee id
    assets: [],        // assets for that employee
    loading: false,

    initSelect() {
      // Initialize TomSelect and bridge to Alpine
      if (window.TomSelect) {
        const ts = new TomSelect(this.$refs.employeeSelect, {
          create: false,
          maxOptions: 5000,
          placeholder: 'Search employee…',
          sortField: { field: 'text', direction: 'asc' }
        });
        ts.on('change', (val) => {
          this.employee = val || '';
          this.loadAssets();
        });
      }
    },

    async loadAssets() {
      this.assets = [];
      if (!this.employee) return;
      this.loading = true;
      try {
        const res = await fetch(`/asset/repairs/assets/${this.employee}`);
        const data = await res.json();
        this.assets = Array.isArray(data) ? data : [];
      } catch (err) {
        console.error(err);
        alert('Failed to load assets for employee.');
      } finally {
        this.loading = false;
      }
    }
  }
}
</script>
@endpush

@endsection
