<?php
include "config.php";
session_start();

if (!isset($_SESSION['log'])) {
    echo json_encode(["status" => "error", "msg" => "Unauthorized"]);
    exit;
}

include "financial_year_calculation.php";

$accountyear    = $financialYearStart . "-" . $financialYearEnd;
$year_code_end   = substr($financialYearEnd, 2);
$year_code_start = substr($financialYearStart, 2);

if (!isset($_POST['ids']) || !is_array($_POST['ids']) || count($_POST['ids']) === 0) {
    echo json_encode(["status" => "error", "msg" => "No records selected"]);
    exit;
}

$ids = $_POST['ids'];

/* ------------------------------
   SANITIZE IDS
--------------------------------*/
$cleanIds = [];
foreach ($ids as $id) {
    $cleanIds[] = "'" . mysqli_real_escape_string($connect, $id) . "'";
}

$idList = implode(",", $cleanIds);

/* ------------------------------
   SOFT DELETE (NO EINVOICE)
--------------------------------*/
$delete_sql = "
    UPDATE second_transaction
    SET status='deleted'
    WHERE ticket IN ($idList)
      AND status=''
      AND einvoice_generated = 0
      AND financialyear='$accountyear'
";

if (!mysqli_query($connect, $delete_sql)) {
    echo json_encode(["status" => "error", "msg" => "Delete failed"]);
    exit;
}

/* ------------------------------
   COUNT EXISTING EINVOICES
--------------------------------*/
$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);
$last_number  = (int)$count_row['total'];

/* ------------------------------
   FETCH REMAINING RECORDS
--------------------------------*/
$fetch_sql = "
    SELECT id
    FROM second_transaction
    WHERE einvoice_generated = 0
      AND financialyear='$accountyear'
      AND status=''
    ORDER BY id ASC
";

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

$running_no = $last_number + 1;
$yearcode   = "YSS" . $year_code_start . $year_code_end;

/* ------------------------------
   REASSIGN INVOICE NUMBERS
--------------------------------*/
while ($row = mysqli_fetch_assoc($fetch_result)) {
    $id = (int)$row['id'];
    $invoice_no = $yearcode . "/" . $running_no;

    mysqli_query(
        $connect,
        "UPDATE second_transaction
         SET salescode='$invoice_no'
         WHERE id=$id AND status=''"
    );

    $running_no++;
}

echo json_encode(["status" => "success", "msg" => "Selected records deleted successfully"]);
exit;
