<?php
require_once __DIR__ . '/_report_common.php';

$employee_id = (int)($_GET['employee_id'] ?? 0);
$from = $_GET['from'] ?? date('Y-m-01');
$to   = $_GET['to'] ?? date('Y-m-d');

$emps = $pdo->prepare("SELECT id, full_name FROM employees WHERE company_id=? ORDER BY full_name");
$emps->execute([$cid]);
$emps = $emps->fetchAll(PDO::FETCH_ASSOC);

$whereEmp = $employee_id ? " AND a.employee_id = {$employee_id} " : "";

$sql = "
SELECT a.*, e.full_name,
  (SELECT IFNULL(SUM(s.amount),0) FROM employee_advance_settlements s WHERE s.company_id=a.company_id AND s.advance_id=a.id) AS settled_amount
FROM employee_advances a
JOIN employees e ON e.id=a.employee_id
WHERE a.company_id=?
  AND a.tx_date BETWEEN ? AND ?
  {$whereEmp}
ORDER BY a.tx_date DESC, a.id DESC
";
$st = $pdo->prepare($sql);
$st->execute([$cid,$from,$to]);
$rows = $st->fetchAll(PDO::FETCH_ASSOC);

render_layout('تقرير العهد','التقارير <span class="mx-1">/</span> تقرير العهد', function() use ($emps,$employee_id,$from,$to,$rows) {
?>
<div class="container-fluid mt-3">
  <div class="d-flex align-items-start align-items-md-center justify-content-between flex-column flex-md-row gap-2">
    <div>
      <div class="fw-bold fs-4">تقرير العهد</div>
      <div class="text-secondary small">عرض عهد الموظفين وتسوياتها</div>
    </div>
    <div class="d-flex gap-2 no-print">
      <button class="btn btn-dark btn-sm" onclick="window.print()"><i class="bi bi-printer"></i> طباعة</button>
    </div>
  </div>

  <div class="card cardx p-3 mt-2 no-print">
    <form method="get" class="row g-2 align-items-end">
      <div class="col-12 col-md-4">
        <label class="form-label">الموظف</label>
        <select class="selectpicker" data-style="form-select" data-live-search="true" data-size="8"   name="employee_id">
          <option value="0">الكل</option>
          <?php foreach($emps as $e): ?>
            <option value="<?= (int)$e['id'] ?>" <?= $employee_id===(int)$e['id']?'selected':'' ?>><?= h($e['full_name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-6 col-md-3">
        <label class="form-label">من</label>
        <?= render_date_input('from', $from) ?>
      </div>
      <div class="col-6 col-md-3">
        <label class="form-label">إلى</label>
        <?= render_date_input('to', $to) ?>
      </div>
      <div class="col-12 col-md-2">
        <button class="btn btn-outline-secondary w-100">عرض</button>
      </div>
    </form>
  </div>

  <div class="card cardx mt-3">
    <div class="p-3 d-flex align-items-center justify-content-between">
      <div class="fw-bold">النتائج</div>
      <span class="text-secondary small"><?= count($rows) ?> حركة</span>
    </div>
    <div class="table-responsive px-3 pb-3">
      <table class="table align-middle mb-0">
        <thead>
          <tr class="text-secondary small">
            <th>#</th><th>الموظف</th><th>التاريخ</th><th class="text-end">العهدة</th><th class="text-end">التسويات</th><th class="text-end">المتبقي</th><th>الحالة</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach($rows as $r): 
            $remain = (float)$r['amount'] - (float)$r['settled_amount'];
          ?>
            <tr>
              <td class="text-secondary"><?= (int)$r['id'] ?></td>
              <td class="fw-semibold"><?= h($r['full_name']) ?></td>
              <td class="text-secondary"><?= h($r['tx_date']) ?></td>
              <td class="text-end fw-semibold"><?= number_format((float)$r['amount'],2) ?></td>
              <td class="text-end"><?= number_format((float)$r['settled_amount'],2) ?></td>
              <td class="text-end"><?= number_format($remain,2) ?></td>
              <td>
                <?php if($r['status']==='OPEN'): ?>
                  <span class="badge bg-warning-subtle text-warning border border-warning-subtle">مفتوحة</span>
                <?php elseif($r['status']==='SETTLED'): ?>
                  <span class="badge bg-success-subtle text-success border border-success-subtle">مسوّاة</span>
                <?php else: ?>
                  <span class="badge bg-danger-subtle text-danger border border-danger-subtle">ملغاة</span>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; ?>
          <?php if(!count($rows)): ?>
            <tr><td colspan="7" class="text-center text-secondary py-4">لا توجد بيانات</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php }); ?>
