<?php /* payroll/process.php */
$sym      = setting('currency_symbol','Rs.');
$canEdit  = in_array($period['status'],['draft','processing']);
$canApprove = Auth::can('payroll.approve') && $period['status']==='processing';
$canPay  = Auth::can('payroll.approve') && $period['status']==='approved';
$statusCls=['draft'=>'secondary','processing'=>'warning','approved'=>'info','paid'=>'success'][$period['status']]??'secondary';
?>
<div class="d-flex justify-content-between align-items-start mb-3 flex-wrap gap-2">
  <div>
    <h5 class="fw-bold mb-1">
      <i class="bi bi-receipt me-2 text-success"></i><?= e($period['period_name']) ?>
      <span class="badge bg-<?=$statusCls?> ms-2"><?=ucfirst($period['status'])?></span>
    </h5>
    <small class="text-muted"><?=fDate($period['start_date'])?> – <?=fDate($period['end_date'])?></small>
  </div>
  <div class="d-flex gap-2 flex-wrap">
    <a href="<?=APP_URL?>/payroll" class="btn btn-sm btn-outline-secondary">← Payroll</a>
    <?php if($canApprove):?>
    <form method="POST" action="<?=APP_URL?>/payroll/approve/<?=$period['id']?>"
          onsubmit="return confirm('Approve this payroll?')">
      <?=Auth::csrfField()?>
      <button class="btn btn-sm btn-info fw-semibold"><i class="bi bi-check-all me-1"></i>Approve</button>
    </form>
    <?php endif;?>
    <?php if($canPay):?>
    <form method="POST" action="<?=APP_URL?>/payroll/mark-paid/<?=$period['id']?>"
          onsubmit="return confirm('Mark ALL salaries as paid?')">
      <?=Auth::csrfField()?>
      <button class="btn btn-sm btn-success fw-semibold"><i class="bi bi-cash me-1"></i>Mark All Paid</button>
    </form>
    <?php endif;?>
  </div>
</div>

<?= flashMessages() ?>

<?php if(!empty($employees)):
  $totalNet = array_sum(array_column($employees,'net_salary'));
  $totalGross = array_sum(array_column($employees,'gross_salary'));
?>
<!-- Summary KPIs -->
<div class="row g-2 mb-3">
  <div class="col-6 col-md-3"><div class="card text-center py-3"><div class="fw-bold fs-4"><?=count($employees)?></div><small class="text-muted">Employees</small></div></div>
  <div class="col-6 col-md-3"><div class="card text-center py-3 border-primary"><div class="fw-bold text-primary"><?=currency($totalGross)?></div><small class="text-muted">Gross Payroll</small></div></div>
  <div class="col-6 col-md-3"><div class="card text-center py-3 border-success"><div class="fw-bold text-success"><?=currency($totalNet)?></div><small class="text-muted">Net Payroll</small></div></div>
  <div class="col-6 col-md-3"><div class="card text-center py-3"><div class="fw-bold"><?=count(array_filter($employees,fn($e)=>$e['payment_status']==='paid'))?>/<?=count($employees)?></div><small class="text-muted">Paid</small></div></div>
</div>

<form method="POST" action="<?=APP_URL?>/payroll/save/<?=$period['id']?>">
  <?=Auth::csrfField()?>
  <div class="card">
    <div class="card-header bg-dark text-white fw-semibold small d-flex justify-content-between">
      <span><i class="bi bi-table me-1"></i>Payroll Sheet — <?=e($period['period_name'])?></span>
      <?php if($canEdit):?>
      <button type="submit" class="btn btn-sm btn-warning fw-semibold py-0 px-3">
        <i class="bi bi-calculator me-1"></i>Calculate & Save
      </button>
      <?php endif;?>
    </div>
    <div class="table-responsive">
      <table class="table table-sm table-hover mb-0" style="font-size:.78rem;min-width:900px">
        <thead class="table-dark">
          <tr>
            <th>#</th><th>Employee</th><th class="text-end">Basic</th>
            <th class="text-center" style="width:70px">Present</th>
            <th class="text-center" style="width:60px">OT Hrs</th>
            <th class="text-center" style="width:70px">OT Rate</th>
            <th class="text-end">Allowances</th><th class="text-end">Deductions</th>
            <th class="text-end">Gross</th><th class="text-end fw-bold">Net</th>
            <th>Payment</th><th>Status</th><th class="no-print">Payslip</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach($employees as $i=>$e):
            $hasPay = $e['record_id']>0;
            $stCls  = $e['payment_status']==='paid'?'table-success bg-opacity-10':'';
          ?>
          <tr class="<?=$stCls?>">
            <td class="text-muted"><?=$i+1?></td>
            <td>
              <input type="hidden" name="employee_id[]" value="<?=$e['id']?>">
              <div class="fw-semibold"><?=e($e['full_name'])?></div>
              <code style="font-size:.62rem;color:#94a3b8"><?=e($e['emp_code'])?></code>
            </td>
            <td class="text-end"><?=currency($e['basic_salary'])?></td>
            <td>
              <input type="number" name="present_days[]"
                     class="form-control form-control-sm text-center"
                     value="<?=$e['present_days']??26?>" min="0" max="31" step="0.5"
                     <?=!$canEdit?'readonly':''?> style="width:62px">
            </td>
            <td>
              <input type="number" name="overtime_hours[]"
                     class="form-control form-control-sm text-center"
                     value="<?=$e['overtime_hours']??0?>" min="0" step="0.5"
                     <?=!$canEdit?'readonly':''?> style="width:54px">
            </td>
            <td>
              <input type="number" name="overtime_rate[]"
                     class="form-control form-control-sm text-center"
                     value="<?=$e['overtime_rate']??0?>" min="0" step="1"
                     <?=!$canEdit?'readonly':''?> style="width:62px">
            </td>
            <td class="text-end text-success"><?=$hasPay?currency($e['total_allowances']):'—'?></td>
            <td class="text-end text-danger"><?=$hasPay?currency($e['total_deductions']):'—'?></td>
            <td class="text-end fw-semibold"><?=$hasPay?currency($e['gross_salary']):'—'?></td>
            <td class="text-end fw-bold text-primary"><?=$hasPay?currency($e['net_salary']):'—'?></td>
            <td>
              <select name="payment_method[]" class="form-select form-select-sm" style="width:110px" <?=!$canEdit?'disabled':''?>>
                <option value="bank_transfer" <?=($e['payment_method']??'')==='bank_transfer'?'selected':''?>>🏦 Bank</option>
                <option value="cash"          <?=($e['payment_method']??'')==='cash'?'selected':''?>>💵 Cash</option>
                <option value="cheque"        <?=($e['payment_method']??'')==='cheque'?'selected':''?>>📝 Cheque</option>
              </select>
            </td>
            <td>
              <span class="badge <?=$e['payment_status']==='paid'?'bg-success':'bg-warning text-dark'?>" style="font-size:.6rem">
                <?=ucfirst($e['payment_status']??'pending')?>
              </span>
            </td>
            <td class="no-print">
              <?php if($hasPay):?>
              <a href="<?=APP_URL?>/payroll/payslip/<?=$e['record_id']?>"
                 class="btn btn-sm btn-outline-secondary py-0 px-2" title="View Payslip">
                <i class="bi bi-file-earmark-person"></i>
              </a>
              <?php else:?>—<?php endif;?>
            </td>
          </tr>
          <?php endforeach;?>
        </tbody>
        <tfoot class="table-secondary fw-bold">
          <tr>
            <td colspan="6">TOTAL (<?=count($employees)?> employees)</td>
            <td class="text-end text-success"><?=currency(array_sum(array_column($employees,'total_allowances')))?></td>
            <td class="text-end text-danger"><?=currency(array_sum(array_column($employees,'total_deductions')))?></td>
            <td class="text-end"><?=currency($totalGross)?></td>
            <td class="text-end text-primary"><?=currency($totalNet)?></td>
            <td colspan="3"></td>
          </tr>
        </tfoot>
      </table>
    </div>
  </div>
</form>
<?php endif;?>