<?php
session_start();
include("header.php");
include("footer.php");
include("nav.php");
include 'connect.php';
include ("function.php");

// Check if the user is logged in
if (!isset($_SESSION['emailadd'])) {
  header("Location: index.php");
  exit;
}

// Get the invoice number from the URL parameter
if (isset($_GET['invno'])) {
  $invno = $_GET['invno'];
} else {
  header("Location: main.php");
  exit;
}

// Retrieve the sales invoice header data
$query = "SELECT invhead.*, customer.custname FROM invhead INNER JOIN customer ON invhead.clientregno = customer.clientregno WHERE invno='$invno'";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) == 0) {
  // Invoice number does not exist, redirect to sales_view.php
  header("Location: sales_view.php");
  exit;
}
$invhead = mysqli_fetch_assoc($result);

// Retrieve the sales invoice details data
$query = "SELECT invdet.*, inccode.detail FROM invdet INNER JOIN inccode ON invdet.inccode = inccode.inccode WHERE invno='$invno'";
$result = mysqli_query($conn, $query);
$invdetails = array();
while ($row = mysqli_fetch_assoc($result)) {
  $invdetails[] = $row;
}

// Display the sales invoice data
?>
<main>
  <h2>Sales Invoice <?php echo $invno; ?></h2>
  <div>
    <div>Customer: <?php echo $invhead['custname']; ?></div>
    <div>Invoice Date: <?php echo $invhead['invdate']; ?></div>
    <div>Payment Term: <?php echo $invhead['payterm']; ?></div>
    <div>Invoice Due Date: <?php echo $invhead['invduedate']; ?></div>
    <div>Total Tax Amount: <?php echo number_format($invhead['taxamt'], 2); ?></div>
    <div>Total Invoice Amount: <?php echo number_format($invhead['totamt'], 2); ?></div>
  </div>
  <table>
    <thead>
      <tr>
        <th>Item Code</th>
        <th>Description</th>
        <th>Amount</th>
        <th>Taxable</th>
        <th>Tax Amount</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($invdetails as $invdetail): ?>
        <tr>
          <td><?php echo $invdetail['inccode']; ?></td>
          <td><?php echo $invdetail['detail']; ?></td>
          <td><?php echo number_format($invdetail['amount'], 2); ?></td>
          <td><?php echo $invdetail['tax'] == 1 ? 'Yes' : 'No'; ?></td>
          <td><?php echo number_format($invdetail['taxamt'], 2); ?></td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</main>
