<?php
session_start();
include("header.php");
include("nav.php");
include 'connect.php';

// Check if the user is logged in
if (!isset($_SESSION['emailadd'])) {
  header("Location: index.php");
  exit;
}
include 'function.php';

// Check if the user has permission to view this page
if (!user_has_permission('clerk')) {
  header("Location: main.php");
  exit;
}

// Retrieve the available invno values from the quothead table
$sql = "SELECT invno FROM quothead ORDER BY invno ASC";
$result = $conn->query($sql);

// Check if there are any invno values available
if ($result->num_rows > 0) {
  // Display the form to select an invno
  ?>
  <main>
    <form method="post">
      <label for="invno">Pilih No Sebutharga:</label>
      <select name="invno" id="invno">
        <?php
        // Display the available invno values as options in the dropdown menu
        while ($row = $result->fetch_assoc()) {
          echo '<option value="' . $row['invno'] . '">' . $row['invno'] . '</option>';
        }
        ?>
      </select>
      <button type="submit">Lihat Sebutharga</button>
    </form>
  </main>
  <?php
} else {
  echo "No results found.";
}

// Check if a specific invno has been selected
if (isset($_POST['invno'])) {
  // Retrieve the data for the selected invno from the quothead and quotdet tables
  $invno = $_POST['invno'];
  $sql = "SELECT quothead.invno, quothead.clientregno, quothead.cfno, quothead.invdate, quothead.invduedate, quothead.taxamt AS totaltax, quothead.totamt, quothead.totrec, quotdet.inccode, quotdet.detail, quotdet.amount, quotdet.tax, quotdet.taxamt 
  FROM quothead 
  LEFT JOIN quotdet ON quothead.invno = quotdet.invno 
  WHERE quothead.invno = '$invno'
  ORDER BY quothead.invno ASC";
  $result = $conn->query($sql);


  // Display the quothead data for the selected invoice
  if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    ?>
    <main>
      <h2>No Sebutharga: <?php echo $row['invno']; ?></h2>
      <table>
        <tr>
          <td>Client Reg No:</td>
          <td><?php echo $row['clientregno']; ?></td>
        </tr>
        <tr>
          <td>CF No:</td>
          <td><?php echo $row['cfno']; ?></td>
        </tr>
        <tr>
          <td>Inv Date:</td>
          <td><?php echo $row['invdate']; ?></td>
        </tr>
        <tr>
          <td>Inv Due Date:</td>
          <td><?php echo $row['invduedate']; ?></td>
        </tr>
        <tr>
          <td>Tax Amt:</td>
          <td><?php echo number_format($row['totaltax'], 2, '.', ','); ?></td>

        </tr>
        <tr>
          <td>Tot Amt:</td>
          <td><?php echo number_format($row['totamt'], 2, '.', ','); ?></td>

        </tr>
        <tr>
          <td>Tot Rec:</td>
          <td><?php echo number_format($row['totrec'], 2, '.', ','); ?></td>

        </tr>
      </table>
      <h3>Invoice Details</h3>
      <table>
      <tr>
        <th>Code</th>
        <th>Detail</th>
        <th>Amount</th>
        <th>Tax</th>
        <th>Tax Amount</th>
      </tr>
      <?php
      // Display the quotdet data for the selected invoice
      $result->data_seek(0);
      while ($row = $result->fetch_assoc()) {
        ?>
        <tr>
          <td><?php echo $row['inccode']; ?></td>
          <td><?php echo $row['detail']; ?></td>
          <td><?php echo number_format($row['amount'], 2, '.', ','); ?></td>
          <td><input type="checkbox" name="tax[]" value="<?php echo $row['tax']; ?>"<?php if ($row['tax'] == 1) echo "checked"; ?>></td>
          <td><?php echo number_format($row['taxamt'], 2, '.', ','); ?></td>

        </tr>
        <?php
      }
      ?>
    </table>
<style>
  .form-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }

  .form-container button {
    margin-left: 10px;
  }
</style>

<div class="form-container">
  <form method="post" onsubmit="return confirmChange()">
    <input type="hidden" name="invno" value="<?php echo $invno; ?>">
    <button type="submit" name="change">Change to Invoice</button>
  </form>

  <form method="post" onsubmit="return confirmDelete()">
    <input type="hidden" name="invno" value="<?php echo $invno; ?>">
    <button type="submit" name="delete">Delete This Quotation</button>
  </form>

  <button type="submit" name="print" onclick="confirmPrint()">Print</button>
</div>

<script>
function confirmChange() {
  return confirm("Are you sure you want to change it to invoice <?php echo $invno; ?>?");
}

function confirmDelete() {
  return confirm("Are you sure you want to delete this quotation no <?php echo $invno; ?>?");
}
function confirmPrint() {
  if (confirm('Are you sure you want to print invoice <?php echo $invno; ?>?')) {
    window.open('/TCPDF/examples/quote.php?invno=<?php echo $invno; ?>', '_blank');
  }
}

</script>
  </main>
  <?php
  } else {
    echo "No results found.";
  }
}
if (isset($_POST['change'])) {
  // Get the selected invno
  $invno = $_POST['invno'];
  $next_docno = get_next_docno();    

  // Insert data into invhead table
  $sql = "INSERT INTO invhead SELECT * FROM quothead WHERE invno = '$invno'";
  
  $result = $conn->query($sql);

    // Check for errors
  if (!$result) {
    echo '<script>alert("Error inserting payment header.")</script>';
    exit;
  }

  // Insert data into invdet table
  $sql = "INSERT INTO invdet SELECT * FROM quotdet WHERE invno = '$invno'";
  $result = $conn->query($sql);

  // Check if the data was successfully inserted into both tables
  if ($result) {

    $sql =" UPDATE invhead SET invno = '$next_docno' WHERE invno = '$invno'";
    $result = $conn->query($sql);
    $sql =" UPDATE invdet SET invno = '$next_docno' WHERE invno = '$invno'";
    $result = $conn->query($sql);
    echo '<script>alert("Data inserted successfully.")</script>';
    exit();

  } else {
    echo "Error: " . $sql . "<br>" . $conn->error;
  }
}

if (isset($_POST['print'])) {
  // Get the selected invno
  $invno = $_POST['invno'];

  // Redirect to the print.php file, passing the invno as a parameter in the URL
  header("Location: TCPDF/examples/quote.php?invno='$invno'");
  exit;
}

if (isset($_POST['delete'])) {
  // Get the selected invno
  $invno = $_POST['invno'];

  // DELETE data FROM invhead table
  $sql = "DELETE FROM quothead WHERE invno = '$invno'";
  
  $result = $conn->query($sql);

    // Check for errors
  if (!$result) {
    echo '<script>alert("Error deleting payment header.")</script>';
    exit;
  }

  // Insert data into invdet table
  $sql = "DELETE FROM quotdet WHERE invno = '$invno'";
  $result = $conn->query($sql);

  // Check if the data was successfully inserted into both tables
  if ($result) {
    
    echo '<script>alert("Data DELETED successfully.")</script>';
    exit();
  } else {
    echo "Error: " . $sql . "<br>" . $conn->error;
  }
}






// Include footer file
include 'footer.php';

?>