<?php
// ============================================================
//  MediCore — Dashboard
//  File: dashboard.php
// ============================================================
$page  = 'dashboard';
$title = 'Dashboard';
require_once 'includes/header.php';

$cfg   = $settings;
$cur   = $cfg['currency'];
$today = today();

// ── KPI queries ───────────────────────────────────────────────
$todaySales     = db_rows("SELECT * FROM sales     WHERE date = ?", [$today]);
$todayPurchases = db_rows("SELECT * FROM purchases WHERE date = ?", [$today]);

$saleTotal  = array_sum(array_column($todaySales,     'final_price'));
$saleProfit = array_sum(array_column($todaySales,     'approx_profit'));
$purchTotal = array_sum(array_column($todayPurchases, 'final_price'));

$totalCash = (float) db_val(
    "SELECT COALESCE(SUM(IF(type='in',amount,-amount)),0) FROM cash_ledger"
);

$expiredCount = (int) db_val(
    "SELECT COUNT(DISTINCT product_id) FROM purchase_items
      WHERE exp != '' AND exp < DATE_FORMAT(NOW(),'%Y-%m')"
);
$lowStockCount = (int) db_val(
    "SELECT COUNT(*) FROM products
      WHERE is_active=1 AND stock_pcs > 0
        AND low_stock_alert > 0 AND stock_pcs < low_stock_alert"
);
$outStockCount = (int) db_val(
    "SELECT COUNT(*) FROM products WHERE is_active=1 AND stock_pcs <= 0"
);
$pendingReqs   = (int) db_val(
    "SELECT COUNT(*) FROM requisitions WHERE status IN ('active','ordered')"
);
$pendingPOs    = (int) db_val(
    "SELECT COUNT(*) FROM purchases WHERE due > 0"
);
$totalProducts  = (int) db_val("SELECT COUNT(*) FROM products  WHERE is_active=1");
$totalCustomers = (int) db_val("SELECT COUNT(*) FROM customers WHERE id > 1");
$supplierDue    = (float) db_val("SELECT COALESCE(SUM(balance),0) FROM suppliers");
$customerDue    = (float) db_val("SELECT COALESCE(SUM(due),0)     FROM customers");
$customerAdv    = (float) db_val("SELECT COALESCE(SUM(advance),0) FROM customers WHERE id > 1");

// Stock value = sum of (stock_pcs × sale_price)
$stockValue = (float) db_val(
    "SELECT COALESCE(SUM(stock_pcs * sale_price),0) FROM products WHERE is_active=1"
);

// Monthly totals for comparison
$monthSales = (float) db_val(
    "SELECT COALESCE(SUM(final_price),0) FROM sales
      WHERE DATE_FORMAT(date,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m')"
);
$monthPurch = (float) db_val(
    "SELECT COALESCE(SUM(final_price),0) FROM purchases
      WHERE DATE_FORMAT(date,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m')"
);

// ── Monthly sales chart data (last 6 months) ─────────────────
$months = [];
for ($i = 5; $i >= 0; $i--) {
    $m      = date('Y-m', strtotime("-$i months"));
    $amt    = (float) db_val(
        "SELECT COALESCE(SUM(final_price),0) FROM sales
          WHERE DATE_FORMAT(date,'%Y-%m') = ?", [$m]
    );
    $profit = (float) db_val(
        "SELECT COALESCE(SUM(approx_profit),0) FROM sales
          WHERE DATE_FORMAT(date,'%Y-%m') = ?", [$m]
    );
    $months[] = [
        'label'  => date('M', strtotime("$m-01")),
        'amount' => $amt,
        'profit' => $profit,
    ];
}
?>

<!-- ── Page action buttons ────────────────────────── -->
<script>
document.getElementById('ph-actions').innerHTML =
  `<a class="btn btn-primary btn-sm" href="sale/entry.php">🛒 New Sale</a>
   <a class="btn btn-sm"            href="purchase/entry.php">📦 New Purchase</a>`;
</script>

<!-- ── Row 1 — Main KPIs ──────────────────────────── -->
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:10px">

  <div class="sc" style="border-top:3px solid var(--accent)">
    <div class="slabel">Today's Sales</div>
    <div class="sval b"><?= $cur . number_format($saleTotal, 2) ?></div>
    <div style="font-size:10px;color:var(--text2);margin-top:3px">
      <?= count($todaySales) ?> invoice(s)
    </div>
  </div>

  <div class="sc" style="border-top:3px solid var(--brand)">
    <div class="slabel">Today's Purchase</div>
    <div class="sval b" style="color:var(--brand)"><?= $cur . number_format($purchTotal, 2) ?></div>
    <div style="font-size:10px;color:var(--text2);margin-top:3px">
      <?= count($todayPurchases) ?> PO(s)
    </div>
  </div>

  <div class="sc" style="border-top:3px solid <?= $saleProfit >= 0 ? 'var(--accent)' : 'var(--danger)' ?>">
    <div class="slabel">Today's Profit</div>
    <div class="sval b" style="color:<?= $saleProfit >= 0 ? 'var(--accent)' : 'var(--danger)' ?>">
      <?= $cur . number_format($saleProfit, 2) ?>
    </div>
    <div style="font-size:10px;color:var(--text2);margin-top:3px">Approx.</div>
  </div>

  <div class="sc" style="border-top:3px solid var(--warn)">
    <div class="slabel">Cash Balance</div>
    <div class="sval b" style="color:var(--warn)"><?= $cur . number_format($totalCash, 2) ?></div>
    <div style="font-size:10px;color:var(--text2);margin-top:3px">All accounts</div>
  </div>

</div>

<!-- ── Row 2 — Business Stats ────────────────────── -->
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:10px">

  <div class="sc">
    <div class="slabel">Total Products</div>
    <div class="sval b"><?= $totalProducts ?></div>
  </div>

  <div class="sc">
    <div class="slabel">Total Customers</div>
    <div class="sval b"><?= $totalCustomers ?></div>
  </div>

  <div class="sc">
    <div class="slabel">Customer Due</div>
    <div class="sval b" style="color:var(--danger)"><?= $cur . number_format($customerDue, 2) ?></div>
    <div style="font-size:10px;color:var(--text3);margin-top:2px">Outstanding</div>
  </div>

  <div class="sc">
    <div class="slabel">Supplier Payable</div>
    <div class="sval b" style="color:var(--brand)"><?= $cur . number_format($supplierDue, 2) ?></div>
    <div style="font-size:10px;color:var(--text3);margin-top:2px">Outstanding</div>
  </div>

</div>

<!-- ── Row 3 — Stock Value + Advance + POs ───────── -->
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:10px">

  <div class="sc" style="border-top:3px solid var(--teal);cursor:pointer"
       onclick="location='product/list.php'">
    <div class="slabel">Total Stock Value</div>
    <div class="sval b" style="color:var(--teal)"><?= $cur . number_format($stockValue, 0) ?></div>
    <div style="font-size:10px;color:var(--text3);margin-top:2px">All active products</div>
  </div>

  <div class="sc" style="border-top:3px solid var(--accent);cursor:pointer"
       onclick="location='customer/list.php'">
    <div class="slabel">Customer Advance</div>
    <div class="sval b" style="color:var(--accent)"><?= $cur . number_format($customerAdv, 2) ?></div>
    <div style="font-size:10px;color:var(--text3);margin-top:2px">Pre-paid balance</div>
  </div>

  <div class="sc" style="border-top:3px solid var(--warn);cursor:pointer"
       onclick="location='purchase/list.php'">
    <div class="slabel">Pending PO Dues</div>
    <div class="sval b" style="color:var(--warn)"><?= $pendingPOs ?></div>
    <div style="font-size:10px;color:var(--text3);margin-top:2px">Purchase orders with due</div>
  </div>

  <div class="sc" style="border-top:3px solid var(--purple)">
    <div class="slabel">This Month Sales</div>
    <div class="sval b" style="color:var(--purple)"><?= $cur . number_format($monthSales, 0) ?></div>
    <div style="font-size:10px;color:var(--text3);margin-top:2px">
      Purchase: <?= $cur . number_format($monthPurch, 0) ?>
    </div>
  </div>

</div>

<!-- ── Row 4 — Stock Alerts ──────────────────────── -->
<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:12px">

  <?php if ($expiredCount > 0): ?>
  <div class="al al-d" style="cursor:pointer" onclick="location='product/expired.php'">
    ⏰ <strong><?= $expiredCount ?></strong> expired product batch(es) — click to review
  </div>
  <?php else: ?>
  <div class="al al-s">✅ No expired products</div>
  <?php endif; ?>

  <?php if ($lowStockCount > 0): ?>
  <div class="al al-w" style="cursor:pointer" onclick="location='product/list.php'">
    ⚠ <strong><?= $lowStockCount ?></strong> product(s) low on stock
  </div>
  <?php else: ?>
  <div class="al al-s">✅ Stock levels OK</div>
  <?php endif; ?>

  <?php if ($outStockCount > 0): ?>
  <div class="al al-d" style="cursor:pointer" onclick="location='product/list.php'">
    🚫 <strong><?= $outStockCount ?></strong> product(s) out of stock
  </div>
  <?php else: ?>
  <div class="al al-s">✅ No out-of-stock items</div>
  <?php endif; ?>

</div>

<!-- ── Pending Requisitions widget ────────────────── -->
<?php if ($pendingReqs > 0): ?>
<div style="display:flex;gap:10px;margin-bottom:12px">
  <div class="al al-w" style="flex:1;cursor:pointer"
       onclick="location='product/req-record.php'">
    📝 <strong><?= $pendingReqs ?></strong> pending requisition(s) awaiting purchase order
    — <a href="product/req-record.php" style="color:var(--brand);font-weight:600">
         View Requisitions →
       </a>
  </div>
  <div class="al al-i" style="flex:1;cursor:pointer"
       onclick="location='product/smart-requisition.php'">
    🤖 Smart Requisition available
    — <a href="product/smart-requisition.php" style="color:var(--brand);font-weight:600">
         View Priority List →
       </a>
  </div>
</div>
<?php endif; ?>

<!-- ── Row 4 — Chart + Recent Sales ─────────────── -->
<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">

  <div class="card">
    <div class="ch"><div class="ct">📊 6-Month Sales vs Profit</div></div>
    <canvas id="salesChart" height="170"></canvas>
  </div>

  <div class="card">
    <div class="ch">
      <div class="ct">🧾 Today's Sales</div>
      <a href="sale/list.php" style="font-size:11px;color:var(--brand)">View all →</a>
    </div>
    <?php if ($todaySales): ?>
    <div class="tw"><table>
      <thead><tr>
        <th>Invoice</th><th>Customer</th><th>Amount</th><th>Status</th>
      </tr></thead>
      <tbody>
        <?php foreach (array_slice($todaySales, 0, 8) as $s): ?>
        <tr>
          <td class="mono" style="color:var(--brand);font-weight:700">
            <?= htmlspecialchars($s['invoice']) ?>
          </td>
          <td><?= htmlspecialchars($s['customer_name']) ?></td>
          <td class="mono"><?= $cur . number_format($s['final_price'], 2) ?></td>
          <td>
            <?php
              $bc = match($s['status']) {
                'Paid'    => 'background:#d4f0e6;color:var(--accent)',
                'Partial' => 'background:#fff3dc;color:var(--warn)',
                default   => 'background:#fde8e8;color:var(--danger)',
              };
            ?>
            <span class="badge" style="<?= $bc ?>"><?= $s['status'] ?></span>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table></div>
    <?php else: ?>
    <div class="empty-state">No sales today</div>
    <?php endif; ?>
  </div>

</div>

<!-- ── Chart.js ──────────────────────────────────── -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
new Chart(document.getElementById('salesChart').getContext('2d'), {
  type: 'bar',
  data: {
    labels: <?= json_encode(array_column($months, 'label'))  ?>,
    datasets: [
      {
        label: 'Sales',
        data:  <?= json_encode(array_column($months, 'amount')) ?>,
        backgroundColor: 'rgba(45,58,140,0.7)',
        borderRadius: 4,
        order: 2
      },
      {
        label: 'Profit',
        data:  <?= json_encode(array_column($months, 'profit')) ?>,
        type:  'line',
        borderColor: 'rgba(26,158,110,1)',
        backgroundColor: 'rgba(26,158,110,0.1)',
        borderWidth: 2,
        pointRadius: 3,
        fill: true,
        tension: 0.3,
        order: 1
      }
    ]
  },
  options: {
    plugins: { legend: { labels: { font: { size: 10 } } } },
    scales: {
      y: { beginAtZero: true, ticks: { font: { size: 10 } } },
      x: { ticks:            { font: { size: 10 } } }
    }
  }
});
</script>

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