  <?php
  session_start();
  include("header.php");
  include("footer.php");
  include("nav.php");
  include("connect.php");

  // Check if the user is logged in
  if (!isset($_SESSION['emailadd'])) {
    header("Location: index.php");
    exit;
  }
  ?>


<main>

<head>
  <meta charset="UTF-8">
  <title>Invoice List</title>
  <link rel="stylesheet" href="style.css">
</head>

  <div class="container">
    <h2>Senarai Invois</h2>
    <form method="post" action="">
      <div class="form-group">
        <div>
          <label for="supregno">No Pendaftaran Pembekal / Kontraktor:</label>
          <select id="supregno" name="supregno">
            <?php
        // Retrieve list of available account numbers
            $query = "SELECT supregno, supname FROM supplier";
            $result = mysqli_query($conn, $query);
            while ($row = mysqli_fetch_assoc($result)) {
              echo "<option value='" . $row['supregno'] . "'>" . $row['supname'] . "</option>";
            }
            ?>
          </select>
        </div>
      </div>
       <div>
        <input type="submit" name="submit" value="Senaraikan">
      </div>
    </form>
  </div>







<body>

<?php
  // Query the database for the list of supregno
  $query = "SELECT DISTINCT supregno FROM sup_invhead ORDER BY supregno ASC";
  $result = mysqli_query($conn, $query);

  // Check if the form has been submitted
  if (isset($_POST['submit'])) {
    $supregno = $_POST['supregno'];


    // Query the database for the list of invoices
   $query = "SELECT pono, poduedate, totamt, totpay FROM sup_invhead WHERE supregno = '$supregno' ORDER BY podate ASC";
    $result = mysqli_query($conn, $query);

    // Check if any invoices are found
    if (mysqli_num_rows($result) > 0) {
      // Display the invoices in a table
      echo "<h2>Invoice List for supregno: $supregno</h2>";
      echo "<table>";
      echo "<tr><th>No PO.</th><th>Tarikh Matang</th><th>Jumlah Belian</th><th>Jumlah BAyaran</th><th>Status</th></tr>";
      $owing = 0;
      while ($row = mysqli_fetch_assoc($result)) {
        echo "<tr>";
        echo "<td>" . $row['pono'] . "</td>";
        echo "<td>" . $row['poduedate'] . "</td>";
        echo "<td>" . number_format($row['totamt'], 2, '.', ',') . "</td>";
        echo "<td>" . $row['totpay'] . "</td>";
        if ($row['totamt'] - $row['totpay'] == 0) {
          echo "<td>Closed</td>";
        } else {
          echo "<td>Open</td>";
          $owing += $row['totamt'] - $row['totpay'];
        }
        echo "</tr>";
      }
      echo "</table>";
echo "<p>Amount owing to $supregno: " . number_format($owing, 2, '.', ',') . "</p>";
    } else {
      // If no invoices are found, display a message
      echo "<p>No invoices found for Pelanggan: $supregno</p>";
    }
  }
?>

</body>

</main>
