<?php
require_once __DIR__ . '/_report_common.php';
[$from,$to] = get_range();

$stmt = $pdo->prepare("
  SELECT
    je.entry_date,
    a.code AS cash_code,
    a.name AS cash_name,
    SUM(jl.debit - jl.credit) AS cash_movement
  FROM journal_lines jl
  JOIN journal_entries je ON je.id = jl.entry_id
  JOIN accounts a ON a.id = jl.account_id
  WHERE jl.company_id=? AND je.status='POSTED'
    AND je.entry_date BETWEEN ? AND ?
    AND a.is_cash=1
  GROUP BY je.entry_date, a.id
  ORDER BY je.entry_date
");
$stmt->execute([$cid,$from,$to]);
$rows = $stmt->fetchAll();

$total = 0;
foreach($rows as $r){ $total += (float)$r['cash_movement']; }

render_layout("التدفقات النقدية", "الرئيسية <span class='mx-1'>/</span> التقارير <span class='mx-1'>/</span> التدفقات النقدية", function() use ($rows,$from,$to,$total) {
?>
<div class="card cardx mt-3">
  <div class="p-3">
    <form class="row g-2 align-items-end" method="get">
      <div class="col-12 col-md-4">
        <label class="form-label small text-secondary">من</label>
        <?= render_date_input('from', $from) ?>
      </div>
      <div class="col-12 col-md-4">
        <label class="form-label small text-secondary">إلى</label>
        <?= render_date_input('to', $to) ?>
      </div>
      <div class="col-12 col-md-4">
        <button class="btn btn-dark w-100"><i class="bi bi-funnel"></i> تطبيق</button>
      </div>
    </form>
  </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 class="text-end">التغير النقدي</th>
        </tr>
      </thead>
      <tbody>
        <?php if(!$rows): ?>
          <tr><td colspan="3" class="text-center text-secondary py-4">لا توجد بيانات</td></tr>
        <?php else: foreach($rows as $r): ?>
          <tr>
            <td class="text-secondary"><?= h($r['entry_date']) ?></td>
            <td class="fw-semibold"><?= h($r['cash_code'].' - '.$r['cash_name']) ?></td>
            <td class="text-end fw-semibold"><?= number_format((float)$r['cash_movement'],2) ?></td>
          </tr>
        <?php endforeach; endif; ?>
      </tbody>
      <tfoot>
        <tr><th colspan="2" class="text-end">إجمالي صافي التدفق</th><th class="text-end"><?= number_format($total,2) ?></th></tr>
      </tfoot>
    </table>
  </div>
</div>
<?php }); ?>
