<?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;
}

// Check if the form has been submitted
if (isset($_POST['submit'])) {
  // Get the month and year from the form
  $month = mysqli_real_escape_string($conn, $_POST['month']);
  $year = mysqli_real_escape_string($conn, $_POST['year']);

  // Query the database for the invhead data for the selected month and year
  $query = "SELECT supregno, SUM(totamt) as total_amount, SUM(totpay) as total_pay FROM sup_invhead WHERE MONTH(podate) = '$month' AND YEAR(podate) = '$year' GROUP BY supregno";
  $result = mysqli_query($conn, $query);

  // Calculate the amount owing for each client
  $owing = array();
  while ($row = mysqli_fetch_assoc($result)) {
    $owing[$row['supregno']] = $row['total_amount'] - $row['total_pay'];
  }
} else {
  // If the form has not been submitted, set the default month and year to the current month and year
  $month = date('m');
  $year = date('Y');
}
?>

<main>

  
  <h2>Purchase Order Summary for <?php echo date('F Y', strtotime("$year-$month-01")); ?></h2>

  <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    <div class="form-group">
      <label for="month">Month:</label>
      <select name="month" id="month">
        <?php for ($i = 1; $i <= 12; $i++) { ?>
          <option value="<?php echo $i; ?>" <?php if ($i == $month) echo 'selected'; ?>><?php echo date('F', mktime(0, 0, 0, $i, 1)); ?></option>
        <?php } ?>
      </select>
    </div>
    <div class="form-group">
      <label for="year">Year:</label>
      <select name="year" id="year">
        <?php for ($i = date('Y') - 5; $i <= date('Y') + 5; $i++) { ?>
          <option value="<?php echo $i; ?>" <?php if ($i == $year) echo 'selected'; ?>><?php echo $i; ?></option>
        <?php } ?>
      </select>
    </div>
    <button type="submit" name="submit">Senarai</button>
  </form>

  <?php if (isset($_POST['submit'])) { ?>
    <table>
      <tr>
        <th>Client Reg. No.</th>
        <th>Total Amount</th>
        <th>Total Received</th>
        <th>Amount Owing</th>
      </tr>
      <?php foreach ($owing as $supregno => $amount) { ?>
        <tr>
          <td><?php echo $supregno; ?></td>
          <td><?php echo number_format($row['total_amount'], 2, '.', ','); ?></td>
          <td><?php echo number_format($row['total_pay'], 2, '.', ','); ?></td>
          <td><?php echo number_format($amount, 2, '.', ','); ?></td>
        </tr>
       <?php } ?>
</table>
<p>Amount owing for <?php echo date('F Y', strtotime("$year-$month-01")); ?>:</p>
<p><?php echo number_format(array_sum($owing), 2, '.', ','); ?></p>
  <?php } ?>
</main>