<?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;
}

  // Retrieve list of available customers
  $query = "SELECT clientregno, custname FROM customer";
  $result = mysqli_query($conn, $query);
  $customers = array();
  while ($row = mysqli_fetch_assoc($result)) {
    $customers[] = $row;
  }

    // Retrieve list of available bank account no
  $query04 = "SELECT accno, accholder FROM bankacc";
  $result04 = mysqli_query($conn, $query04);
  $bankaccs = array();
  while ($row = mysqli_fetch_assoc($result04)) {
    $bankaccs[] = $row;
  }

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $clientregno = $_POST["clientregno"];
  $recptno = get_next_docno();
  $recptdate = $_POST["recptdate"];
  $recamt = $_POST["recamt"];
  $balamt = $recamt;
  $remark = $_POST["remark"];
  $createby = $_SESSION['emailadd'];
  $accno = $_POST["accno"];
  $status = $_POST['status'];

  // Validate input
  if (empty($clientregno) || empty($recptdate) || empty($recamt) || empty($remark) || empty($createby) || empty($accno)) {
    echo '<script>alert("Invalid input.")</script>';
    exit;
  }

  // Sanitize input
  $clientregno = mysqli_real_escape_string($conn, $clientregno);
  $recptno = mysqli_real_escape_string($conn, $recptno);
  $recptdate = mysqli_real_escape_string($conn, $recptdate);
  $recamt = mysqli_real_escape_string($conn, $recamt);
  $balamt = mysqli_real_escape_string($conn, $balamt);
  $remark = mysqli_real_escape_string($conn, $remark);
  $createby = mysqli_real_escape_string($conn, $createby);
  $accno = mysqli_real_escape_string($conn, $accno);


// Insert payment header
$query = "INSERT INTO payhead (clientregno, recptno, recptdate, recamt, balamt, remark, createby) VALUES ('$clientregno','$recptno', '$recptdate', '$recamt', '$balamt', '$remark', '$createby')";
$result = mysqli_query($conn, $query);

  // Check for errors
  if (!$result) {
    echo '<script>alert("Error inserting payment header.")</script>';
    exit;
  }

// Insert into tbl_bankin
$query = "INSERT INTO bank_trn (accno, trndate, docno, amount, status, remark, recfrm) VALUES ('$accno', '$recptdate', '$recptno', '$recamt' , '$status', '$remark', '$clientregno')";
$result = mysqli_query($conn, $query);

 // Check for errors
  if (!$result) {
    echo '<script>alert("Error inserting bank transaction.")</script>';
    // Rollback the payment header
    $query = "DELETE FROM payhead WHERE recptno = '$recptno'";
    $result = mysqli_query($conn, $query);
    exit;
  }

// Insert into running receipt no
$query = "INSERT INTO rundocno (docno) VALUES ('$recptno')";
$result = mysqli_query($conn, $query);

  // Check for errors
  if (!$result) {
    echo '<script>alert("Error inserting running receipt number.")</script>';
    // Rollback the payment header and bank transaction
    $query = "DELETE FROM payhead WHERE recptno = '$recptno'";
    $result = mysqli_query($conn, $query);
    $query = "DELETE FROM bank_trn WHERE docno = '$recptno'";
    $result = mysqli_query($conn, $query);
    exit;
  }

// Get all open invoices for the client
  $query02 = "SELECT invno, totamt, totrec FROM invhead WHERE clientregno = '$clientregno' AND totamt > totrec";
  $result02 = mysqli_query($conn, $query02);

// Check for errors
if (!$result02) {
echo '<script>alert("Error retrieving invoices.")</script>';
// Rollback the payment header, bank transaction, and running receipt number
$query = "DELETE FROM payhead WHERE recptno = '$recptno'";
$result = mysqli_query($conn, $query);
$query = "DELETE FROM bank_trn WHERE docno = '$recptno'";
$result = mysqli_query($conn, $query);
$query = "DELETE FROM rundocno WHERE docno = '$recptno'";
$result = mysqli_query($conn, $query);
exit;
}


  $invoices = array();
  while ($row = mysqli_fetch_assoc($result02)) {
    $invoices[] = $row;
  }


// Process the payment and update the invoices
foreach ($invoices as $invoice) {
  $invno = $invoice['invno'];
  $totamt = $invoice['totamt'];
  $totrec = $invoice['totrec'];

  $payamt = min($recamt, $totamt - $totrec);

  // Insert payment details
  $query = "INSERT INTO paydet (recptno, invno, payamt) VALUES ('$recptno', '$invno', '$payamt')";
  $result = mysqli_query($conn, $query);

  // Check for errors
if (!$result) {
  echo '<script>alert("Error inserting payment details.")</script>';
  // Rollback the payment header, bank transaction, running receipt number, and previous payment details
  $query = "DELETE FROM payhead WHERE recptno = '$recptno'";
  $result = mysqli_query($conn, $query);
  $query = "DELETE FROM bank_trn WHERE docno = '$recptno'";
  $result = mysqli_query($conn, $query);
  $query = "DELETE FROM rundocno WHERE docno = '$recptno'";
  $result = mysqli_query($conn, $query);
  $query = "DELETE FROM paydet WHERE recptno = '$recptno'";
  $result = mysqli_query($conn, $query);
  exit;
  }

  // Update invoice header with total payment received
  $query = "UPDATE invhead SET totrec = totrec + '$payamt' WHERE invno = '$invno'";
  $result = mysqli_query($conn, $query);
// Check for errors
if (!$result) {
  echo '<script>alert("Error updating invoice header.")</script>';
  // Rollback the payment header, bank transaction, running receipt number, and previous payment details
  $query = "DELETE FROM payhead WHERE recptno = '$recptno'";
  $result = mysqli_query($conn, $query);
  $query = "DELETE FROM bank_trn WHERE docno = '$recptno'";
  $result = mysqli_query($conn, $query);
  $query = "DELETE FROM rundocno WHERE docno = '$recptno'";
  $result = mysqli_query($conn, $query);
  $query = "DELETE FROM paydet WHERE recptno = '$recptno'";
  $result = mysqli_query($conn, $query);
  exit;
}

  // Update payment header with balance amount
  $balamt = $recamt - $payamt;
  $query = "UPDATE payhead SET balamt = '$balamt' WHERE recptno = '$recptno'";
  $result = mysqli_query($conn, $query);

// Check for errors
if (!$result) {
  echo '<script>alert("Error updating payment header.")</script>';
  // Rollback the payment header, bank transaction, running receipt number, and previous payment details
  $query = "DELETE FROM payhead WHERE recptno = '$recptno'";
  $result = mysqli_query($conn, $query);
  $query = "DELETE FROM bank_trn WHERE docno = '$recptno'";
  $result = mysqli_query($conn, $query);
  $query = "DELETE FROM rundocno WHERE docno = '$recptno'";
  $result = mysqli_query($conn, $query);
  $query = "DELETE FROM paydet WHERE recptno = '$recptno'";
  $result = mysqli_query($conn, $query);
  $query = "UPDATE invhead SET totrec = totrec - '$payamt' WHERE invno = '$invno'";
  $result = mysqli_query($conn, $query);
  exit;
}

  $recamt -= $payamt;

  if ($recamt == 0) {
    break; // Payment fully processed
  }
}

// Check if payment was fully processed
if ($recamt > 0) {
echo '<script>alert("Payment was not fully processed.")</script>';
// Rollback the payment header, bank transaction, running receipt number, and previous payment details
$query = "DELETE FROM payhead WHERE recptno = '$recptno'";
$result = mysqli_query($conn, $query);
$query = "DELETE FROM bank_trn WHERE docno = '$recptno'";
$result = mysqli_query($conn, $query);
$query = "DELETE FROM rundocno WHERE docno = '$recptno'";
$result = mysqli_query($conn, $query);
$query = "DELETE FROM paydet WHERE recptno = '$recptno'";
$result = mysqli_query($conn, $query);
foreach ($invoices as $invoice) {
$invno = $invoice['invno'];
$query = "UPDATE invhead SET totrec = totrec - '$payamt' WHERE invno = '$invno'";
$result = mysqli_query($conn, $query);
}
exit;
}

echo '<script>alert("Payment processed successfully.")</script>';
}



?>

<main>
  <h2>Rekod Penerimaan Bayaran</h2>
  <form method="post" action="payrecpt.php">
    <div class="form-group">
      <div>
        <label for="accno">Select Bank Account:</label>
        <select id="accno" name="accno" required>
          <option value="">- Select Bank Account -</option>
          <?php foreach ($bankaccs as $bankacc): ?>
            <option value="<?php echo $bankacc['accno']; ?>"><?php echo $bankacc['accholder']; ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <div>
          <label for="clientregno">Customer:</label>
          <select id="clientregno" name="clientregno" required>
            <option value="">- Select Customer -</option>
            <?php foreach ($customers as $customer): ?>
              <option value="<?php echo $customer['clientregno']; ?>" data-balance="<?php echo getCustomerBalance($conn, $customer['clientregno']); ?>"><?php echo $customer['custname']; ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>
      <div>
        <div><label for="recptdate">Receipt Date:</label></div>
        <input type="date" id="recptdate" name="recptdate" value="<?php echo date("Y-m-d"); ?>" required>
        <div><label for="recamt">Received Amount:</label></div>
        <input type="number" id="recamt" name="recamt" step="0.01" required>
        <div><label for="status">Status:</label></div>
        <input type="text" id="status" name="status">
        <div><label for="remark">Remark:</label></div>
        <input type="text" id="remark" name="remark">
        <div><label for="balance">Customer Balance :</label></div>
        <input type="number" id="balance" name="balance" value="0.00" readonly>
      </div>
      <br>
      <button type="submit">Record Payment</button>
    </div>
  </form>

<script>
  // Update the balance when a supplier is selected
  document.getElementById("clientregno").addEventListener("change", function() {
    var balance = this.options[this.selectedIndex].getAttribute("data-balance");
    document.getElementById("balance").value = parseFloat(balance).toFixed(2);
  });
</script>

</main>
