<?php 
include "config.php";
session_start();
$user=$_SESSION['log'];
include "financial_year_calculation.php";
$accountyear    = $financialYearStart."-".$financialYearEnd;
$year_code_end = substr($financialYearEnd,2);
$year_code_start = substr($financialYearStart,2);

$ticket = $_GET['edi'];
$sql = "update  second_transaction set status='deleted' where ticket = '$ticket' and status='' and financialyear='$accountyear'";
//echo $sql;
 $go = mysqli_query($connect,$sql);
 
 // 1. Count records with einvoice_generated = 0
$count_sql = "SELECT COUNT(*) AS total FROM second_transaction WHERE einvoice_generated = 1 and financialyear='$accountyear' and status=''";
$count_result = mysqli_query($connect, $count_sql);
$count_row = mysqli_fetch_assoc($count_result);
$total = $count_row['total'];
//echo $count_sql;

//echo "Total Pending E-Invoices: $total <br>";

// 2. Fetch records to rearrange
$fetch_sql = "SELECT id FROM second_transaction 
              WHERE einvoice_generated = 0 and financialyear='$accountyear' and status=''
              ORDER BY id ASC";
			  echo $fetch_sql;

$fetch_result = mysqli_query($connect, $fetch_sql);

$running_no = $total+1; // starting series

while ($row = mysqli_fetch_assoc($fetch_result)) {
    $id = $row['id'];
	$yearcode='YSS'.$year_code_start.$year_code_end;

    // Invoice format: YSS2526/1
    $invoice_no = $yearcode . "/" . $running_no;

    // Update invoice number
    $update_sql = "UPDATE second_transaction 
                   SET salescode = '$invoice_no' 
                   WHERE id = $id and status=''";

    mysqli_query($connect, $update_sql);

    $running_no++;
}
 
  header('Location:secondtransaction.php');

?>