<?php
include "auth.php";
checkPermission(['admin','manager']); // allow all roles here
?>
<?php


include 'db.php'; // DB connection ($conn is mysqli)

// safe search input
$search = "";
if (isset($_GET['search'])) {
    $search = $conn->real_escape_string(trim($_GET['search']));
}

// Supplier Ledger Summary Query (aggregate purchases per supplier to avoid row-multiplication)
$sql = "SELECT 
            s.supplier_id, 
            s.supplier_name, 
            s.phone AS supplier_phone,
            IFNULL(p.total_purchase,0) AS total_purchase,
            IFNULL(p.total_paid,0) AS total_paid,
            (IFNULL(p.total_purchase,0) - IFNULL(p.total_paid,0)) AS total_due
        FROM suppliers s
        LEFT JOIN (
            SELECT supplier_id, 
                   SUM(total) AS total_purchase,
                   SUM(paid)  AS total_paid
            FROM purchases
            GROUP BY supplier_id
        ) p ON s.supplier_id = p.supplier_id
        WHERE (s.supplier_name LIKE '%$search%' OR s.phone LIKE '%$search%')
        ORDER BY s.supplier_name ASC";

$result = $conn->query($sql);
if (!$result) {
    die("SQL Error: " . $conn->error);
}

// Totals for footer
$total_purchase = $total_paid = $total_due = 0.0;
$rows = [];
while ($row = $result->fetch_assoc()) {
    // Ensure numeric types
    $row['total_purchase'] = (float)$row['total_purchase'];
    $row['total_paid']     = (float)$row['total_paid'];
    $row['total_due']      = (float)$row['total_due'];

    $rows[] = $row;
    $total_purchase += $row['total_purchase'];
    $total_paid     += $row['total_paid'];
    $total_due      += $row['total_due'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Suppliers Ledger</title>
  <link rel="stylesheet" href="css/style.css">
  <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
  <style>
    table { width:100%; border-collapse:collapse; margin-top:20px; }
    th, td { border:1px solid #e5e7eb; padding:10px; text-align:center; }
    th { background:#f3f4f6; }
    tfoot td { font-weight:bold; background:#f9fafb; }

    /* Modal + overlay */
    #modalOverlay {
      display:none;
      position:fixed;
      top:0; left:0; width:100%; height:100%;
      background:rgba(0,0,0,0.6);
      z-index:9998;
    }
    #detailsModal {
      display:none;
      position:fixed;
      top:6%; left:50%; transform:translateX(-50%);
      width:88%;
      max-width:1100px;
      max-height:86%;
      overflow:auto;
      background:#fff;
      border:1px solid #ccc;
      padding:20px;
      z-index:9999;
      border-radius:8px;
      box-shadow:0 2px 18px rgba(0,0,0,0.35);
    }
    #detailsModal h3 { margin-top:0; }
    #detailsModal .btn-close { margin-top:10px; background:#ef4444; color:#fff; border:none; padding:8px 14px; border-radius:6px; cursor:pointer; }
    #detailsModal .btn-print { margin-left:8px; background:#10b981; color:#fff; border:none; padding:8px 14px; border-radius:6px; cursor:pointer; }
    .supplier-header { display:flex; justify-content:space-between; align-items:flex-start; gap:10px; margin-bottom:12px; }
    .supplier-header .left { font-weight:600; }
    .small-muted { color:#6b7280; font-size:13px; }
    .items-table th, .items-table td { padding:8px; border:1px solid #e5e7eb; }
  </style>
</head>
<body class="suppliers-ledger-page">
<?php include("global/header.php"); ?>

<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> Suppliers Ledger</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 htmlspecialchars($_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">

      <div>
        <form method="get"  class="filter-box">
          <div class="form-group">
            <input type="text" name="search" placeholder="Search by Name or Phone" value="<?php echo htmlspecialchars($search); ?>">
          </div>
          <div class="form-group">
            <button type="submit">Search</button>
          </div>
          <div class="form-group">
              <a href="suppliers-ledger.php"><button type="button" class="filter-reset-btn">Reset</button></a>
          </div>
          <div class="form-group">
            <button onclick="printReport()" style="background:#10b981;">🖨️ Print</button>
          </div>
        </form>
        
      </div>

      <table id="ledgerTable">
        <thead>
          <tr>
            <th>Supplier Name</th>
            <th>Phone</th>
            <th>Total Purchase</th>
            <th>Paid</th>
            <th>Due</th>
            <th style="text-align: center">Action</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($rows as $row) { ?>
            <tr>
              <td><?php echo htmlspecialchars($row['supplier_name']); ?></td>
              <td><?php echo htmlspecialchars($row['supplier_phone']); ?></td>
              <td><?php echo number_format($row['total_purchase'], 2); ?></td>
              <td><?php echo number_format($row['total_paid'], 2); ?></td>
              <td><?php echo number_format($row['total_due'], 2); ?></td>
              <td style="text-align: center"><button class="btn btn-view" onclick="viewDetails(<?php echo (int)$row['supplier_id']; ?>)">View</button></td>
            </tr>
          <?php } ?>
        </tbody>
        <tfoot>
          <tr>
            <td colspan="2">Total</td>
            <td><?php echo number_format($total_purchase, 2); ?></td>
            <td><?php echo number_format($total_paid, 2); ?></td>
            <td><?php echo number_format($total_due, 2); ?></td>
            <td>-</td>
          </tr>
        </tfoot>
      </table>
    </div>
  </section>
</main>

<!-- Overlay + Modal -->
<div id="modalOverlay"></div>
<div id="detailsModal" role="dialog" aria-modal="true" aria-labelledby="modalTitle">
  <div style="display:flex; justify-content:space-between; align-items:center;">
    <h3 id="modalTitle">Supplier Purchase Details</h3>
    <div>
      <button class="btn-print" id="modalPrintBtn" onclick="printModalContent()">🖨️ Print</button>
      <button class="btn-close" onclick="closeModal()">Close</button>
    </div>
  </div>
  <div id="detailsContent">Loading...</div>
</div>

<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function(){
  $('#ledgerTable').DataTable({
    "pageLength": 10
  });

  // close modal when overlay clicked
  $('#modalOverlay').on('click', function(){ closeModal(); });

  // prevent form submit when printing
  $(document).on('click', '#printButton', function(e){
    e.preventDefault();
    printReport();
  });
});

// Load supplier ledger details in modal
function viewDetails(supplierId) {
  $.ajax({
    url: "supplier_ledger_details.php",
    type: "GET",
    data: { supplier_id: supplierId },
    success: function(data){
      $('#detailsContent').html(data);
      $('#modalOverlay').show();
      $('#detailsModal').show();
    }
  });
}

function closeModal() {
  $('#modalOverlay').hide();
  $('#detailsModal').hide();
}

// ✅ Print main supplier ledger table
function printReport() {
  var table = document.querySelector("#ledgerTable").cloneNode(true);

  // remove last column (Action) from each row (header/body/footer)
  for (var i = 0; i < table.rows.length; i++) {
    if (table.rows[i].cells.length > 0) {
      table.rows[i].deleteCell(-1);
    }
  }

  var win = window.open('', '', 'height=700,width=900');
  win.document.write('<html><head><title>Suppliers Ledger</title>');
  win.document.write('<style>');
  win.document.write(`
  body {
    font-family: Arial, sans-serif;
    margin: 20px;
}
.global-print .print-bg{
    height: auto !important;
  }
    table{width:100%;border-collapse:collapse;}
    th,td{border:1px solid #ddd;padding:8px;text-align:center;}
    th{background:#f3f4f6;}
    tfoot td{font-weight:bold;background:#f9fafb;}
  `);
  win.document.write('</style></head><body class="global-print">');
  win.document.write(`
    <?php
    include("global/global-print-heading.php");
?>
<main class="print-body-content">
<h2 style="text-align: center; text-decoration: underline;">Supplier Ledger</h2>
  `);
  win.document.write(table.outerHTML);
  win.document.write(`

  </main>
    <?php
    include("global/global-print-footer.php");
?>
  `);
  win.document.write('</body></html>');
  win.document.close();
  win.focus();
  win.print();
}

// ✅ Print modal details
function printModalContent() {
  var content = document.getElementById('detailsContent').innerHTML;
  var win = window.open('', '', 'height=800,width=1000');
  win.document.write('<html><head><title>Supplier Details</title>');
  win.document.write('<style>');
  win.document.write(`
  body {
    font-family: Arial, sans-serif;
    margin: 20px;
}
  .global-print .print-bg{
    height: auto !important;
  }
    table{width:100%;border-collapse:collapse;}
    th,td{border:1px solid #ddd;padding:8px;}
    th{background:#f3f4f6;}
 
  `);
  win.document.write('</style></head><body class="global-print">');
  win.document.write(`
    <?php
    include("global/global-print-heading.php");
?>
<main class="print-body-content">
<h2 style="text-align: center; text-decoration: underline;">Supplier Ledger</h2>
  `);
  win.document.write(content);
  win.document.write(`
  </main>
    <?php
    include("global/global-print-footer.php");
?>
  `);
  win.document.write('</body></html>');
  win.document.close();
  win.focus();
  win.print();
}
</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>
