<?php
include "auth.php";
checkPermission(['admin','manager']); // allow all roles here
?>
<?php
require_once "db.php"; // $conn is mysqli

// === Helpers ===
function safe_query($conn, $sql) {
    $res = $conn->query($sql);
    if ($res === false) return null;
    return $res;
}
function fetch_all_assoc($res) {
    $arr = [];
    if (!$res) return $arr;
    while ($r = $res->fetch_assoc()) $arr[] = $r;
    return $arr;
}

$today = date('Y-m-d');

// === Summary ===
$res = safe_query($conn, "SELECT IFNULL(SUM(total),0) AS val FROM sales WHERE DATE(sale_date) = '$today'");
$total_sales = ($res ? (float)$res->fetch_assoc()['val'] : 0.0);

$res = safe_query($conn, "SELECT IFNULL(SUM(total),0) AS val FROM purchases WHERE DATE(purchase_date) = '$today'");
$total_purchases = ($res ? (float)$res->fetch_assoc()['val'] : 0.0);

$res = safe_query($conn, "SELECT IFNULL(SUM(amount),0) AS val FROM expenses WHERE DATE(created_at) = '$today'");
$total_expenses = ($res ? (float)$res->fetch_assoc()['val'] : 0.0);

$sell_profit = $total_sales - $total_purchases;

// === Top sale products ===
$sql = "SELECT si.product AS product_name, IFNULL(SUM(si.qty),0) AS qty, IFNULL(SUM(si.subtotal),0) AS total
        FROM sale_items si
        JOIN sales s ON si.sale_id = s.sale_id
        WHERE DATE(s.sale_date) = '$today'
        GROUP BY si.product
        ORDER BY total DESC";
$topProducts = fetch_all_assoc(safe_query($conn, $sql));

// === Expenses ===
$sql = "SELECT e.expense_id, e.expense_name, IFNULL(ec.category_name,'') AS category_name, e.amount
        FROM expenses e
        LEFT JOIN expense_categories ec ON e.category_id = ec.category_id
        WHERE DATE(e.created_at) = '$today'
        ORDER BY e.expense_id ASC";
$expenses = fetch_all_assoc(safe_query($conn, $sql));

// === Pay to Supplier ===
$sql = "SELECT dp.due_payment_id, dp.invoice_no, dp.payment_date, dp.amount, IFNULL(s.supplier_name,'') AS supplier_name
        FROM due_payments dp
        LEFT JOIN suppliers s ON dp.supplier_id = s.supplier_id
        WHERE DATE(dp.payment_date) = '$today'
        ORDER BY dp.due_payment_id DESC";
$payToSuppliers = fetch_all_assoc(safe_query($conn, $sql));

// === Receive from Customer ===
$sql = "SELECT dc.collection_id, dc.sale_id, dc.collected_amount, dc.collection_date, IFNULL(c.customer_name,'') AS customer_name
        FROM due_collection dc
        LEFT JOIN sales s ON dc.sale_id = s.sale_id
        LEFT JOIN customers c ON s.customer_id = c.customer_id
        WHERE DATE(dc.collection_date) = '$today'
        ORDER BY dc.collection_id DESC";
$receiveFromCustomers = fetch_all_assoc(safe_query($conn, $sql));

// === Totals ===
$tp_sum_qty=0; $tp_sum_total=0; foreach ($topProducts as $r){ $tp_sum_qty += (float)$r['qty']; $tp_sum_total += (float)$r['total']; }
$exp_sum=0; foreach($expenses as $r){ $exp_sum += (float)$r['amount']; }
$sup_sum=0; foreach($payToSuppliers as $r){ $sup_sum += (float)$r['amount']; }
$rc_sum=0; foreach($receiveFromCustomers as $r){ $rc_sum += (float)$r['collected_amount']; }
?>
<?php
// === Purchases (today) ===
$sql = "SELECT pi.product AS product_name, IFNULL(SUM(pi.qty),0) AS qty, IFNULL(SUM(pi.subtotal),0) AS total
        FROM purchase_items pi
        JOIN purchases p ON pi.purchase_id = p.purchase_id
        WHERE DATE(p.purchase_date) = '$today'
        GROUP BY pi.product
        ORDER BY total DESC";
$purchaseProducts = fetch_all_assoc(safe_query($conn, $sql));

// Totals
$pp_sum_qty=0; $pp_sum_total=0;
foreach ($purchaseProducts as $r){
    $pp_sum_qty += (float)$r['qty'];
    $pp_sum_total += (float)$r['total'];
}
?>


<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Today Report</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<style>
.cards { display:flex; gap:16px; flex-wrap:wrap; margin-bottom:18px; }
.card-stat { flex:1; padding:18px; border-radius:8px; color:#fff; min-width:180px; }
.bg-sale { background:#10b981; }
.bg-purchase { background:#ef4444; }
.bg-expense { background:#374151; }
.bg-profit { background:#14b8a6; }
.card-stat h6 { margin:0 0 8px 0; font-size:13px; color:rgba(255,255,255,0.9); }
.card-stat .big { font-size:22px; font-weight:700; }
.panel { background:#fff; border-radius:8px; padding:14px; box-shadow:0 6px 18px rgba(0,0,0,0.04); margin-bottom:18px; }
.panel h4 { margin:0 0 12px 0; font-weight:600; color:#111827; }
table { width:100%; border-collapse:collapse; margin-top:8px; }
table th, table td { padding:10px; border:1px solid #eef2f7; }
table thead th { background:#f8fafc; }
tfoot td { font-weight:700; background:#fbfdff; }
.text-right { text-align:right; }
.text-center { text-align:center; }
</style>
</head>
<body>
<!-- Global header start -->
        <?php
            include("global/header.php");
         ?>
        <!-- Global header end -->

            <!-- Main -->
            <main class="main">
                <header class="topbar">
                    <button class="hamburger" id="hamburger" aria-label="Toggle menu">☰</button>

                    <div style="margin-left:8px;font-weight:600">Dashboard <span class="topbar-menu-space"> > </span> Profit Loss Report</div>
                    <!-- Global Notification start -->
            <?php include("global/notify.php"); ?>
            <!-- Global Notification end -->
                    <div class="profile">
                    <button class="profile-btn" id="profileBtn" aria-expanded="false">
                        <span>Welcome <?php echo $_SESSION['username']; ?></span>
                        <img class="avatar" src="https://i.pravatar.cc/80" alt="Profile" />
                    </button>
                    <nav class="dropdown" id="profileDropdown">
                        <a href="profile.php">Profile Settings</a>
                        <a href="users.php">Users Settings</a>
                        <a href="logout.php">Logout</a>
                    </nav>
                </div>
                </header>

  <section class="content">
    <div class="container">
      <!-- Summary -->
      <div class="cards">
        <div class="card-stat bg-sale"><h6>SALE</h6><div class="big">৳ <?php echo number_format($total_sales,2); ?></div></div>
        <div class="card-stat bg-purchase"><h6>PURCHASE</h6><div class="big">৳ <?php echo number_format($total_purchases,2); ?></div></div>
        <div class="card-stat bg-expense"><h6>EXPENSE</h6><div class="big">৳ <?php echo number_format($total_expenses,2); ?></div></div>
        <div class="card-stat bg-profit"><h6>PROFIT</h6><div class="big">৳ <?php echo number_format($sell_profit,2); ?></div></div>
      </div>

      <!-- Row 1 -->
      <div class="row" style="display:flex; gap:16px; flex-wrap:wrap;">
        <div class="panel" style="flex:1; min-width:360px;">
          <h4>Top Sale Product</h4>
          <table id="topProductsTable">
            <thead><tr><th>#</th><th>Product</th><th>Qty</th><th class="text-right">Total (৳)</th></tr></thead>
            <tbody>
              <?php if(count($topProducts)>0): $i=1; foreach($topProducts as $row): ?>
                <tr>
                  <td><?php echo $i++; ?></td>
                  <td><?php echo htmlspecialchars($row['product_name']); ?></td>
                  <td><?php echo (int)$row['qty']; ?></td>
                  <td class="text-right"><?php echo number_format($row['total'],2); ?></td>
                </tr>
              <?php endforeach; else: ?>
                <!-- MUST output same number of td as header (4) to avoid DataTables error -->
                <tr><td></td><td class="text-center">No data available</td><td></td><td></td></tr>
              <?php endif; ?>
            </tbody>
            <tfoot><tr><td colspan="2">Total</td><td><?php echo (int)$tp_sum_qty; ?></td><td class="text-right"><?php echo number_format($tp_sum_total,2); ?></td></tr></tfoot>
          </table>
        </div>
        <div class="panel" style="flex:1; min-width:360px;">
  <h4>Top Purchase Product</h4>
  <table id="purchaseProductsTable">
    <thead>
      <tr>
        <th>#</th>
        <th>Product</th>
        <th>Qty</th>
        <th class="text-right">Total (৳)</th>
      </tr>
    </thead>
    <tbody>
      <?php if(count($purchaseProducts)>0): $i=1; foreach($purchaseProducts as $row): ?>
        <tr>
          <td><?php echo $i++; ?></td>
          <td><?php echo htmlspecialchars($row['product_name']); ?></td>
          <td><?php echo (int)$row['qty']; ?></td>
          <td class="text-right"><?php echo number_format($row['total'],2); ?></td>
        </tr>
      <?php endforeach; else: ?>
        <tr><td></td><td class="text-center">No data available</td><td></td><td></td></tr>
      <?php endif; ?>
    </tbody>
    <tfoot>
      <tr>
        <td colspan="2">Total</td>
        <td><?php echo (int)$pp_sum_qty; ?></td>
        <td class="text-right"><?php echo number_format($pp_sum_total,2); ?></td>
      </tr>
    </tfoot>
  </table>
</div>


        <div class="panel" style="flex:1; min-width:360px;">
          <h4>Expense</h4>
          <table id="expensesTable">
            <thead><tr><th>#</th><th>Expense</th><th>Category</th><th class="text-right">Amount (৳)</th></tr></thead>
            <tbody>
              <?php if(count($expenses)>0): $i=1; foreach($expenses as $row): ?>
                <tr>
                  <td><?php echo $i++; ?></td>
                  <td><?php echo htmlspecialchars($row['expense_name']); ?></td>
                  <td><?php echo htmlspecialchars($row['category_name']); ?></td>
                  <td class="text-right"><?php echo number_format($row['amount'],2); ?></td>
                </tr>
              <?php endforeach; else: ?>
                <!-- same number of tds (4) -->
                <tr><td></td><td class="text-center">No data available</td><td></td><td></td></tr>
              <?php endif; ?>
            </tbody>
            <tfoot><tr><td colspan="3">Total</td><td class="text-right"><?php echo number_format($exp_sum,2); ?></td></tr></tfoot>
          </table>
        </div>
      </div>

      <!-- Row 2 -->
      <div class="row" style="display:flex; gap:16px; flex-wrap:wrap;">
        <div class="panel" style="flex:1; min-width:360px;">
          <h4>Pay to Supplier</h4>
          <table id="paySupplierTable">
            <thead><tr><th>#</th><th>Supplier</th><th>Date</th><th class="text-right">Amount (৳)</th></tr></thead>
            <tbody>
              <?php if(count($payToSuppliers)>0): $i=1; foreach($payToSuppliers as $row): ?>
                <tr>
                  <td><?php echo $i++; ?></td>
                  <td><?php echo htmlspecialchars($row['supplier_name']); ?> <?php if(!empty($row['invoice_no'])) echo ' (Inv: '.htmlspecialchars($row['invoice_no']).')'; ?></td>
                  <td><?php echo htmlspecialchars($row['payment_date']); ?></td>
                  <td class="text-right"><?php echo number_format($row['amount'],2); ?></td>
                </tr>
              <?php endforeach; else: ?>
                <tr><td></td><td class="text-center">No data available</td><td></td><td></td></tr>
              <?php endif; ?>
            </tbody>
            <tfoot><tr><td colspan="3">Total</td><td class="text-right"><?php echo number_format($sup_sum,2); ?></td></tr></tfoot>
          </table>
        </div>

        <div class="panel" style="flex:1; min-width:360px;">
          <h4>Receive from Customer</h4>
          <table id="receiveCustomerTable">
            <thead><tr><th>#</th><th>Customer</th><th>Date</th><th class="text-right">Amount (৳)</th></tr></thead>
            <tbody>
              <?php if(count($receiveFromCustomers)>0): $i=1; foreach($receiveFromCustomers as $row): ?>
                <tr>
                  <td><?php echo $i++; ?></td>
                  <td><?php echo htmlspecialchars($row['customer_name']); ?> <?php if(!empty($row['sale_id'])) echo '(Sale ID: '.(int)$row['sale_id'].')'; ?></td>
                  <td><?php echo htmlspecialchars($row['collection_date']); ?></td>
                  <td class="text-right"><?php echo number_format($row['collected_amount'],2); ?></td>
                </tr>
              <?php endforeach; else: ?>
                <tr><td></td><td class="text-center">No data available</td><td></td><td></td></tr>
              <?php endif; ?>
            </tbody>
            <tfoot><tr><td colspan="3">Total</td><td class="text-right"><?php echo number_format($rc_sum,2); ?></td></tr></tfoot>
          </table>
        </div>
      </div>
    </div>
  </section>
</main>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script>
$('#topProductsTable, #purchaseProductsTable, #expensesTable, #paySupplierTable, #receiveCustomerTable').DataTable({
  paging:true, pageLength:5, lengthChange:false, ordering:true, info:false, searching:true
});

</script>
 <script>
            // Sidebar accordion: click ONLY the top-level buttons, not the whole LI.
            const submenuButtons = document.querySelectorAll(".has-submenu > .menu-link");
            submenuButtons.forEach((btn) => {
                btn.addEventListener("click", (e) => {
                    e.preventDefault(); // keep as a toggle, no page jump
                    const currentItem = btn.parentElement; // .has-submenu
                    const isOpen = currentItem.classList.contains("open");

                    // Close other open menus (accordion behavior)
                    document.querySelectorAll(".has-submenu.open").forEach((li) => {
                        if (li !== currentItem) {
                            li.classList.remove("open");
                            const b = li.querySelector(".menu-link");
                            if (b) b.setAttribute("aria-expanded", "false");
                        }
                    });

                    // Toggle current
                    currentItem.classList.toggle("open");
                    btn.setAttribute("aria-expanded", String(!isOpen));
                });
            });

            // Ensure clicks inside submenu DO NOT toggle/close the parent unintentionally
            document.querySelectorAll(".submenu").forEach((ul) => {
                ul.addEventListener("click", (e) => {
                    e.stopPropagation();
                });
            });

            // Mobile: show/hide sidebar
            const sidebar = document.getElementById("sidebar");
            const hamburger = document.getElementById("hamburger");
            hamburger.addEventListener("click", () => {
                sidebar.classList.toggle("active");
            });

            // Close sidebar when clicking outside on small screens
            document.addEventListener("click", (e) => {
                const isClickInside = sidebar.contains(e.target) || hamburger.contains(e.target);
                if (!isClickInside && sidebar.classList.contains("active")) {
                    sidebar.classList.remove("active");
                }
            });

            // Profile dropdown
            const profileBtn = document.getElementById("profileBtn");
            const profileDropdown = document.getElementById("profileDropdown");
            profileBtn.addEventListener("click", (e) => {
                e.stopPropagation();
                const open = profileDropdown.classList.toggle("open");
                profileBtn.setAttribute("aria-expanded", String(open));
            });
            document.addEventListener("click", () => profileDropdown.classList.remove("open"));
        </script>
</body>
</html>
