<?php $this->start('body'); ?>
<?php
$r = $this->data['r']; $from = $this->data['from']; $to = $this->data['to'];
$this->data['form_action'] = PROOT . 'FinancialReports/cashFlow';
$b = $r['buckets'];
$netChange = $r['net_change'];
$positive  = $netChange >= 0;
?>

<div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
  <div>
    <h5 class="mb-0 fw-semibold"><i class="fas fa-arrows-turn-to-dots me-2 text-muted"></i>Cash Flow</h5>
    <div class="text-muted small"><?= humanDate($from); ?> &rarr; <?= humanDate($to); ?> &middot; direct method</div>
  </div>
  <div class="d-flex gap-2">
    <a href="<?= PROOT; ?>FinancialReports" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Reports</a>
    <button class="btn btn-sm btn-outline-primary" onclick="window.print()"><i class="fas fa-print me-1"></i>Print</button>
  </div>
</div>

<?php include __DIR__ . '/_range_form.php'; ?>

<!-- Headline strip -->
<div class="row g-2 mb-3">
  <div class="col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Opening cash</div>
    <div class="fs-4 fw-bold">TZS <?= number_format($r['opening_cash'], 0); ?></div>
    <div class="small text-muted">as of <?= humanDate(date('Y-m-d', strtotime($from . ' -1 day'))); ?></div>
  </div></div></div>
  <div class="col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Net change</div>
    <div class="fs-4 fw-bold <?= $positive ? 'text-success' : 'text-danger'; ?>">TZS <?= number_format($netChange, 0); ?></div>
    <div class="small text-muted"><?= $positive ? 'cash generated' : 'cash consumed'; ?></div>
  </div></div></div>
  <div class="col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Closing cash</div>
    <div class="fs-4 fw-bold text-primary">TZS <?= number_format($r['closing_cash'], 0); ?></div>
    <div class="small text-muted">computed from opening + net</div>
  </div></div></div>
  <div class="col-md-3"><div class="card border-0 shadow-sm h-100 border-<?= $r['reconciles'] ? 'success' : 'warning'; ?>"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Actual cash bal.</div>
    <div class="fs-4 fw-bold">TZS <?= number_format($r['actual_closing'], 0); ?></div>
    <?php if ($r['reconciles']): ?>
      <div class="small text-success"><i class="fas fa-check me-1"></i>reconciles</div>
    <?php else: ?>
      <div class="small text-warning"><i class="fas fa-triangle-exclamation me-1"></i>off by <?= number_format(abs($r['closing_cash'] - $r['actual_closing']), 2); ?></div>
    <?php endif; ?>
  </div></div></div>
</div>

<div class="row g-3">
  <!-- Sectioned statement -->
  <div class="col-lg-7">
    <div class="card border-0 shadow-sm h-100"><div class="card-body p-0">
      <table class="table table-sm mb-0 align-middle">
        <thead class="table-light">
          <tr><th>Statement</th><th class="money" style="width:180px;">TZS</th></tr>
        </thead>
        <tbody>
          <?php
            $section = function ($title, $rows, $subtotal, $subLabel) {
                echo '<tr class="table-secondary"><th colspan="2" class="text-uppercase small">' . htmlspecialchars($title) . '</th></tr>';
                if (empty($rows)) {
                    echo '<tr><td class="text-muted small ps-4" colspan="2">&mdash; no activity &mdash;</td></tr>';
                } else {
                    foreach ($rows as [$label, $val, $isInflow]) {
                        if (abs($val) < 0.005) continue;
                        $cls = $isInflow ? 'text-success' : 'text-danger';
                        echo '<tr>';
                        echo   '<td class="ps-4 small">' . htmlspecialchars($label) . '</td>';
                        echo   '<td class="money font-monospace small ' . $cls . '">'
                             . ($isInflow ? '' : '(') . number_format(abs($val), 2) . ($isInflow ? '' : ')')
                             . '</td>';
                        echo '</tr>';
                    }
                }
                echo '<tr class="fw-semibold border-top"><td>' . htmlspecialchars($subLabel) . '</td>';
                echo '<td class="money font-monospace ' . ($subtotal >= 0 ? 'text-success' : 'text-danger') . '">'
                     . number_format($subtotal, 2) . '</td></tr>';
            };
          ?>

          <?php
            $section('Operating activities',
              [
                ['Cash received from customers / sales', $b['operating_in'],  true],
                ['Cash paid to suppliers / expenses',    $b['operating_out'], false],
                ['Cash paid for payroll',                $b['payroll_out'],   false],
                ['Cash paid for taxes',                  $b['tax_out'],       false],
                ['Bank interest / income',               $b['bank_adj_in'],   true],
                ['Bank fees / adjustments',              $b['bank_adj_out'],  false],
              ],
              $r['operating'],
              'Net cash from operating activities'
            );

            $section('Investing activities',
              [
                ['Proceeds from asset disposals', $b['investing_in'],  true],
                ['Purchase of fixed assets',      $b['investing_out'], false],
              ],
              $r['investing'],
              'Net cash from investing activities'
            );

            $section('Financing activities',
              [
                ['Loan proceeds / capital injection', $b['financing_in'],  true],
                ['Loan repayments / drawings',        $b['financing_out'], false],
              ],
              $r['financing'],
              'Net cash from financing activities'
            );

            if (abs($r['other']) >= 0.01) {
                $section('Other / unclassified',
                  [
                    ['Unclassified inflows',  $b['other_in'],  true],
                    ['Unclassified outflows', $b['other_out'], false],
                  ],
                  $r['other'],
                  'Net unclassified'
                );
            }
          ?>

          <tr class="table-primary fw-bold">
            <th class="text-uppercase small">Net change in cash</th>
            <th class="money font-monospace <?= $positive ? 'text-success' : 'text-danger'; ?>">
              <?= number_format($netChange, 2); ?>
            </th>
          </tr>
          <tr>
            <td class="small">Opening cash</td>
            <td class="money font-monospace small"><?= number_format($r['opening_cash'], 2); ?></td>
          </tr>
          <tr class="fw-bold border-top">
            <td class="text-uppercase small">Closing cash</td>
            <td class="money font-monospace text-primary"><?= number_format($r['closing_cash'], 2); ?></td>
          </tr>
        </tbody>
      </table>
    </div></div>
  </div>

  <!-- Cash account breakdown + source-type drill -->
  <div class="col-lg-5">
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-body p-0">
        <div class="p-3 pb-2"><h6 class="text-uppercase text-muted small mb-0">Cash accounts &middot; closing as of <?= humanDate($to); ?></h6></div>
        <table class="table table-sm mb-0">
          <tbody>
            <?php
              $sumCash = 0.0;
              foreach ($r['cash_accounts'] as $c):
                $bal = (float)$c['balance'];
                $sumCash += $bal;
            ?>
              <tr>
                <td class="small">
                  <span class="font-monospace text-muted me-2"><?= htmlspecialchars($c['account_code']); ?></span>
                  <?= htmlspecialchars($c['account_name']); ?>
                </td>
                <td class="money font-monospace small"><?= number_format($bal, 2); ?></td>
              </tr>
            <?php endforeach; ?>
            <tr class="fw-semibold border-top">
              <td>Total cash on hand</td>
              <td class="money font-monospace"><?= number_format($sumCash, 2); ?></td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <div class="card border-0 shadow-sm">
      <div class="card-body p-0">
        <div class="p-3 pb-2 d-flex justify-content-between align-items-center">
          <h6 class="text-uppercase text-muted small mb-0">By source type</h6>
          <span class="small text-muted"><?= count($r['by_source']); ?></span>
        </div>
        <table class="table table-sm mb-0">
          <thead class="table-light">
            <tr>
              <th>Source</th><th>Category</th>
              <th class="money">In</th><th class="money">Out</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($r['by_source'])): ?>
              <tr><td colspan="4" class="text-center text-muted small py-3">No cash movement in this period.</td></tr>
            <?php else: ?>
              <?php foreach ($r['by_source'] as $s): ?>
                <tr>
                  <td class="small font-monospace"><?= htmlspecialchars($s['source_type']); ?><div class="small text-muted"><?= (int)$s['count']; ?> lines</div></td>
                  <td class="small text-muted"><?= htmlspecialchars($s['category']); ?></td>
                  <td class="money font-monospace small text-success"><?= $s['in']  > 0 ? number_format($s['in'],  2) : '—'; ?></td>
                  <td class="money font-monospace small text-danger"><?= $s['out'] > 0 ? number_format($s['out'], 2) : '—'; ?></td>
                </tr>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<?php $this->end(); ?>
