<?php

ini_set('display_errors', 1);
error_reporting(E_ERROR);
ob_start();
require ("includes/check_auth_user.php");
require ("includes/dbconnect.php");
include ('includes/function.php');
$zdb = $_SESSION["zdbyear_" . $dbname];
mysqli_select_db($conn, $zdb);

//include("includes/menu_rights.php");
$admin = $_SESSION["admin_" . $dbname];
$usertype = $_SESSION["usertype_" . $dbname];

$zroot = $_SESSION["zdir"];
//browse($zdb);

if ($_REQUEST["compcode"]) {
    $vouchno = $_REQUEST["compcode"];

    $sql = "SHOW TABLES FROM `$zdb`";
    $result = mysqli_query($conn, $sql);

    if (!empty($zdb)) {
        $safeCompcode = escapeshellarg($zdb); // Prevent command injection
        $scriptPath = 'sisbar_db.sh';

        if (file_exists($scriptPath)) {
            $output = shell_exec("bash $scriptPath $safeCompcode 2>&1");
//            echo "<pre>$output</pre>";
            $tableNames = [];
            while ($row = mysqli_fetch_row($result)) {
                if (strpos($row[0], '_de') !== false) {
                    $tableNames[] = $row[0];
                    $table = $row[0];
//            print  "truncate table $table";
                    mysqli_query($conn, "Delete from `$table`") or die(mysqli_error($conn));
                }
            }
            echo "1";
        } else {
            echo "Shell script not found.";
        }
    } else {
        echo "No compcode provided.";
    }
} else {
    echo "0";
}
?>    