<?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';



// Retrieve the available invno values from the invhead table
$sql = "SELECT invno FROM invhead ORDER BY invno ASC";
$result = $conn->query($sql);

// Check if there are any invno values available
if ($result->num_rows > 0) {

  $query1 = "SELECT inccode, detail FROM inccode";
  $result1 = mysqli_query($conn, $query1);
  $sales_items = array();
  while ($row1 = mysqli_fetch_assoc($result1)) {
    $sales_items[] = $row1;
  }
  ?>
  <main>
    <form method="post">
      <label for="invno">Pilih No Sebutharga:</label>
      <select name="invno" id="invno" class="form-control" style="width: auto; display: inline-block;">
        <?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" class="btn">View Invoice</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 invhead and invdet tables
  $invno = $_POST['invno'];
  $sql = "SELECT invhead.invno, invhead.clientregno, invhead.cfno, invhead.invdate, invhead.invduedate, invhead.taxamt AS totaltax, invhead.totamt, invhead.totrec, invdet.inccode, invdet.detail, invdet.amount, invdet.ID, invdet.tax, invdet.taxamt 
  FROM invhead 
  LEFT JOIN invdet ON invhead.invno = invdet.invno 
  WHERE invhead.invno = '$invno'
  ORDER BY invhead.invno ASC";
  $result = $conn->query($sql);


  // Display the invhead 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']; ?>&nbsp;<input type="date" id="invdate" class="form-control" value="<?php echo $row['invdate'] ?>" style="display: none; width: auto;"></td></td>
        </tr>
        <tr>
          <td>Inv Due Date:</td>
          <td><?php echo $row['invduedate']; ?>&nbsp;<input type="date" id="invduedate" class="form-control" value="<?php echo $row['invduedate'] ?>" style="display: none; width: auto;"></td></td>
        </tr>
        <tr>
          <td>Tax Amt:</td>
          <td><?php echo number_format($row['totaltax'], 2, '.', ','); ?>&nbsp;<input type="text" id="totaltax" class="form-control" value="<?php echo $row['totaltax'] ?>" style="display: none; width: auto;"></td>

        </tr>
        <tr>
          <td>Tot Amt:</td>
          <td><?php echo number_format($row['totamt'], 2, '.', ','); ?>&nbsp;<input type="text" id="totamt" class="form-control" value="<?php echo $row['totamt'] ?>" style="display: none; width: auto;"></td>

        </tr>
        <tr>
          <td>Tot Rec:</td>
          <td><?php echo number_format($row['totrec'], 2, '.', ','); ?>&nbsp;<input type="text" id="totrec" class="form-control" value="<?php echo $row['totrec'] ?>" style="display: none; width: auto;"></td>
        </tr>
      </table>
      <button class="btn btn-secondary" id="edit" onclick="editInvhead()">EDIT</button>
      <button class="btn btn-danger" style="display: none" id="cancel" onclick="location.reload()">CANCEL</button>
      <button class="btn btn-success" id="save" style="display: none" onclick="Save()">SAVE</button>
      <script type="text/javascript">
        function editInvhead() {
          $('#totrec').css('display', 'inline-block');
          $('#totamt').css('display', 'inline-block');
          $('#totaltax').css('display', 'inline-block');
          $('#invduedate').css('display', 'inline-block');
          $('#invdate').css('display', 'inline-block');
          $('#edit').css('display', 'none');
          $('#cancel').css('display', 'inline-block');
          $('#save').css('display', 'inline-block');
        }

        function Save(){
          var invID = '<?php echo $row['invno'] ?>';
          var invdate = $('#invdate').val();
          var invduedate = $('#invduedate').val();
          var totaltax = $('#totaltax').val();
          var totamt = $('#totamt').val();
          var totrec = $('#totrec').val();
              $.ajax({
                type: 'POST',
                url: 'ajax/editInvoiceHead.php',
                data: { 
                  invID: invID,
                  invdate: invdate,
                  invduedate: invduedate,
                  totaltax: totaltax,
                  totamt: totamt,
                  totrec: totrec,
                },
                success: function(data){
                  alert(data);
                  location.reload();
                }
              });
        }
      </script>
      <h3>Invoice Details</h3>
      <table>
        <tr>
          <th>Code</th>
          <th>Detail</th>
          <th>Amount</th>
          <th>Tax</th>
          <th>Tax Amount</th>
          <th>EDIT</th>
        </tr>
        <?php
      // Display the invdet data for the selected invoice
        $result->data_seek(0);
        $i=0;
        while ($row = $result->fetch_assoc()) {
          $i++;
          ?>
          <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>
            <td><button type="button" class="btn btn-primary" id="myBtn<?php echo $i ?>">
              EDIT
            </button></td>
          </tr>
          <div id="myModal<?php echo $i ?>" class="modal">
            <div class="modal-content">
              <div class="modal-header">
                <span class="close">&times;</span>
                <h2>Modal Header</h2>
              </div>
              <div class="modal-body">
                <label>Code</label>
                <select class="form-control" id="inccode<?php echo $row['ID'] ?>"><option value="<?php echo $row['inccode'] ?>"><?php echo $row['inccode'] ?></option><?php foreach ($sales_items as $item): ?><option value="<?php echo $item['inccode']; ?>"><?php echo $item['detail']; ?></option><?php endforeach; ?></select>
                <label>Detail</label>
                <input class="form-control" type="text" id="detail<?php echo $row['ID'] ?>" value="<?php echo $row['detail']?>">
                <label>Amount</label>
                <input class="form-control" type="number" id="amount<?php echo $row['ID'] ?>" value="<?php echo $row['amount']?>">
                <label>Tax</label>
                <input class="form-control" type="number" id="taxamt<?php echo $row['ID'] ?>" value="<?php echo $row['taxamt']?>">
              </div>
              <div class="modal-footer">
                <button class="btn btn-success" onclick="edit<?php echo $i ?>()">EDIT</button>
              </div>
            </div>
          </div>

          <script type="text/javascript">
            document.addEventListener("DOMContentLoaded", function() {
              var buttons = document.querySelectorAll(".btn-primary");

              buttons.forEach((btn) => {
                btn.onclick = function() {
                  var modalId = btn.getAttribute("id").replace("myBtn", "myModal");
                  var modal = document.getElementById(modalId);
                  if (modal) {
                    modal.style.display = "block";
                  }
                };
              });

              document.querySelectorAll(".close").forEach((close) => {
                close.onclick = function() {
                  var modal = close.closest(".modal");
                  if (modal) {
                    modal.style.display = "none";
                  }
                };
              });

              window.onclick = function(event) {
                document.querySelectorAll(".modal").forEach((modal) => {
                  if (event.target === modal) {
                    modal.style.display = "none";
                  }
                });
              };
            });

            function edit<?php echo $i ?>() {
              var ID = <?php echo $row['ID'] ?>;
              var inccode = $('#inccode<?php echo $row['ID'] ?>').val();
              var detail = $('#detail<?php echo $row['ID'] ?>').val();
              var amount = $('#amount<?php echo $row['ID'] ?>').val();
              var taxamt = $('#taxamt<?php echo $row['ID'] ?>').val();
              $.ajax({
                type: 'POST',
                url: 'ajax/editInvoiceDetail.php',
                data: { 
                  ID: ID,
                  inccode: inccode,
                  detail: detail,
                  amount: amount,
                  taxamt: taxamt,
                },
                success: function(data){
                  alert(data);
                  location.reload();
                }
              });
            }
          </script>
          <?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 confirmDelete()">
          <input type="hidden" name="invno" value="<?php echo $invno; ?>">
          <button type="submit" name="delete">Delete This Invoice</button>
        </form>

        <button type="submit" name="print" onclick="confirmPrint()">Print</button>
      </div>
      <script>
        function confirmDelete() {
          return confirm("Are you sure you want to delete this invoice no <?php echo $invno; ?>?");
        }

        function confirmPrint() {
          if (confirm('Are you sure you want to print invoice <?php echo $invno; ?>?')) {
            window.open('/TCPDF/examples/invoice.php?invno=<?php echo $invno; ?>', '_blank');
          }
        }

      </script>
    </main>
    <?php
  } else {
    echo "No results found.";
  }
}
if (isset($_POST['delete'])) {
  // Get the selected invno
  $invno = $_POST['invno'];

  // DELETE data FROM invhead table
  $sql = "DELETE FROM invhead 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 invdet 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;
  }
}

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/invoice.php?invno='$invno'");
  exit;
}





// Include footer file
include 'footer.php';

?>