<?php
// public/index.php
$pageTitle = 'Dashboard';
require_once('./config/db.php');
require_once("./includes/auth.php");
include('./includes/header.php');

// Totals (today / this month) using sale_items joined to sales_master (for Date)
$today = (new DateTime('today'))->format('Y-m-d');
$monthStart = (new DateTime('first day of this month'))->format('Y-m-01');

// Today
$todayStmt = $pdo->prepare("
    SELECT 
      COALESCE(SUM(si.TotalAmount),0) AS revenue,
      COALESCE(SUM(si.Quantity),0) AS items
    FROM sale_items si
    JOIN sales_master sm ON sm.SaleID = si.SaleID
    WHERE DATE(sm.Date) = ?
");
$todayStmt->execute([$today]);
$todayData = $todayStmt->fetch(PDO::FETCH_ASSOC);

// This month
$monthStmt = $pdo->prepare("
    SELECT 
      COALESCE(SUM(si.TotalAmount),0) AS revenue,
      COALESCE(SUM(si.Quantity),0) AS items
    FROM sale_items si
    JOIN sales_master sm ON sm.SaleID = si.SaleID
    WHERE sm.Date >= ? AND sm.Date < DATE_ADD(?, INTERVAL 1 MONTH)
");
$monthStmt->execute([$monthStart, $monthStart]);
$monthData = $monthStmt->fetch(PDO::FETCH_ASSOC);

// Best products overall (by quantity sold)
$bestStmt = $pdo->query("
    SELECT p.Name, COALESCE(SUM(si.Quantity),0) AS qty
    FROM sale_items si
    LEFT JOIN products p ON p.ProductID = si.ProductID
    GROUP BY si.ProductID
    ORDER BY qty DESC
    LIMIT 5
");
$best = $bestStmt->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
  .dashboard-card {
    border: none;
    border-radius: 18px;
    padding: 25px;
    background: #ffffff;
    box-shadow: 0 4px 14px rgba(0,0,0,0.08);
    transition: 0.2s ease-in-out;
  }
  .dashboard-card:hover {
    box-shadow: 0 8px 20px rgba(0,0,0,0.12);
    transform: translateY(-3px);
  }
  .card-title {
    font-size: 1.1rem;
    font-weight: 600;
    color: #555;
  }
  .card-value {
    font-size: 2rem;
    font-weight: 700;
    margin: 5px 0;
    color: #0d6efd;
  }
  .top-list li {
    border: none !important;
    padding: 12px 10px;
    background: #f9fbff;
    border-radius: 12px;
    margin-bottom: 6px;
  }
</style>

<div class="row g-4 mt-2">

  <div class="col-md-4">
    <div class="dashboard-card">
      <div class="d-flex justify-content-between">
        <h5 class="card-title">Today Revenue</h5>
        <i class="bi bi-cash-stack fs-2 text-primary"></i>
      </div>
      <div class="card-value">
        <?= number_format((float)($todayData['revenue'] ?? 0), 2) ?>
      </div>
      <p class="text-muted mb-0">Items sold: <?= (int)($todayData['items'] ?? 0) ?></p>
    </div>
  </div>

  <div class="col-md-4">
    <div class="dashboard-card">
      <div class="d-flex justify-content-between">
        <h5 class="card-title">This Month Revenue</h5>
        <i class="bi bi-bar-chart-line fs-2 text-primary"></i>
      </div>
      <div class="card-value">
        <?= number_format((float)($monthData['revenue'] ?? 0), 2) ?>
      </div>
      <p class="text-muted mb-0">Items sold: <?= (int)($monthData['items'] ?? 0) ?></p>
    </div>
  </div>

  <div class="col-md-4">
    <div class="dashboard-card">
      <div class="d-flex justify-content-between">
        <h5 class="card-title">Top Products</h5>
        <i class="bi bi-trophy fs-2 text-warning"></i>
      </div>

      <ul class="list-group top-list mt-3">
        <?php if (!empty($best)): ?>
          <?php foreach ($best as $row): ?>
            <li class="list-group-item d-flex justify-content-between align-items-center">
              <?= htmlspecialchars($row['Name'] ?? 'Unknown product') ?>
              <span class="badge bg-primary rounded-pill px-3 py-2"><?= (int)$row['qty'] ?></span>
            </li>
          <?php endforeach; ?>
        <?php else: ?>
          <li class="list-group-item text-center">No sales yet</li>
        <?php endif; ?>
      </ul>
    </div>
  </div>

</div>

<!-- SALE HISTORY TABLE WITH DATE FILTER -->
<div class="card mt-4">
    <div class="card-header bg-primary text-white">
        <h5 class="mb-0">Sales History</h5>
    </div>
    <div class="card-body">

        <?php
        // Get filter dates
        $fromDate = $_GET['from_date'] ?? '';
        $toDate = $_GET['to_date'] ?? '';

        // Prepare query with optional filter
        $sql = "
            SELECT 
                sm.SaleID,
                sm.Date,
                sm.CustomerName,
                sm.CustomerPhone,
                SUM(si.TotalAmount) AS TotalAmount
            FROM sales_master sm
            LEFT JOIN sale_items si ON si.SaleID = sm.SaleID
        ";

        $conditions = [];
        $params = [];

        if ($fromDate) {
            $conditions[] = "sm.Date >= ?";
            $params[] = $fromDate . " 00:00:00";
        }

        if ($toDate) {
            $conditions[] = "sm.Date <= ?";
            $params[] = $toDate . " 23:59:59";
        }

        if ($conditions) {
            $sql .= " WHERE " . implode(" AND ", $conditions);
        }

        $sql .= " GROUP BY sm.SaleID ORDER BY sm.Date DESC";

        $historyStmt = $pdo->prepare($sql);
        $historyStmt->execute($params);
        $sales = $historyStmt->fetchAll(PDO::FETCH_ASSOC);
        ?>

        <!-- Filter Form -->
        <form method="get" class="row g-2 mb-3">
            <div class="col-auto">
                <input type="date" class="form-control" name="from_date" value="<?= htmlspecialchars($fromDate) ?>" placeholder="From">
            </div>
            <div class="col-auto">
                <input type="date" class="form-control" name="to_date" value="<?= htmlspecialchars($toDate) ?>" placeholder="To">
            </div>
            <div class="col-auto">
                <button type="submit" class="btn btn-primary">Filter</button>
            </div>
            <div class="col-auto">
                <a href="index.php" class="btn btn-secondary">Reset</a>
            </div>
        </form>

        <!-- Table -->
        <div class="table-responsive">
            <table class="table table-bordered table-striped table-hover">
                <thead class="table-dark">
                    <tr>
                        <th>Sale ID</th>
                        <th>Date</th>
                        <th>Customer</th>
                        <th>Phone</th>
                        <th>Total Amount</th>
                    </tr>
                </thead>
                <tbody>
                <?php if ($sales): ?>
                    <?php foreach ($sales as $row): ?>
                    <tr>
                        <td><?= $row['SaleID'] ?></td>
                        <td><?= date("Y-m-d H:i", strtotime($row['Date'])) ?></td>
                        <td><?= htmlspecialchars($row['CustomerName']) ?></td>
                        <td><?= htmlspecialchars($row['CustomerPhone']) ?></td>
                        <td><?= number_format($row['TotalAmount'], 2) ?></td>
                    </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="5" class="text-center">No sales found</td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

    </div>
</div>



<?php include('./includes/footer.php'); ?>
