<?php
declare(strict_types=1);
require_once __DIR__ . '/../private/lib/bootstrap.php';
require_once __DIR__ . '/../private/views/layout.php';
require_login();

$totals   = dash_totals();
$pipeline = dash_pipeline();
$aging    = dash_aging();
$fees     = dash_by_fee_type();
$coll     = dash_collections(12);
$upcoming = dash_upcoming(10);
$batch    = batch_today();
$ffAlerts = dash_ff_deadlines(10);
$riskRows = dash_discharge_risk();
$riskTot  = dash_discharge_risk_total();

// Order the aging buckets the way a person reads them, not the way SQL grouped them.
$order = ['0-30 days', '31-60 days', '61-90 days', '91-180 days', '180+ days', 'No payment yet'];
$colors = [
    '0-30 days'     => '#146B52',
    '31-60 days'    => '#4E8A5C',
    '61-90 days'    => '#A8560A',
    '91-180 days'   => '#91242A',
    '180+ days'     => '#6B1418',
    'No payment yet'=> '#626C7D',
];
$agingByKey = [];
foreach ($aging as $a) {
    $agingByKey[$a['bucket']] = $a;
}
$agingRows = [];
foreach ($order as $k) {
    if (isset($agingByKey[$k])) {
        $agingRows[] = [
            'bucket'  => $k,
            'balance' => (int) $agingByKey[$k]['balance'],
            'cases'   => (int) $agingByKey[$k]['cases'],
            'color'   => $colors[$k],
        ];
    }
}

$pipeLabels = [
    'ready_to_file' => ['Ready to file', '#146B52'],
    'active'        => ['Paying',        '#2E7DA8'],
    'at_risk'       => ['At risk',       '#A8560A'],
    'stalled'       => ['Stalled',       '#91242A'],
    'never_paid'    => ['Never paid',    '#626C7D'],
];
$pipeRows = [];
$pipeIndex = [];
foreach ($pipeline as $p) {
    $pipeIndex[$p['funding_status']] = $p;
}
foreach ($pipeLabels as $key => [$label, $color]) {
    if (isset($pipeIndex[$key])) {
        $pipeRows[] = [
            'key'   => $key,
            'label' => $label,
            'color' => $color,
            'value' => (int) $pipeIndex[$key]['cases'],
            'balance' => (int) $pipeIndex[$key]['balance'],
        ];
    }
}

$collRows = [];
foreach ($coll as $c) {
    $ts = strtotime($c['ym'] . '-01');
    $collRows[] = [
        'label'    => date('F Y', $ts),
        'short'    => date('M', $ts),
        'received' => (int) $c['received'],
        'payments' => (int) $c['payments'],
    ];
}

$atRisk = 0;
foreach ($pipeRows as $p) {
    if (in_array($p['key'], ['at_risk', 'stalled', 'never_paid'], true)) {
        $atRisk += $p['balance'];
    }
}

layout_head('Dashboard', 'dashboard');
?>

<div class="page-head">
  <div>
    <h1>Dashboard</h1>
    <p class="sub">Where the money stands as of <?= e(date('F j, Y')) ?>.</p>
  </div>
  <a class="btn" href="cases.php?workflow=pre_filing&amp;with_balance=1&amp;sort=oldest">Work the pre-filing list</a>
</div>

<?php if ($ffAlerts): ?>
  <div class="card" style="border-left:3px solid var(--risk);margin-bottom:16px">
    <h2 style="color:var(--risk)">Court filing fee deadlines</h2>
    <p class="hint" style="margin:0 0 10px">
      A missed filing fee installment gets a Chapter 7 case dismissed without a discharge.
    </p>
    <table>
      <tbody>
      <?php foreach ($ffAlerts as $a): ?>
        <tr>
          <td style="width:96px">
            <span class="badge <?= $a['deadline_status'] === 'past_deadline' ? 'risk' : 'warn' ?>">
              <?= (int) $a['days_left'] < 0
                    ? abs((int) $a['days_left']) . 'd overdue'
                    : (int) $a['days_left'] . 'd left' ?>
            </span>
          </td>
          <td>
            <a class="t-name" href="case.php?id=<?= (int) $a['case_id'] ?>">
              <?= e($a['last_name']) ?><?= $a['first_name'] ? ', ' . e($a['first_name']) : '' ?>
            </a>
            <div class="t-sub">
              deadline <?= e(fmt_date($a['final_deadline'])) ?>
              <?php if ($a['next_installment_due']): ?>
                &middot; next installment <?= e(fmt_date($a['next_installment_due'])) ?>
              <?php endif; ?>
            </div>
          </td>
          <td class="num money"><?= money((int) $a['ff_balance_cents']) ?></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
<?php endif; ?>

<div class="grid c3" style="margin-bottom:16px">
  <div class="stat accent">
    <div class="stat-label">Outstanding</div>
    <div class="stat-value money"><?= money((int) ($totals['balance'] ?? 0)) ?></div>
    <div class="stat-note">across <?= (int) ($totals['live_cases'] ?? 0) ?> open cases</div>
  </div>
  <div class="stat good">
    <div class="stat-label">Collected to date</div>
    <div class="stat-value money"><?= money((int) ($totals['paid'] ?? 0)) ?></div>
    <div class="stat-note">
      <?= (int) ($totals['charged'] ?? 0) > 0
            ? round(((int) $totals['paid'] / (int) $totals['charged']) * 100) . '% of everything billed'
            : 'no charges recorded' ?>
    </div>
  </div>
  <div class="stat warn">
    <div class="stat-label">Not moving</div>
    <div class="stat-value money"><?= money($atRisk) ?></div>
    <div class="stat-note">quiet 45 days or longer</div>
  </div>
  <div class="stat <?= $riskTot > 0 ? 'risk' : '' ?>">
    <div class="stat-label">At discharge risk</div>
    <div class="stat-value money"><?= money($riskTot) ?></div>
    <div class="stat-note">
      <?= count($riskRows) ?> filed Ch 7 case<?= count($riskRows) === 1 ? '' : 's' ?> still owing fees
    </div>
  </div>
  <div class="stat">
    <div class="stat-label">Taken in today</div>
    <div class="stat-value money"><?= money((int) ($batch['system_total'] ?? 0)) ?></div>
    <div class="stat-note">
      <?= (int) ($batch['payment_count'] ?? 0) ?> payment<?= (int) ($batch['payment_count'] ?? 0) === 1 ? '' : 's' ?>,
      <?= money((int) ($batch['cash_total'] ?? 0)) ?> cash
    </div>
  </div>
</div>

<div class="split">
  <div>
    <div class="card">
      <div style="display:flex;justify-content:space-between;align-items:baseline;margin-bottom:10px">
        <h2 style="margin:0">Pre-filing pipeline</h2>
        <span class="t-sub">Cases cannot be filed until they are funded, so this is the queue that matters.</span>
      </div>
      <div id="chart-pipeline"></div>
      <div class="funding-legend">
        <?php foreach ($pipeRows as $p): ?>
          <span>
            <i style="background:<?= e($p['color']) ?>"></i>
            <a href="cases.php?workflow=pre_filing&amp;sort=oldest"><?= e($p['label']) ?></a>
            <?= (int) $p['value'] ?> &middot; <span class="num"><?= money($p['balance']) ?></span>
          </span>
        <?php endforeach; ?>
      </div>
    </div>

    <div class="card">
      <h2>Payments received by month</h2>
      <div id="chart-collections"></div>
    </div>

    <div class="card">
      <h2>Outstanding by time since last payment</h2>
      <div id="chart-aging"></div>
      <p class="hint">
        For pre-filing work this measures whether a case is still moving, not whether a bill is overdue.
      </p>
    </div>
  </div>

  <div>
    <div class="card">
      <h2>Outstanding by fee type</h2>
      <div id="chart-fees"></div>
    </div>

    <div class="card tight">
      <div class="card-head"><h2 style="margin:0">Coming up</h2></div>
      <?php if (!$upcoming): ?>
        <div class="empty"><strong>Nothing scheduled</strong>Milestones with a date will appear here.</div>
      <?php else: ?>
        <table>
          <tbody>
          <?php foreach ($upcoming as $m):
              $overdue = strtotime($m['due_date']) < strtotime('today'); ?>
            <tr>
              <td style="width:74px">
                <span class="badge <?= $overdue ? 'risk' : '' ?>"><?= e(fmt_date($m['due_date'])) ?></span>
              </td>
              <td>
                <a href="case.php?id=<?= (int) $m['case_id'] ?>" class="t-name">
                  <?= e($m['last_name']) ?><?= $m['first_name'] ? ', ' . e($m['first_name']) : '' ?>
                </a>
                <div class="t-sub">
                  <?= e($m['milestone']) ?><?= $m['includes_signing'] ? ' + signing' : '' ?>
                </div>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      <?php endif; ?>
    </div>
  </div>
</div>

<script type="application/json" id="data-aging"><?= json_encode($agingRows) ?></script>
<script type="application/json" id="data-fees"><?= json_encode($fees) ?></script>
<script type="application/json" id="data-collections"><?= json_encode($collRows) ?></script>
<script type="application/json" id="data-pipeline"><?= json_encode($pipeRows) ?></script>

<?php layout_foot(true); ?>
