<?php
// ============================================================
//  MediCore — Profit Report
//  File: accounting/profit.php
// ============================================================
$page  = 'accounting/profit';
$title = 'Profit Report';
require_once '../includes/header.php';

// This page is nothing but profit figures, so it's gated by the
// "Profit Visibility" permission (User Management → Permissions) —
// separate from (and in addition to) the older 'profit' module
// permission that just controls the sidebar link's visibility.
require_permission('profit_view');

$cur = $settings['currency'];

// Default date range — current month
$from = $_GET['from'] ?? date('Y-m-01');
$to   = $_GET['to']   ?? date('Y-m-d');

// ── KPI Queries ───────────────────────────────────────────────
$totalSales = (float) db_val(
    "SELECT COALESCE(SUM(final_price),0) FROM sales
      WHERE date BETWEEN ? AND ?", [$from, $to]
);
$totalCost = (float) db_val(
    "SELECT COALESCE(SUM(si.cost * si.qty),0)
       FROM sale_items si
       JOIN sales s ON s.id = si.sale_id
      WHERE s.date BETWEEN ? AND ?", [$from, $to]
);
$grossProfit = $totalSales - $totalCost;
$totalExp    = (float) db_val(
    "SELECT COALESCE(SUM(amount),0) FROM expenses
      WHERE date BETWEEN ? AND ?", [$from, $to]
);
$netProfit   = $grossProfit - $totalExp;
$totalOrders = (int) db_val(
    "SELECT COUNT(*) FROM sales WHERE date BETWEEN ? AND ?", [$from, $to]
);
$margin = $totalSales > 0 ? ($grossProfit / $totalSales) * 100 : 0;

// ── Monthly breakdown (last 12 months or filtered range) ──────
$months = db_rows(
    "SELECT DATE_FORMAT(s.date,'%Y-%m')              AS month,
            COUNT(DISTINCT s.id)                     AS orders,
            COALESCE(SUM(s.final_price),0)           AS revenue,
            COALESCE(SUM(si.cost * si.qty),0)        AS cost,
            COALESCE(SUM(s.approx_profit),0)         AS profit,
            COALESCE(SUM(s.paid),0)                  AS collected,
            COALESCE(SUM(s.due),0)                   AS due
       FROM sales s
       JOIN sale_items si ON si.sale_id = s.id
      WHERE s.date BETWEEN ? AND ?
      GROUP BY DATE_FORMAT(s.date,'%Y-%m')
      ORDER BY month ASC",
    [$from, $to]
);

// ── Top 10 products by profit ─────────────────────────────────
$topProducts = db_rows(
    "SELECT si.product_name,
            SUM(si.qty)                        AS qty_sold,
            SUM(si.after_disc)                 AS revenue,
            SUM(si.cost * si.qty)              AS cost,
            SUM(si.after_disc - si.cost*si.qty) AS profit
       FROM sale_items si
       JOIN sales s ON s.id = si.sale_id
      WHERE s.date BETWEEN ? AND ?
      GROUP BY si.product_name
      ORDER BY profit DESC
      LIMIT 10",
    [$from, $to]
);

// ── Expense breakdown by category ─────────────────────────────
$expByCategory = db_rows(
    "SELECT category,
            COUNT(*)       AS count,
            SUM(amount)    AS total
       FROM expenses
      WHERE date BETWEEN ? AND ?
      GROUP BY category
      ORDER BY total DESC",
    [$from, $to]
);
?>

<!-- ── Filter bar ─────────────────────────────────── -->
<form method="GET" style="display:flex;gap:9px;align-items:center;
      flex-wrap:wrap;margin-bottom:14px;padding:10px 14px;
      background:var(--surface);border:1px solid var(--border);
      border-radius:var(--r)">
  <span style="font-size:12px;font-weight:600;color:var(--text2)">
    📅 Date Range:
  </span>
  <input type="date" name="from" value="<?= $from ?>"
    style="padding:5px 8px;border:1px solid var(--border);
           border-radius:var(--rsm);font-family:inherit;
           font-size:12px;outline:none">
  <span style="color:var(--text3);font-size:11px">to</span>
  <input type="date" name="to" value="<?= $to ?>"
    style="padding:5px 8px;border:1px solid var(--border);
           border-radius:var(--rsm);font-family:inherit;
           font-size:12px;outline:none">

  <!-- Quick range buttons -->
  <?php
  $ranges = [
    'Today'      => [date('Y-m-d'), date('Y-m-d')],
    'This Week'  => [date('Y-m-d', strtotime('monday this week')), date('Y-m-d')],
    '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')],
  ];
  foreach ($ranges as $label => [$rf, $rt]):
    $active = ($from === $rf && $to === $rt);
  ?>
  <a href="?from=<?= $rf ?>&to=<?= $rt ?>"
     class="btn btn-sm"
     style="<?= $active ? 'background:var(--brand);color:#fff;border-color:var(--brand)' : '' ?>">
    <?= $label ?>
  </a>
  <?php endforeach; ?>

  <button type="submit" class="btn btn-primary btn-sm">Apply</button>
</form>

<!-- ── KPI Cards ──────────────────────────────────── -->
<div style="display:grid;grid-template-columns:repeat(5,1fr);
            gap:10px;margin-bottom:14px">

  <div class="sc" style="border-top:3px solid var(--brand)">
    <div class="slabel">Total Sales</div>
    <div class="sval b" style="color:var(--brand)">
      <?= $cur . number_format($totalSales, 2) ?>
    </div>
    <div style="font-size:10px;color:var(--text3);margin-top:2px">
      <?= $totalOrders ?> invoice(s)
    </div>
  </div>

  <div class="sc" style="border-top:3px solid var(--warn)">
    <div class="slabel">Total Cost</div>
    <div class="sval b" style="color:var(--warn)">
      <?= $cur . number_format($totalCost, 2) ?>
    </div>
    <div style="font-size:10px;color:var(--text3);margin-top:2px">
      Cost of goods sold
    </div>
  </div>

  <div class="sc"
       style="border-top:3px solid <?= $grossProfit>=0?'var(--accent)':'var(--danger)' ?>">
    <div class="slabel">Gross Profit</div>
    <div class="sval b"
         style="color:<?= $grossProfit>=0?'var(--accent)':'var(--danger)' ?>">
      <?= $cur . number_format($grossProfit, 2) ?>
    </div>
    <div style="font-size:10px;color:var(--text3);margin-top:2px">
      Margin: <?= number_format($margin, 1) ?>%
    </div>
  </div>

  <div class="sc" style="border-top:3px solid var(--danger)">
    <div class="slabel">Expenses</div>
    <div class="sval b" style="color:var(--danger)">
      <?= $cur . number_format($totalExp, 2) ?>
    </div>
    <div style="font-size:10px;color:var(--text3);margin-top:2px">
      Operating costs
    </div>
  </div>

  <div class="sc"
       style="border-top:3px solid <?= $netProfit>=0?'var(--teal)':'var(--danger)' ?>;
              background:<?= $netProfit>=0?'var(--accent-xlight)':'#fff5f5' ?>">
    <div class="slabel">Net Profit</div>
    <div class="sval b"
         style="color:<?= $netProfit>=0?'var(--teal)':'var(--danger)' ?>;font-size:18px">
      <?= $cur . number_format($netProfit, 2) ?>
    </div>
    <div style="font-size:10px;margin-top:2px;
                color:<?= $netProfit>=0?'var(--teal)':'var(--danger)' ?>">
      <?= $netProfit >= 0 ? '▲ Profitable' : '▼ Loss' ?>
    </div>
  </div>

</div>

<!-- ── Chart + Expense breakdown ─────────────────── -->
<div style="display:grid;grid-template-columns:1fr 260px;
            gap:12px;margin-bottom:14px">

  <!-- Monthly trend chart -->
  <div class="card">
    <div class="ch">
      <div class="ct">📊 Monthly Revenue vs Profit</div>
    </div>
    <?php if ($months): ?>
    <canvas id="profitChart" height="160"></canvas>
    <?php else: ?>
    <div class="empty-state">No data for selected range</div>
    <?php endif; ?>
  </div>

  <!-- Expense by category -->
  <div class="card">
    <div class="ch"><div class="ct">💸 Expenses by Category</div></div>
    <?php if ($expByCategory): ?>
    <div style="display:flex;flex-direction:column;gap:6px;padding-top:4px">
      <?php foreach ($expByCategory as $ec):
        $pct = $totalExp > 0 ? ($ec['total'] / $totalExp) * 100 : 0;
      ?>
      <div>
        <div style="display:flex;justify-content:space-between;
                    font-size:11.5px;margin-bottom:3px">
          <span><?= htmlspecialchars($ec['category']) ?>
            <span style="color:var(--text3);font-size:10px">
              (<?= $ec['count'] ?>)
            </span>
          </span>
          <span class="mono" style="font-weight:700;color:var(--danger)">
            <?= $cur . number_format($ec['total'], 2) ?>
          </span>
        </div>
        <div style="height:5px;background:var(--border);
                    border-radius:3px;overflow:hidden">
          <div style="height:100%;width:<?= min(100,$pct) ?>%;
                      background:var(--danger);border-radius:3px">
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php else: ?>
    <div class="empty-state" style="padding:20px 0">No expenses</div>
    <?php endif; ?>
  </div>

</div>

<!-- ── Monthly breakdown table ───────────────────── -->
<div class="card" style="padding:0;margin-bottom:14px">
  <div class="ch" style="padding:10px 14px">
    <div class="ct">📅 Monthly Breakdown</div>
  </div>
  <?php if ($months): ?>
  <div class="tw">
    <table>
      <thead>
        <tr>
          <th>Month</th>
          <th style="text-align:center">Orders</th>
          <th style="text-align:right">Revenue</th>
          <th style="text-align:right">Cost</th>
          <th style="text-align:right">Gross Profit</th>
          <th style="text-align:center">Margin</th>
          <th style="text-align:right">Collected</th>
          <th style="text-align:right">Due</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($months as $m):
          $gp  = (float)$m['revenue'] - (float)$m['cost'];
          $mgn = (float)$m['revenue'] > 0
               ? ($gp / (float)$m['revenue']) * 100 : 0;
          $gpCl = $gp >= 0 ? 'var(--accent)' : 'var(--danger)';
        ?>
        <tr>
          <td style="font-weight:600">
            <?= date('M Y', strtotime($m['month'] . '-01')) ?>
          </td>
          <td style="text-align:center">
            <span class="badge"><?= $m['orders'] ?></span>
          </td>
          <td class="mono" style="text-align:right;font-weight:700">
            <?= $cur . number_format($m['revenue'], 2) ?>
          </td>
          <td class="mono" style="text-align:right;color:var(--warn)">
            <?= $cur . number_format($m['cost'], 2) ?>
          </td>
          <td class="mono"
              style="text-align:right;font-weight:700;color:<?= $gpCl ?>">
            <?= $cur . number_format($gp, 2) ?>
          </td>
          <td style="text-align:center">
            <span class="badge"
                  style="background:<?= $mgn>=20?'#d4f0e6':($mgn>=10?'#fff3dc':'#fde8e8') ?>;
                         color:<?= $mgn>=20?'var(--accent)':($mgn>=10?'var(--warn)':'var(--danger)') ?>">
              <?= number_format($mgn, 1) ?>%
            </span>
          </td>
          <td class="mono" style="text-align:right;color:var(--accent)">
            <?= $cur . number_format($m['collected'], 2) ?>
          </td>
          <td class="mono"
              style="text-align:right;color:<?= (float)$m['due']>0?'var(--danger)':'var(--text3)' ?>">
            <?= (float)$m['due'] > 0
              ? $cur . number_format($m['due'], 2) : '—' ?>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
      <tfoot>
        <tr style="background:var(--brand-xlight);font-weight:700">
          <td>Total</td>
          <td style="text-align:center"><?= array_sum(array_column($months,'orders')) ?></td>
          <td class="mono" style="text-align:right;color:var(--brand)">
            <?= $cur . number_format(array_sum(array_column($months,'revenue')), 2) ?>
          </td>
          <td class="mono" style="text-align:right;color:var(--warn)">
            <?= $cur . number_format(array_sum(array_column($months,'cost')), 2) ?>
          </td>
          <td class="mono" style="text-align:right;
               color:<?= $grossProfit>=0?'var(--accent)':'var(--danger)' ?>">
            <?= $cur . number_format($grossProfit, 2) ?>
          </td>
          <td style="text-align:center">
            <span class="badge"
                  style="background:<?= $margin>=20?'#d4f0e6':($margin>=10?'#fff3dc':'#fde8e8') ?>;
                         color:<?= $margin>=20?'var(--accent)':($margin>=10?'var(--warn)':'var(--danger)') ?>">
              <?= number_format($margin, 1) ?>%
            </span>
          </td>
          <td class="mono" style="text-align:right;color:var(--accent)">
            <?= $cur . number_format(array_sum(array_column($months,'collected')), 2) ?>
          </td>
          <td class="mono" style="text-align:right;color:var(--danger)">
            <?= $cur . number_format(array_sum(array_column($months,'due')), 2) ?>
          </td>
        </tr>
      </tfoot>
    </table>
  </div>
  <?php else: ?>
  <div class="empty-state">No sales data for selected range.</div>
  <?php endif; ?>
</div>

<!-- ── Top 10 products ────────────────────────────── -->
<div class="card" style="padding:0">
  <div class="ch" style="padding:10px 14px">
    <div class="ct">🏆 Top 10 Products by Profit</div>
    <span style="font-size:11px;color:var(--text3)">
      <?= date('d M Y', strtotime($from)) ?>
      → <?= date('d M Y', strtotime($to)) ?>
    </span>
  </div>
  <?php if ($topProducts): ?>
  <div class="tw">
    <table>
      <thead>
        <tr>
          <th style="width:38px">#</th>
          <th>Product Name</th>
          <th style="text-align:center">Qty Sold</th>
          <th style="text-align:right">Revenue</th>
          <th style="text-align:right">Cost</th>
          <th style="text-align:right">Profit</th>
          <th style="text-align:center">Margin</th>
          <th style="text-align:right;width:120px">Profit Bar</th>
        </tr>
      </thead>
      <tbody>
        <?php
        $maxProfit = max(1, max(array_column($topProducts, 'profit')));
        foreach ($topProducts as $i => $p):
          $pft  = (float)$p['profit'];
          $rev  = (float)$p['revenue'];
          $cst  = (float)$p['cost'];
          $mgn  = $rev > 0 ? ($pft / $rev) * 100 : 0;
          $bar  = max(0, min(100, ($pft / $maxProfit) * 100));
          $pCl  = $pft >= 0 ? 'var(--accent)' : 'var(--danger)';
          $rank = ['🥇','🥈','🥉'];
        ?>
        <tr>
          <td style="text-align:center;font-size:14px">
            <?= $rank[$i] ?? ($i + 1) ?>
          </td>
          <td style="font-weight:600;font-size:12px">
            <?= htmlspecialchars($p['product_name']) ?>
          </td>
          <td class="mono" style="text-align:center">
            <span class="badge"><?= number_format($p['qty_sold']) ?></span>
          </td>
          <td class="mono" style="text-align:right;font-weight:700">
            <?= $cur . number_format($rev, 2) ?>
          </td>
          <td class="mono" style="text-align:right;color:var(--warn)">
            <?= $cur . number_format($cst, 2) ?>
          </td>
          <td class="mono" style="text-align:right;font-weight:700;color:<?= $pCl ?>">
            <?= $cur . number_format($pft, 2) ?>
          </td>
          <td style="text-align:center">
            <span class="badge"
                  style="background:<?= $mgn>=20?'#d4f0e6':($mgn>=10?'#fff3dc':'#fde8e8') ?>;
                         color:<?= $mgn>=20?'var(--accent)':($mgn>=10?'var(--warn)':'var(--danger)') ?>">
              <?= number_format($mgn, 1) ?>%
            </span>
          </td>
          <td style="padding:8px 12px">
            <div style="height:6px;background:var(--border);
                        border-radius:3px;overflow:hidden">
              <div style="height:100%;width:<?= $bar ?>%;
                          background:<?= $pCl ?>;border-radius:3px">
              </div>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php else: ?>
  <div class="empty-state">No sales data for selected range.</div>
  <?php endif; ?>
</div>

<!-- ── Chart.js ──────────────────────────────────── -->
<?php if ($months): ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
new Chart(document.getElementById('profitChart').getContext('2d'), {
  data: {
    labels: <?= json_encode(array_map(
        fn($m) => date('M Y', strtotime($m['month'].'-01')), $months
    )) ?>,
    datasets: [
      {
        type: 'bar',
        label: 'Revenue',
        data: <?= json_encode(array_map(fn($m) => round((float)$m['revenue'],2), $months)) ?>,
        backgroundColor: 'rgba(45,58,140,0.65)',
        borderRadius: 4,
        order: 2
      },
      {
        type: 'line',
        label: 'Gross Profit',
        data: <?= json_encode(array_map(
            fn($m) => round((float)$m['revenue'] - (float)$m['cost'], 2), $months
        )) ?>,
        borderColor: 'rgba(26,158,110,1)',
        backgroundColor: 'rgba(26,158,110,0.08)',
        borderWidth: 2,
        pointRadius: 4,
        fill: true,
        tension: 0.35,
        order: 1
      }
    ]
  },
  options: {
    plugins: { legend: { labels: { font: { size: 10 } } } },
    scales: {
      y: { beginAtZero: true, ticks: { font: { size: 10 } } },
      x: { ticks:            { font: { size: 10 } } }
    }
  }
});
</script>
<?php endif; ?>

<?php require_once '../includes/footer.php'; ?>
