<?php /* finance/overview.php &mdash; Advanced Edition */
$sym    = setting('currency_symbol','Rs.');
$npClr  = $netProfit >= 0 ? '#16a34a' : '#dc2626';
$npBg   = $netProfit >= 0 ? '#f0fdf4' : '#fef2f2';
$npIcon = $netProfit >= 0 ? 'bi-trending-up' : 'bi-trending-down';

// P&L margin
$grossMargin = $sales['total'] > 0
    ? round(($netProfit / $sales['total']) * 100, 1)
    : 0;

// Cashflow data arrays
$cfLabels  = array_map(fn($r) => date('d M', strtotime($r['d'])), $cashflow);
$cfValues  = array_map(fn($r) => (float) $r['income'], $cashflow);
?>

<style>
/* ── Page hero ────────────────────────────────────────── */
.fo-hero{
  background:#0f172a;border-radius:14px;padding:20px 26px;color:#fff;
  margin-bottom:18px;border:1px solid #1e293b;box-shadow:0 4px 20px rgba(0,0,0,.15)
}
.fo-hero .page-title{font-size:1.2rem;font-weight:800;display:flex;align-items:center;gap:10px;margin-bottom:4px}
.fo-hero .page-meta{font-size:.78rem;color:#94a3b8;display:flex;align-items:center;gap:8px;flex-wrap:wrap}
.fo-hero .page-meta .sep{color:#334155}
.hero-btn{border-radius:10px;font-weight:600;font-size:.8rem;padding:7px 14px;
  display:inline-flex;align-items:center;gap:6px;text-decoration:none;transition:all .15s}
.btn-ghost{background:transparent;color:#94a3b8;border:1px solid #334155}
.btn-ghost:hover{background:#1e293b;color:#fff;border-color:#475569}

/* ── KPI tiles ───────────────────────────────────────── */
.fin-tile{border-radius:14px;padding:18px 20px;position:relative;overflow:hidden;height:100%;
  transition:transform .15s,box-shadow .15s}
.fin-tile:hover{transform:translateY(-2px);box-shadow:0 8px 24px rgba(0,0,0,.1)}
.fin-tile .ft-icon{width:40px;height:40px;border-radius:12px;display:flex;align-items:center;
  justify-content:center;font-size:1.1rem;margin-bottom:12px}
.fin-tile .ft-val{font-size:1.55rem;font-weight:900;line-height:1;margin-bottom:4px}
.fin-tile .ft-lbl{font-size:.65rem;text-transform:uppercase;letter-spacing:.07em;font-weight:700;opacity:.7}
.fin-tile .ft-sub{font-size:.72rem;margin-top:6px;opacity:.8}

/* ── Position cards ──────────────────────────────────── */
.pos-card{border-radius:14px;padding:16px 18px;border:1.5px solid transparent;height:100%;
  transition:transform .15s,box-shadow .15s}
.pos-card:hover{transform:translateY(-2px);box-shadow:0 6px 18px rgba(0,0,0,.08)}
.pos-card .pc-icon{width:38px;height:38px;border-radius:10px;display:flex;align-items:center;
  justify-content:center;font-size:1rem;margin-bottom:10px}
.pos-card .pc-val{font-size:1.35rem;font-weight:900;line-height:1;margin-bottom:5px}
.pos-card .pc-lbl{font-size:.65rem;text-transform:uppercase;letter-spacing:.06em;font-weight:700;margin-bottom:6px}
.pos-card .pc-link{font-size:.72rem;text-decoration:none;font-weight:600;display:inline-flex;align-items:center;gap:3px}

/* ── Date shortcut buttons ───────────────────────────── */
.date-shortcut{border-radius:8px;padding:4px 12px;font-size:.72rem;font-weight:600;
  border:1.5px solid #e2e8f0;background:#fff;color:#475569;cursor:pointer;text-decoration:none;
  transition:all .12s}
.date-shortcut.active,.date-shortcut:hover{background:#0f172a;color:#fff;border-color:#0f172a}

/* ── Cards ───────────────────────────────────────────── */
.fin-card{border-radius:14px;border:1px solid #e8ecf0;background:#fff;overflow:hidden;
  box-shadow:0 1px 6px rgba(0,0,0,.04)}
.fin-card-header{padding:12px 18px;border-bottom:1px solid #f1f5f9;display:flex;
  justify-content:space-between;align-items:center}
.fin-card-header .fch-title{font-size:.78rem;font-weight:700;color:#334155;
  display:flex;align-items:center;gap:6px}

/* ── Expense row ─────────────────────────────────────── */
.exp-row{display:flex;align-items:center;gap:10px;padding:7px 0;
  border-bottom:1px solid #f8fafc;font-size:.78rem}
.exp-row:last-child{border-bottom:none}
.exp-dot{width:10px;height:10px;border-radius:50%;flex-shrink:0}
</style>

<!-- ══════════════════════════════════════════════════ -->
<!-- HERO                                                -->
<!-- ══════════════════════════════════════════════════ -->
<div class="fo-hero">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
    <div>
      <div class="page-title">
        <i class="bi bi-graph-up-arrow" style="color:#0891b2"></i>
        Finance Overview
      </div>
      <div class="page-meta">
        <i class="bi bi-calendar3" style="font-size:.7rem"></i>
        <?=date('d M Y',strtotime($from))?> &ndash; <?=date('d M Y',strtotime($to))?>
        <span class="sep">&middot;</span>
        Net Result:
        <span style="color:<?=$netProfit>=0?'#6ee7b7':'#fca5a5'?>;font-weight:700">
          <?=$sym?><?=number_format(abs($netProfit),0)?>
          <?=$netProfit>=0?'Profit':'Loss'?>
        </span>
        <span class="sep">&middot;</span>
        Margin: <span style="color:#94a3b8;font-weight:600"><?=$grossMargin?>%</span>
      </div>
    </div>
    <div class="d-flex gap-2">
      <a href="<?=APP_URL?>/finance/accounts"    class="hero-btn btn-ghost"><i class="bi bi-wallet2"></i>Cash & Bank</a>
      <a href="<?=APP_URL?>/finance/credit-book" class="hero-btn btn-ghost"><i class="bi bi-journal-bookmark"></i>Credit Book</a>
      <a href="<?=APP_URL?>/cheques"             class="hero-btn btn-ghost"><i class="bi bi-bank2"></i>Cheques</a>
    </div>
  </div>
</div>

<?= flashMessages() ?>

<!-- ══════════════════════════════════════════════════ -->
<!-- DATE FILTER                                         -->
<!-- ══════════════════════════════════════════════════ -->
<div class="fin-card mb-4">
  <div class="card-body py-2">
    <form method="GET" action="<?=APP_URL?>/finance/overview"
          class="d-flex gap-2 flex-wrap align-items-center">
      <input type="date" name="from" class="form-control form-control-sm"
             value="<?=e($from)?>" style="width:140px">
      <span class="text-muted small">to</span>
      <input type="date" name="to" class="form-control form-control-sm"
             value="<?=e($to)?>" style="width:140px">
      <button class="btn btn-secondary btn-sm fw-semibold">
        <i class="bi bi-funnel me-1"></i>Apply
      </button>
      <?php foreach([
        'This Month' => [date('Y-m-01'),           date('Y-m-d')],
        'Last Month' => [date('Y-m-01',strtotime('first day of last month')),
                         date('Y-m-t',strtotime('last day of last month'))],
        'This Year'  => [date('Y-01-01'),           date('Y-m-d')],
      ] as $lbl => [$f,$t]):
        $act = ($from===$f && $to===$t);
      ?>
      <a href="?from=<?=$f?>&to=<?=$t?>"
         class="date-shortcut <?=$act?'active':''?>"><?=$lbl?></a>
      <?php endforeach;?>
    </form>
  </div>
</div>

<!-- ══════════════════════════════════════════════════ -->
<!-- ROW 1 &mdash; 4 KPI TILES                                -->
<!-- ══════════════════════════════════════════════════ -->
<div class="row g-3 mb-4">

  <div class="col-6 col-xl-3">
    <div class="fin-tile" style="background:linear-gradient(135deg,#1e3a8a,#2563eb);color:#fff">
      <div class="ft-icon" style="background:rgba(255,255,255,.15)">
        <i class="bi bi-receipt"></i>
      </div>
      <div class="ft-lbl">Total Sales</div>
      <div class="ft-val"><?=$sym?><?=number_format($sales['total'],0)?></div>
      <div class="ft-sub">
        <?=number_format($sales['cnt'])?> invoices &nbsp;&middot;&nbsp;
        Collected <?=$sym?><?=number_format((float)$sales['paid'],0)?>
      </div>
      <?php if((float)$sales['balance']>0):?>
      <div class="ft-sub" style="color:#bfdbfe">
        Due <?=$sym?><?=number_format((float)$sales['balance'],0)?>
      </div>
      <?php endif;?>
    </div>
  </div>

  <div class="col-6 col-xl-3">
    <div class="fin-tile" style="background:linear-gradient(135deg,#1e40af,#0891b2);color:#fff">
      <div class="ft-icon" style="background:rgba(255,255,255,.15)">
        <i class="bi bi-cart-fill"></i>
      </div>
      <div class="ft-lbl">Total Purchases</div>
      <div class="ft-val"><?=$sym?><?=number_format($purchases['total'],0)?></div>
      <div class="ft-sub">
        <?=number_format($purchases['cnt'])?> orders &nbsp;&middot;&nbsp;
        Paid <?=$sym?><?=number_format((float)$purchases['paid'],0)?>
      </div>
    </div>
  </div>

  <div class="col-6 col-xl-3">
    <div class="fin-tile" style="background:linear-gradient(135deg,#7f1d1d,#dc2626);color:#fff">
      <div class="ft-icon" style="background:rgba(255,255,255,.15)">
        <i class="bi bi-wallet2"></i>
      </div>
      <div class="ft-lbl">Total Expenses</div>
      <div class="ft-val"><?=$sym?><?=number_format($expenses['total'],0)?></div>
      <div class="ft-sub"><?=number_format($expenses['cnt'])?> expense entries</div>
    </div>
  </div>

  <div class="col-6 col-xl-3">
    <div class="fin-tile" style="background:linear-gradient(135deg,<?=$netProfit>=0?'#14532d,#16a34a':'#7f1d1d,#dc2626'?>);color:#fff">
      <div class="ft-icon" style="background:rgba(255,255,255,.15)">
        <i class="bi <?=$npIcon?>"></i>
      </div>
      <div class="ft-lbl">Net <?=$netProfit>=0?'Profit':'Loss'?></div>
      <div class="ft-val"><?=$sym?><?=number_format(abs($netProfit),0)?></div>
      <div class="ft-sub">
        Margin: <?=$grossMargin?>%
        <?php if((float)$sales['total']>0):?>
        &nbsp;&middot;&nbsp; <?=$sym?><?=number_format(abs($netProfit/$sales['cnt']),0)?>/invoice
        <?php endif;?>
      </div>
    </div>
  </div>

</div>

<!-- ══════════════════════════════════════════════════ -->
<!-- ROW 2 &mdash; POSITION CARDS                             -->
<!-- ══════════════════════════════════════════════════ -->
<div class="row g-3 mb-4">

  <!-- Receivables -->
  <div class="col-md-4">
    <div class="pos-card" style="background:#fffbeb;border-color:#fde68a">
      <div class="pc-icon" style="background:#fef9c3;color:#d97706">
        <i class="bi bi-arrow-down-left-circle-fill"></i>
      </div>
      <div class="pc-lbl" style="color:#d97706">Receivables &mdash; Owed to You</div>
      <div class="pc-val" style="color:#d97706"><?=$sym?><?=number_format($receivables,2)?></div>
      <div class="text-muted small mb-2">From credit customers</div>
      <?php if($chequesIn>0):?>
      <div class="d-flex align-items-center gap-1 mb-2"
           style="font-size:.72rem;color:#d97706;background:#fef9c3;
                  border-radius:8px;padding:4px 8px">
        <i class="bi bi-hourglass-split"></i>
        + <?=$sym?><?=number_format($chequesIn,0)?> in pending cheques
      </div>
      <?php endif;?>
      <a href="<?=APP_URL?>/finance/credit-book" class="pc-link" style="color:#d97706">
        View Credit Book <i class="bi bi-arrow-right"></i>
      </a>
    </div>
  </div>

  <!-- Payables -->
  <div class="col-md-4">
    <div class="pos-card" style="background:#fef2f2;border-color:#fca5a5">
      <div class="pc-icon" style="background:#fee2e2;color:#dc2626">
        <i class="bi bi-arrow-up-right-circle-fill"></i>
      </div>
      <div class="pc-lbl" style="color:#dc2626">Payables &mdash; You Owe</div>
      <div class="pc-val" style="color:#dc2626"><?=$sym?><?=number_format($payables,2)?></div>
      <div class="text-muted small mb-2">To suppliers</div>
      <?php if($chequesOut>0):?>
      <div class="d-flex align-items-center gap-1 mb-2"
           style="font-size:.72rem;color:#dc2626;background:#fee2e2;
                  border-radius:8px;padding:4px 8px">
        <i class="bi bi-hourglass-split"></i>
        + <?=$sym?><?=number_format($chequesOut,0)?> in pending cheques
      </div>
      <?php endif;?>
      <a href="<?=APP_URL?>/suppliers" class="pc-link" style="color:#dc2626">
        View Suppliers <i class="bi bi-arrow-right"></i>
      </a>
    </div>
  </div>

  <!-- Cash & Bank -->
  <div class="col-md-4">
    <div class="pos-card" style="background:#f0fdf4;border-color:#86efac">
      <div class="pc-icon" style="background:#dcfce7;color:#16a34a">
        <i class="bi bi-bank-fill"></i>
      </div>
      <div class="pc-lbl" style="color:#16a34a">Cash & Bank Position</div>
      <div class="pc-val" style="color:#16a34a"><?=$sym?><?=number_format($totalCashBank,2)?></div>
      <?php foreach($accounts as $acc):?>
      <div class="d-flex justify-content-between small mb-1">
        <span class="text-muted">
          <i class="bi <?=$acc['account_type']==='cash'?'bi-cash':'bi-bank'?> me-1"></i>
          <?=e($acc['account_name'])?>
        </span>
        <span class="fw-semibold text-success">
          <?=$sym?><?=number_format($acc['current_balance'],0)?>
        </span>
      </div>
      <?php endforeach;?>
      <a href="<?=APP_URL?>/finance/accounts" class="pc-link mt-1" style="color:#16a34a">
        Manage Accounts <i class="bi bi-arrow-right"></i>
      </a>
    </div>
  </div>

</div>

<!-- ══════════════════════════════════════════════════ -->
<!-- ROW 3 &mdash; CHARTS                                     -->
<!-- ══════════════════════════════════════════════════ -->
<div class="row g-3">

  <!-- Daily Cash Collected -->
  <div class="col-lg-7">
    <div class="fin-card h-100">
      <div class="fin-card-header">
        <div class="fch-title">
          <i class="bi bi-bar-chart-line text-primary"></i>
          Daily Cash Collected
        </div>
        <span class="text-muted" style="font-size:.7rem">
          <?=date('d M',strtotime($from))?> &ndash; <?=date('d M',strtotime($to))?>
        </span>
      </div>
      <div class="p-3">
        <?php if(empty($cashflow)):?>
        <div class="text-center text-muted py-5 small">
          <i class="bi bi-bar-chart d-block fs-2 mb-2 opacity-25"></i>
          No cash flow data for this period
        </div>
        <?php else:?>
        <canvas id="cashflowChart" height="120"></canvas>
        <?php endif;?>
      </div>
    </div>
  </div>

  <!-- Expense Breakdown + Summary -->
  <div class="col-lg-5">
    <div class="fin-card mb-3">
      <div class="fin-card-header">
        <div class="fch-title">
          <i class="bi bi-pie-chart text-danger"></i>
          Expense Breakdown
        </div>
      </div>
      <div class="p-3">
        <?php if(empty($expenseByCat)):?>
        <div class="text-center text-muted small py-3">No expenses this period</div>
        <?php else:?>
        <div class="row">
          <div class="col-7">
            <canvas id="expenseChart" height="140"></canvas>
          </div>
          <div class="col-5 ps-0">
            <?php
            $expColors=['#dc2626','#f97316','#d97706','#eab308','#84cc16','#22c55e','#06b6d4','#6366f1'];
            $expTotal = array_sum(array_column($expenseByCat,'total'));
            foreach($expenseByCat as $i=>$e):
              $pct = $expTotal>0?round((float)$e['total']/$expTotal*100):0;
            ?>
            <div class="exp-row">
              <span class="exp-dot" style="background:<?=$expColors[$i%8]?>"></span>
              <div class="flex-grow-1" style="min-width:0">
                <div class="fw-semibold text-truncate" style="font-size:.7rem">
                  <?=e($e['category_name'])?>
                </div>
                <div style="font-size:.65rem;color:#94a3b8"><?=$pct?>%</div>
              </div>
              <div class="text-end" style="font-size:.7rem;font-weight:700;white-space:nowrap">
                <?=$sym?><?=number_format((float)$e['total'],0)?>
              </div>
            </div>
            <?php endforeach;?>
          </div>
        </div>
        <?php endif;?>
      </div>
    </div>

    <!-- P&L Summary card -->
    <div class="fin-card">
      <div class="fin-card-header">
        <div class="fch-title">
          <i class="bi bi-calculator text-info"></i>
          P&L Summary
        </div>
      </div>
      <div class="p-3">
        <?php foreach([
          ['Revenue',   $sales['total'],     '#16a34a', '+'],
          ['Purchases', $purchases['total'],  '#dc2626', '−'],
          ['Expenses',  $expenses['total'],   '#dc2626', '−'],
        ] as [$lbl,$val,$clr,$pfx]):
          $barPct = $sales['total']>0 ? min(100,round((float)$val/$sales['total']*100)) : 0;
        ?>
        <div class="mb-3">
          <div class="d-flex justify-content-between align-items-center mb-1">
            <span class="small fw-semibold"><?=$lbl?></span>
            <span class="small fw-bold" style="color:<?=$clr?>">
              <?=$pfx?><?=$sym?><?=number_format((float)$val,0)?>
            </span>
          </div>
          <div style="height:5px;border-radius:3px;background:#f1f5f9">
            <div style="height:5px;border-radius:3px;width:<?=$barPct?>%;background:<?=$clr?>20;
                        outline:2px solid <?=$clr?>40"></div>
          </div>
        </div>
        <?php endforeach;?>
        <div class="d-flex justify-content-between align-items-center py-2 mt-1"
             style="border-top:2px solid #f1f5f9">
          <span class="fw-bold">Net <?=$netProfit>=0?'Profit':'Loss'?></span>
          <span class="fw-bold fs-5" style="color:<?=$npClr?>">
            <?=$sym?><?=number_format(abs($netProfit),0)?>
          </span>
        </div>
        <div style="font-size:.7rem;color:#94a3b8" class="text-end">
          <?=$grossMargin?>% margin
        </div>
      </div>
    </div>
  </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
(function(){
  // ── Daily Cashflow Bar Chart ──────────────────────────
  const cashCanvas = document.getElementById('cashflowChart');
  if(cashCanvas) {
    const vals = <?=json_encode($cfValues)?>;
    const maxV = Math.max(...vals, 1);
    new Chart(cashCanvas, {
      type: 'bar',
      data: {
        labels: <?=json_encode($cfLabels)?>,
        datasets: [{
          data: vals,
          backgroundColor: vals.map(v => v === maxV ? '#1d4ed8' : '#3b82f6'),
          borderRadius: 7,
          borderSkipped: false,
        }]
      },
      options: {
        plugins: {
          legend: { display: false },
          tooltip: {
            backgroundColor: '#0f172a',
            padding: 10,
            callbacks: {
              label: ctx => '  <?=$sym?> ' + ctx.parsed.y.toLocaleString()
            }
          }
        },
        scales: {
          x: { grid: { display: false }, ticks: { font: { size: 11 } } },
          y: {
            beginAtZero: true,
            grid: { color: '#f1f5f9' },
            ticks: { callback: v => '<?=$sym?>' + v.toLocaleString(), font: { size: 11 } }
          }
        },
        responsive: true,
        animation: { duration: 600 }
      }
    });
  }

  // ── Expense Doughnut ─────────────────────────────────
  const expCanvas = document.getElementById('expenseChart');
  if(expCanvas) {
    new Chart(expCanvas, {
      type: 'doughnut',
      data: {
        labels: <?=json_encode(array_column($expenseByCat??[],'category_name'))?>,
        datasets: [{
          data: <?=json_encode(array_map('floatval',array_column($expenseByCat??[],'total')))?>,
          backgroundColor: ['#dc2626','#f97316','#d97706','#eab308','#84cc16','#22c55e','#06b6d4','#6366f1'],
          borderWidth: 2,
          borderColor: '#fff',
          hoverOffset: 6
        }]
      },
      options: {
        cutout: '65%',
        plugins: { legend: { display: false } },
        animation: { duration: 500 }
      }
    });
  }
})();
</script>