<?php /* payroll/employees.php */
$sym    = setting('currency_symbol','Rs.');
$total  = count($employees);
$active = count(array_filter($employees, fn($e)=>$e['status']==='active'));
$depts  = array_unique(array_filter(array_column($employees,'department')));
$totalSalary = array_sum(array_column(
    array_filter($employees, fn($e)=>$e['status']==='active'),
    'basic_salary'
));
?>

<style>
.emp-hero{background:linear-gradient(135deg,#064e3b,#065f46 55%,#059669);
  border-radius:12px;padding:20px 26px;color:#fff;margin-bottom:18px}
.kpi-pill{border-radius:10px;padding:12px 14px;text-align:center;height:100%}
.kpi-pill .val{font-size:1.3rem;font-weight:900;line-height:1}
.kpi-pill .lbl{font-size:.63rem;text-transform:uppercase;letter-spacing:.05em;margin-top:3px;opacity:.85}
.emp-table th{font-size:.7rem;padding:8px 10px;white-space:nowrap}
.emp-table td{font-size:.78rem;padding:7px 10px;vertical-align:middle}
.emp-table tr:hover td{background:#f0fdf4}
.emp-avatar{width:36px;height:36px;border-radius:50%;display:flex;align-items:center;
  justify-content:center;font-size:.72rem;font-weight:700;flex-shrink:0}
.dept-pill{padding:2px 8px;border-radius:12px;font-size:.62rem;font-weight:700}
.pay-type{padding:2px 7px;border-radius:8px;font-size:.6rem;font-weight:700}
</style>

<!-- Hero -->
<div class="emp-hero">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
    <div>
      <h5 class="fw-bold mb-1"><i class="bi bi-people-fill me-2"></i>Employees</h5>
      <div style="opacity:.8;font-size:.82rem">
        <?=$active?> active &nbsp;·&nbsp;
        <?=count($depts)?> departments &nbsp;·&nbsp;
        Total salary: <strong><?=$sym?><?=number_format($totalSalary,0)?></strong>
      </div>
    </div>
    <div class="d-flex gap-2">
      <?php if(Auth::can('payroll.employees')):?>
      <a href="<?=APP_URL?>/payroll/employees/add"
         class="btn btn-light btn-sm fw-semibold" style="color:#059669">
        <i class="bi bi-person-plus me-1"></i>Add Employee
      </a>
      <?php endif;?>
      <a href="<?=APP_URL?>/payroll/fp-upload"
         class="btn btn-outline-light btn-sm">
        <i class="bi bi-fingerprint me-1"></i>FP Upload
      </a>
      <button onclick="window.print()" class="btn btn-outline-light btn-sm">
        <i class="bi bi-printer me-1"></i>Print
      </button>
    </div>
  </div>
</div>

<?= flashMessages() ?>

<!-- KPI Pills -->
<div class="row g-2 mb-3">
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#f0fdf4;border:2px solid #059669">
      <div class="val" style="color:#059669"><?=$active?></div>
      <div class="lbl" style="color:#059669">Active Employees</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#eff6ff;border:2px solid #3b82f6">
      <div class="val" style="color:#3b82f6"><?=count($depts)?></div>
      <div class="lbl" style="color:#3b82f6">Departments</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#fef9c3;border:2px solid #d97706">
      <div class="val" style="color:#d97706"><?=$sym?><?=number_format($totalSalary,0)?></div>
      <div class="lbl" style="color:#d97706">Total Monthly Salary</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#fef2f2;border:2px solid #dc2626">
      <div class="val" style="color:#dc2626"><?=$total-$active?></div>
      <div class="lbl" style="color:#dc2626">Inactive</div>
    </div>
  </div>
</div>

<!-- Filters -->
<div class="card mb-3">
  <div class="card-body py-2">
    <form method="GET" action="<?=APP_URL?>/payroll/employees"
          class="d-flex gap-2 flex-wrap align-items-end">
      <div class="input-group input-group-sm" style="max-width:220px">
        <span class="input-group-text"><i class="bi bi-search"></i></span>
        <input type="text" name="search" class="form-control"
               placeholder="Name, code, designation…"
               value="<?=e($search)?>">
      </div>
      <select name="dept" class="form-select form-select-sm" style="max-width:160px">
        <option value="">All Departments</option>
        <?php foreach($departments as $d):?>
        <option value="<?=e($d['department'])?>"
                <?=$dept===($d['department'])?'selected':''?>>
          <?=e($d['department'])?>
        </option>
        <?php endforeach;?>
      </select>
      <select name="status" class="form-select form-select-sm" style="max-width:120px">
        <option value="active"  <?=$status==='active'? 'selected':''?>>✓ Active</option>
        <option value="inactive"<?=$status==='inactive'?'selected':''?>>✗ Inactive</option>
        <option value="all"     <?=$status==='all'?    'selected':''?>>All</option>
      </select>
      <button class="btn btn-secondary btn-sm fw-semibold">
        <i class="bi bi-funnel me-1"></i>Filter
      </button>
      <a href="<?=APP_URL?>/payroll/employees" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-x-lg"></i>
      </a>
    </form>
  </div>
</div>

<!-- Employee Table -->
<div class="card">
  <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
    <span class="fw-semibold small">
      <i class="bi bi-people me-1"></i>Employee List
    </span>
    <span class="badge bg-secondary"><?=count($employees)?> employees</span>
  </div>
  <div class="table-responsive">
    <table class="table table-sm table-hover mb-0 emp-table">
      <thead class="table-dark">
        <tr>
          <th class="ps-3">#</th>
          <th>Employee</th>
          <th>Department</th>
          <th>Contact</th>
          <th class="text-center">Join Date</th>
          <th class="text-center">Pay Type</th>
          <th class="text-end">Basic Salary</th>
          <th class="text-center">FP</th>
          <th class="text-center">Status</th>
          <th class="text-center">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php if(empty($employees)):?>
        <tr>
          <td colspan="10" class="text-center text-muted py-5">
            <i class="bi bi-people d-block fs-2 mb-2 opacity-25"></i>
            No employees found.
            <?php if(Auth::can('payroll.employees')):?>
            <div class="mt-2">
              <a href="<?=APP_URL?>/payroll/employees/add"
                 class="btn btn-sm btn-outline-success">
                <i class="bi bi-person-plus me-1"></i>Add First Employee
              </a>
            </div>
            <?php endif;?>
          </td>
        </tr>
        <?php endif;?>

        <?php
        // Dept color mapping
        $deptColors=['Management'=>'#7c3aed','Finance'=>'#0891b2','HR'=>'#059669',
                     'Sales'=>'#d97706','Warehouse'=>'#b45309','IT'=>'#1d4ed8',
                     'Operations'=>'#64748b','Marketing'=>'#db2777'];
        $payTypeClr=['monthly'=>['bg-primary','Monthly'],'daily'=>['bg-warning text-dark','Daily'],
                     'hourly'=>['bg-info text-dark','Hourly'],'piece'=>['bg-secondary','Piece']];

        foreach($employees as $i=>$emp):
          $initials  = strtoupper(substr($emp['full_name'],0,1)
                     .(strpos($emp['full_name'],' ')!==false
                       ?substr(strrchr($emp['full_name'],' '),1,1):''));
          $deptColor = $deptColors[$emp['department']??''] ?? '#64748b';
          $isActive  = $emp['status']==='active';
          $ptCfg     = $payTypeClr[$emp['pay_type']??'monthly'] ?? ['bg-secondary','—'];
        ?>
        <tr class="<?=$isActive?'':'opacity-50'?>">
          <td class="ps-3 text-muted small"><?=$i+1?></td>

          <!-- Employee -->
          <td>
            <div class="d-flex align-items-center gap-2">
              <div class="emp-avatar"
                   style="background:<?=$deptColor?>18;color:<?=$deptColor?>">
                <?=e($initials)?>
              </div>
              <div>
                <a href="<?=APP_URL?>/payroll/employees/view/<?=$emp['id']?>"
                   class="fw-bold text-decoration-none text-dark">
                  <?=e($emp['full_name'])?>
                </a>
                <div style="font-size:.65rem;color:#94a3b8">
                  <code><?=e($emp['emp_code'])?></code>
                  <?php if($emp['designation']):?>
                  &nbsp;·&nbsp;<?=e($emp['designation'])?>
                  <?php endif;?>
                </div>
              </div>
            </div>
          </td>

          <!-- Department -->
          <td>
            <?php if($emp['department']):?>
            <span class="dept-pill"
                  style="background:<?=$deptColor?>18;color:<?=$deptColor?>">
              <?=e($emp['department'])?>
            </span>
            <?php else:?>
            <span class="text-muted small">—</span>
            <?php endif;?>
            <?php if($emp['branch_name']):?>
            <div style="font-size:.63rem;color:#94a3b8;margin-top:2px">
              <i class="bi bi-building me-1"></i><?=e($emp['branch_name'])?>
            </div>
            <?php endif;?>
          </td>

          <!-- Contact -->
          <td>
            <?php if($emp['phone']):?>
            <div class="small">
              <i class="bi bi-telephone me-1 text-muted"></i><?=e($emp['phone'])?>
            </div>
            <?php endif;?>
            <?php if($emp['email']):?>
            <div class="text-muted" style="font-size:.65rem">
              <i class="bi bi-envelope me-1"></i><?=e($emp['email'])?>
            </div>
            <?php endif;?>
          </td>

          <!-- Join Date -->
          <td class="text-center">
            <?php if($emp['join_date']):?>
            <div class="small fw-semibold">
              <?=date('d M Y',strtotime($emp['join_date']))?>
            </div>
            <?php
            $years = date_diff(
              date_create($emp['join_date']),
              date_create('today')
            );
            $yrs = $years->y;
            $mos = $years->m;
            ?>
            <div style="font-size:.62rem;color:#94a3b8">
              <?=$yrs>0?"$yrs yr".($yrs>1?'s':'').($mos>0?", $mos mo":'')
                       :($mos>0?"$mos mo":'New')?>
            </div>
            <?php else:?>
            <span class="text-muted">—</span>
            <?php endif;?>
          </td>

          <!-- Pay Type -->
          <td class="text-center">
            <span class="pay-type badge <?=$ptCfg[0]?>"><?=$ptCfg[1]?></span>
          </td>

          <!-- Basic Salary -->
          <td class="text-end fw-bold">
            <?=$sym?><?=number_format($emp['basic_salary'],2)?>
          </td>

          <!-- Fingerprint -->
          <td class="text-center">
            <?php if($emp['fingerprint_id']):?>
            <span title="<?=e($emp['fingerprint_id'])?>"
                  style="color:#059669;font-size:.9rem">
              <i class="bi bi-fingerprint"></i>
            </span>
            <?php else:?>
            <span class="text-muted" style="font-size:.75rem">—</span>
            <?php endif;?>
          </td>

          <!-- Status -->
          <td class="text-center">
            <span class="badge <?=$isActive?'bg-success':'bg-secondary'?>"
                  style="font-size:.62rem">
              <?=$isActive?'Active':'Inactive'?>
            </span>
          </td>

          <!-- Actions -->
          <td class="text-center">
            <div class="d-flex gap-1 justify-content-center">
              <a href="<?=APP_URL?>/payroll/employees/view/<?=$emp['id']?>"
                 class="btn btn-sm btn-outline-primary py-0 px-2" title="View">
                <i class="bi bi-eye"></i>
              </a>
              <?php if(Auth::can('payroll.employees')):?>
              <a href="<?=APP_URL?>/payroll/employees/edit/<?=$emp['id']?>"
                 class="btn btn-sm btn-outline-secondary py-0 px-2" title="Edit">
                <i class="bi bi-pencil"></i>
              </a>
              <form method="POST"
                    action="<?=APP_URL?>/payroll/employees/toggle/<?=$emp['id']?>"
                    onsubmit="return confirm('<?=$isActive?'Deactivate':'Activate'?> <?=e($emp['full_name'])?>?')">
                <?=Auth::csrfField()?>
                <button class="btn btn-sm <?=$isActive?'btn-outline-warning':'btn-outline-success'?> py-0 px-1"
                        title="<?=$isActive?'Deactivate':'Activate'?>">
                  <i class="bi <?=$isActive?'bi-pause-circle':'bi-play-circle'?>"></i>
                </button>
              </form>
              <?php endif;?>
            </div>
          </td>
        </tr>
        <?php endforeach;?>
      </tbody>

      <!-- Department summary footer -->
      <?php if(!empty($employees)):?>
      <tfoot class="table-secondary fw-bold" style="font-size:.72rem">
        <tr>
          <td colspan="6" class="ps-3">TOTAL (<?=count($employees)?> employees)</td>
          <td class="text-end"><?=$sym?><?=number_format($totalSalary,2)?></td>
          <td colspan="3"></td>
        </tr>
      </tfoot>
      <?php endif;?>
    </table>
  </div>
</div>

<!-- Department breakdown -->
<?php if(!empty($depts) && count($employees) > 0):?>
<div class="card mt-3">
  <div class="card-header fw-semibold small bg-transparent">
    <i class="bi bi-diagram-3 me-1"></i>Department Breakdown
  </div>
  <div class="card-body">
    <div class="row g-2">
      <?php
      $deptGroups=[];
      foreach($employees as $e) {
        if($e['status']!=='active') continue;
        $d = $e['department']??'Unassigned';
        if(!isset($deptGroups[$d])) $deptGroups[$d]=['count'=>0,'salary'=>0];
        $deptGroups[$d]['count']++;
        $deptGroups[$d]['salary']+=(float)$e['basic_salary'];
      }
      arsort($deptGroups);
      $maxCount = max(array_column($deptGroups,'count')??[1]);
      foreach($deptGroups as $dName=>$dInfo):
        $clr = $deptColors[$dName]??'#64748b';
        $pct = $maxCount>0?round($dInfo['count']/$maxCount*100):0;
      ?>
      <div class="col-6 col-md-3">
        <div class="p-2 rounded" style="background:<?=$clr?>10;border:1px solid <?=$clr?>30">
          <div class="d-flex justify-content-between align-items-center mb-1">
            <span class="small fw-bold" style="color:<?=$clr?>"><?=e($dName)?></span>
            <span class="badge" style="background:<?=$clr?>;font-size:.62rem"><?=$dInfo['count']?></span>
          </div>
          <div style="height:4px;background:<?=$clr?>20;border-radius:2px">
            <div style="height:4px;border-radius:2px;width:<?=$pct?>%;background:<?=$clr?>"></div>
          </div>
          <div class="mt-1 text-muted" style="font-size:.65rem">
            <?=$sym?><?=number_format($dInfo['salary'],0)?>/mo
          </div>
        </div>
      </div>
      <?php endforeach;?>
    </div>
  </div>
</div>
<?php endif;?>