@extends('layouts.app')
@section('title','Employees')
@section('page-title','Employees')

@section('content')
@include('partials.employee-achievement', ['employees' => $employees])
<div class="page-hd">
  <div><h2>👥 Employees</h2><p>Manage your sales team</p></div>
  <div class="page-hd-right">
    <a href="{{ route('employees.export') }}" class="btn btn-out btn-sm">📥 CSV</a>
    <button class="btn btn-pri btn-sm" onclick="openEmpModal()">+ Add Employee</button>
  </div>
</div>

<!-- KPI Cards -->
<!-- <div class="metrics" style="grid-template-columns:repeat(4,1fr);margin-bottom:16px">
  @php
  $total = $employees->count();
  $active = $employees->where('status','Active')->count();
  $totalLeads = $employees->sum(fn($e)=>$e->leads->count());
  $totalWon = $employees->sum(fn($e)=>$e->leads->where('stage','Won')->count());
  @endphp
  <div class="mc">
    <div style="position:absolute;top:0;left:0;right:0;height:4px;background:#1a73e8;border-radius:12px 12px 0 0"></div>
    <div class="mc-ico" style="background:#e8f0fe">👥</div>
    <div class="mc-val">{{ $total }}</div><div class="mc-lbl">Total</div>
  </div>
  <div class="mc">
    <div style="position:absolute;top:0;left:0;right:0;height:4px;background:#10b981;border-radius:12px 12px 0 0"></div>
    <div class="mc-ico" style="background:#d1fae5">✅</div>
    <div class="mc-val">{{ $active }}</div><div class="mc-lbl">Active</div>
  </div>
  <div class="mc">
    <div style="position:absolute;top:0;left:0;right:0;height:4px;background:#f59e0b;border-radius:12px 12px 0 0"></div>
    <div class="mc-ico" style="background:#fef3c7">🎯</div>
    <div class="mc-val">{{ $totalLeads }}</div><div class="mc-lbl">Leads Assigned</div>
  </div>
  <div class="mc">
    <div style="position:absolute;top:0;left:0;right:0;height:4px;background:#7c3aed;border-radius:12px 12px 0 0"></div>
    <div class="mc-ico" style="background:#ede9fe">🏆</div>
    <div class="mc-val">{{ $totalWon }}</div><div class="mc-lbl">Won</div>
  </div>
</div> -->

<!-- KPI Strip -->
@php
  $total = $employees->count();
  $active = $employees->where('status','Active')->count();
  $totalLeads = $employees->sum(fn($e)=>$e->leads->count());
  $totalWon = $employees->sum(fn($e)=>$e->leads->where('stage','Won')->count());
  $kpiMax = max($total, $active, $totalLeads, $totalWon, 1);
  $kpis = [
    ['icon'=>'👥','val'=>$total,'lbl'=>'Total','bar'=>'#e8f0fe'],
    ['icon'=>'✅','val'=>$active,'lbl'=>'Active','bar'=>'#d1fae5'],
    ['icon'=>'🎯','val'=>$totalLeads,'lbl'=>'Leads Assigned','bar'=>'#fef3c7'],
    ['icon'=>'🏆','val'=>$totalWon,'lbl'=>'Won','bar'=>'#ede9fe'],
  ];
@endphp
<!-- <div style="display:grid;grid-template-columns:repeat(4,1fr);margin-bottom:16px">
  @foreach($kpis as $k)
  <div style="padding:0 16px 0 0">
    <div style="font-size:16px;margin-bottom:6px">{{ $k['icon'] }}</div>
    <div style="height:12px;background:{{ $k['bar'] }}33;border-radius:0px;overflow:hidden;margin-bottom:8px">
      <div style="height:100%;width:{{ round($k['val']/$kpiMax*100) }}%;background:{{ $k['bar'] }};border-radius:0px"></div>
    </div>
    <div style="font-size:14px;font-weight:400;color:#1a2340;line-height:1">{{ $k['val'] }}</div>
    <div style="font-size:14px;color:#687182;margin-top:2px">{{ $k['lbl'] }}</div>
  </div>
  @endforeach
</div> -->
<div style="display:grid;grid-template-columns:repeat(4,1fr);margin-bottom:16px">
  @foreach($kpis as $k)
  <div style="padding:0 16px 0 0">
    <div style="position:relative;height:14px;background:{{ $k['bar'] }}33;border-radius:0px;overflow:visible;margin-bottom:8px">
      <div style="height:100%;width:{{ round($k['val']/$kpiMax*100) }}%;background:{{ $k['bar'] }};border-radius:0px"></div>
      <span style="position:absolute;top:50%;left:0;transform:translateY(-50%);font-size:14px;line-height:1">{{ $k['icon'] }}</span>
    </div>
    <div style="font-size:14px;font-weight:400;color:#1a2340;line-height:1">{{ $k['val'] }}</div>
    <div style="font-size:14px;color:#687182;margin-top:2px">{{ $k['lbl'] }}</div>
  </div>
  @endforeach
</div>

<!-- Filters -->
<form method="GET" action="{{ route('employees.index') }}" id="emp-filter-form">
<div style="display:flex;gap:9px;margin-bottom:14px;flex-wrap:wrap;align-items:center">
  <div class="tb-srch" style="max-width:240px;background:#fff;border:1.5px solid #e0e6f0;border-radius:8px;padding:7px 11px">
    <svg viewBox="0 0 24 24" style="width:12px;height:12px;fill:none;stroke:#9aa5b4;stroke-width:2;flex-shrink:0"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
    <input type="text" name="q" value="{{ $filters['q'] ?? '' }}" placeholder="Search employees…" style="border:none;background:none;outline:none;font-size:12.5px;color:#1a2340;width:100%;font-family:'Inter',sans-serif"
      oninput="clearTimeout(window._et);window._et=setTimeout(()=>document.getElementById('emp-filter-form').submit(),400)">
  </div>
  <select name="dept" onchange="this.form.submit()" style="border:1.5px solid #e0e6f0;border-radius:8px;padding:7px 11px;font-size:12.5px;outline:none;background:#fff;color:#4a5568;font-family:'Inter',sans-serif">
    <option value="">All Departments</option>
    @foreach($departments as $d)<option {{ ($filters['dept']??'')===$d?'selected':'' }}>{{ $d }}</option>@endforeach
  </select>
  <select name="status" onchange="this.form.submit()" style="border:1.5px solid #e0e6f0;border-radius:8px;padding:7px 11px;font-size:12.5px;outline:none;background:#fff;color:#4a5568;font-family:'Inter',sans-serif">
    <option value="">All Status</option>
    <option {{ ($filters['status']??'')==='Active'?'selected':'' }}>Active</option>
    <option {{ ($filters['status']??'')==='Inactive'?'selected':'' }}>Inactive</option>
  </select>
  <a href="{{ route('employees.index') }}" class="btn btn-out btn-sm">Reset</a>
  <span style="font-size:12px;color:#718096;margin-left:auto">{{ $employees->count() }} employee{{ $employees->count()!==1?'s':'' }}</span>
</div>
</form>

<!-- Table -->
<div style="background:#fff;border:1px solid #e0e6f0;border-radius:12px;overflow:hidden;box-shadow:0 1px 4px rgba(0,0,0,.07)">
  <table style="width:100%;border-collapse:collapse">
    <thead>
      <tr style="background:#f7f9fc">
        @foreach(['Employee','Role / Dept','Contact','Leads','Won','Win%','Status','Actions'] as $th)
        <th style="padding:10px 14px;text-align:{{ in_array($th,['Leads','Won','Win%'])?'center':'left' }};font-size:10px;font-weight:700;color:#718096;text-transform:uppercase;letter-spacing:.05em;border-bottom:1px solid #e0e6f0;white-space:nowrap">{{ $th }}</th>
        @endforeach
      </tr>
    </thead>
    <tbody>
      @forelse($employees as $e)
      @php
        $leads = $e->leads->count();
        $won   = $e->leads->where('stage','Won')->count();
        $rate  = $leads ? round($won/$leads*100) : 0;
      @endphp
      <tr>
        <td style="padding:12px 14px">
          <div style="display:flex;align-items:center;gap:10px">
            <div style="width:36px;height:36px;border-radius:50%;background:{{ $e->avatar_color }}22;color:{{ $e->avatar_color }};display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;flex-shrink:0">{{ $e->initials }}</div>
            <div>
              <div style="font-weight:700;font-size:13px;color:#1a2340">{{ $e->name }}</div>
              <div style="font-size:11px;color:#9aa5b4">{{ $e->emp_id }}</div>
            </div>
          </div>
        </td>
        <td style="padding:12px 14px">
          <div style="font-size:12.5px;color:#1a2340">{{ $e->role }}</div>
          <div style="font-size:11px;color:#9aa5b4">{{ $e->department }}</div>
        </td>
        <td style="padding:12px 14px">
          <div style="font-size:12.5px;color:#1a2340">{{ $e->phone }}</div>
          <div style="font-size:11px;color:#9aa5b4">{{ $e->email ?? '--' }}</div>
        </td>
        <td style="padding:12px 14px;text-align:center;font-weight:700;font-size:13px">{{ $leads }}</td>
        <td style="padding:12px 14px;text-align:center;font-weight:700;color:#10b981;font-size:13px">{{ $won }}</td>
        <td style="padding:12px 14px;text-align:center">
          <div style="display:flex;align-items:center;justify-content:center;gap:5px">
            <!-- <div style="width:50px;height:6px;background:#f0f4fa;border-radius:3px;overflow:hidden"><div style="height:100%;background:#10b981;width:{{ $rate }}%"></div></div> -->
            <span style="font-size:11px;font-weight:700;color:#10b981">{{ $rate }}%</span>
          </div>
        </td>
        <td style="padding:12px 14px">
          <span class="badge {{ $e->status==='Active'?'b-positive':'b-lost' }}">✅ {{ $e->status }}</span>
        </td>
        <td style="padding:12px 14px">
          <div style="display:flex;gap:4px">
            <button class="ab ab-e" onclick="openEmpEdit({{ $e->id }})"><svg viewBox="0 0 24 24"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg> Edit</button>
            <form method="POST" action="{{ route('employees.destroy', $e) }}" onsubmit="return confirm('Delete {{ $e->name }}? All leads will become unassigned.')">
              @csrf @method('DELETE')
              <button type="submit" class="ab ab-d">🗑 Delete</button>
            </form>
          </div>
        </td>
      </tr>
      @empty
      <tr><td colspan="8" style="padding:40px;text-align:center;color:#9aa5b4">No employees found.</td></tr>
      @endforelse
    </tbody>
  </table>
</div>

<!-- ── ADD / EDIT EMPLOYEE MODAL ── -->
<!-- <div class="modal-bg" id="emp-modal-bg">
  <div class="modal" id="emp-modal">
    <div class="modal-hd">
      <h3 id="emp-modal-title">+ Add Employee</h3>
      <button class="modal-close" onclick="closeEmpModal()">✕</button>
    </div>
    <div class="modal-body"> -->
  <!-- ── ADD / EDIT EMPLOYEE MODAL ── -->
<div class="emp-modal-bg" id="emp-modal-bg">
  <div class="emp-modal" id="emp-modal">
    <div class="em-hd">
      <h3 id="emp-modal-title">+ Add Employee</h3>
      <button class="em-close" onclick="closeEmpModal()">✕</button>
    </div>
    <div class="em-body">
      <form id="emp-form" method="POST" action="{{ route('employees.store') }}">
        @csrf
        <span id="emp-method-field"></span>
        <input type="hidden" id="ef-id">

        <div class="em-row2">
          <div class="em-field"><label>Full Name <span style="color:#dc2626">*</span></label><input type="text" id="ef-name" name="name" placeholder="Suresh B." required></div>
          <div class="em-field"><label>Employee ID</label><input type="text" id="ef-empid" name="emp_id" placeholder="EMP-001"></div>
        </div>
        <div class="em-row2">
          <div class="em-field"><label>Designation / Role <span style="color:#dc2626">*</span></label><input type="text" id="ef-role" name="role" placeholder="Sales Executive" required></div>
          <div class="em-field">
            <label>Department <span style="color:#dc2626">*</span></label>
            <select id="ef-dept" name="department" required>
              <option value="">Select Department</option>
              @foreach($departments as $d)<option>{{ $d }}</option>@endforeach
            </select>
          </div>
        </div>
        <div class="em-row2">
          <div class="em-field"><label>Phone / WhatsApp <span style="color:#dc2626">*</span></label><input type="tel" id="ef-phone" name="phone" placeholder="+91 98765 43210" required></div>
          <div class="em-field"><label>Email</label><input type="email" id="ef-email" name="email" placeholder="suresh@royalitpark.com"></div>
        </div>
        <div class="em-row3">
          <div class="em-field">
            <label>Status</label>
            <select id="ef-status" name="status"><option value="Active">Active</option><option value="Inactive">Inactive</option></select>
          </div>
          <div class="em-field"><label>Join Date</label><input type="date" id="ef-joindate" name="join_date"></div>
          <div class="em-field"><label>Target (Leads/Month)</label><input type="number" id="ef-target" name="target" placeholder="20" min="0" value="20"></div>
        </div>
        <div class="em-field" style="margin-bottom:12px">
          <label>Avatar Colour</label>
          <div class="av-colors" id="av-color-picker">
            @foreach($colors as $c)
            <div class="av-color {{ $c===$colors[0]?'sel':'' }}" data-color="{{ $c }}" style="background:{{ $c }}" onclick="pickAvColor(this)"></div>
            @endforeach
          </div>
          <input type="hidden" id="ef-color" name="avatar_color" value="{{ $colors[0] }}">
        </div>
        <div class="em-field">
          <label>Notes</label>
          <textarea id="ef-notes" name="notes" placeholder="Any additional notes about this employee…"></textarea>
        </div>
      </form>
    <!-- </div>
    <div class="modal-foot">
      <button class="btn btn-out btn-sm" onclick="closeEmpModal()">Cancel</button>
      <button class="btn btn-pri btn-sm" id="emp-save-btn" onclick="document.getElementById('emp-form').submit()">Add Employee</button>
    </div>
  </div>
</div> -->
    </div>
    <div class="em-footer">
      <button class="btn btn-out btn-sm" onclick="closeEmpModal()">Cancel</button>
      <button class="btn btn-pri btn-sm" id="emp-save-btn" onclick="document.getElementById('emp-form').submit()">Add Employee</button>
    </div>
  </div>
</div>

@push('scripts')
<script>
var EMP_DATA = @json($employees->keyBy('id'));

function openEmpModal(){
  document.getElementById('emp-modal-title').textContent='+ Add Employee';
  document.getElementById('emp-save-btn').textContent='Add Employee';
  document.getElementById('emp-form').action='{{ route('employees.store') }}';
  document.getElementById('emp-method-field').innerHTML='';
  document.getElementById('ef-id').value='';
  document.getElementById('ef-name').value='';
  document.getElementById('ef-empid').value='';
  document.getElementById('ef-role').value='';
  document.getElementById('ef-dept').value='';
  document.getElementById('ef-phone').value='';
  document.getElementById('ef-email').value='';
  document.getElementById('ef-status').value='Active';
  document.getElementById('ef-joindate').value='';
  document.getElementById('ef-target').value='20';
  document.getElementById('ef-notes').value='';
  pickAvColorByVal('{{ $colors[0] }}');
  document.getElementById('emp-modal-bg').classList.add('show');
}

function openEmpEdit(id){
  var e = EMP_DATA[id]; if(!e) return;
  document.getElementById('emp-modal-title').textContent='Edit Employee';
  document.getElementById('emp-save-btn').textContent='Update Employee';
  var url = '{{ url('/employees') }}/' + id;
  document.getElementById('emp-form').action = url;
  document.getElementById('emp-method-field').innerHTML = '<input type="hidden" name="_method" value="PUT">';
  document.getElementById('ef-id').value = id;
  document.getElementById('ef-name').value = e.name || '';
  document.getElementById('ef-empid').value = e.emp_id || '';
  document.getElementById('ef-role').value = e.role || '';
  document.getElementById('ef-dept').value = e.department || '';
  document.getElementById('ef-phone').value = e.phone || '';
  document.getElementById('ef-email').value = e.email || '';
  document.getElementById('ef-status').value = e.status || 'Active';
  document.getElementById('ef-joindate').value = e.join_date ? e.join_date.substring(0,10) : '';
  document.getElementById('ef-target').value = e.target || 20;
  document.getElementById('ef-notes').value = e.notes || '';
  pickAvColorByVal(e.avatar_color || '{{ $colors[0] }}');
  document.getElementById('emp-modal-bg').classList.add('show');
}

function closeEmpModal(){
  document.getElementById('emp-modal-bg').classList.remove('show');
}

function pickAvColor(el){
  document.querySelectorAll('.av-color').forEach(function(c){c.classList.remove('sel');});
  el.classList.add('sel');
  document.getElementById('ef-color').value = el.getAttribute('data-color');
}

function pickAvColorByVal(val){
  document.querySelectorAll('.av-color').forEach(function(c){
    c.classList.toggle('sel', c.getAttribute('data-color') === val);
  });
  document.getElementById('ef-color').value = val;
}

// Close modal on backdrop click
document.getElementById('emp-modal-bg').addEventListener('click', function(e){
  if(e.target === this) closeEmpModal();
});
</script>
@endpush
@endsection
