<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);


// Include necessary files
include "/www/wwwroot/bilspro/config/connect.php";
include "/www/wwwroot/bilspro/config/routeros_api.class.php";

// include "../config/connect.php";
// include "../config/routeros_api.class.php";

// Fetch data from the database
$query = "SELECT * FROM v_load_api_cek_voucher";
$set1 = $pdo->query($query);

if ($set1->rowCount() > 0) {
    $processes = [];

    while ($pset = $set1->fetch(PDO::FETCH_ASSOC)) {
        // Get connection details for the router
        $m_ip   = $pset['ip_address'];
        $m_user = $pset['username'];
        $m_pass = $pset['password'];
        $m_port = $pset['port_api'];
        $idsm   = $pset['id_setting_mikrotik'];

        // Prepare the command for each router
        $command = "php /www/wwwroot/bilspro/load/check_voucher.php {$m_ip} {$m_user} {$m_pass} {$m_port} {$idsm} > /dev/null 2>&1 &";

        // Execute the command in background
        exec($command, $output, $return_var);

        // Check if there was an issue with exec
        if ($return_var !== 0) {
            echo "Error executing command for IP: {$m_ip}\n";
        } else {
            echo "Successfully started background process for IP: {$m_ip}\n";
        }
    }

    echo "Started parallel processes for checking vouchers. => ". date('Y-m-d H:i:s');
} else {
    // Reset status_cek to NULL
    $updateQuery = "UPDATE ganerate_voucher SET status_cek = NULL WHERE status_cek = '1'";
    $stmt = $pdo->prepare($updateQuery);
    if ($stmt->execute()) {
        echo "Update ALL to NULL successful\n";
    } else {
        echo "Error updating status_cek to NULL\n";
    }
}
?>
