<?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";

// Get parameters from command line arguments
$m_ip = $argv[1];    // IP address
$m_user = $argv[2];  // Username
$m_pass = $argv[3];  // Password
$m_port = $argv[4];  // Port
$idsm = $argv[5];    // Mikrotik setting ID

// Create new RouterosAPI instance
$API = new RouterosAPI();
$API->debug = false;

// Connect to the router API
if ($API->connect2($m_ip, $m_user, $m_pass, $m_port)) {
    echo "\n<b>Connected to Router: {$m_ip}</b>\n";

    // Query vouchers that need to be checked
    $ambilv1 = $pdo->prepare("SELECT id, create_time, voucher, durasi FROM v_load_cek_voucher WHERE id_setting_mikrotik = :idsm AND status_cek IS NULL LIMIT 75");
    $ambilv1->execute([':idsm' => $idsm]);

    while ($cekv1 = $ambilv1->fetch(PDO::FETCH_ASSOC)) {
        $iddatav1 = $cekv1['id'];
        $datav1   = $cekv1['voucher'];
        $durasi   = $cekv1['durasi'];

        // Convert the 'durasi' to a valid DateInterval format
        $inter = convertDurationToInterval($durasi);
        if (!$inter) {
            echo "Invalid duration format: $durasi.\n";
            continue;  // Skip this voucher if the duration is invalid
        }

        // Check if the voucher exists in the hotspot users
        $cek = $API->comm('/ip/hotspot/user/print', ["?name" => $datav1]);

        if ($cek) {
            // If voucher exists, check the comment
            if (isset($cek[0]['comment']) && $cek[0]['comment'] != '') {
                $activetime = processCommentDate($cek[0]['comment']);
                $Tgl = new DateTime($activetime);
                $Tgl->add($inter);
                $exp = $Tgl->format('Y-m-d H:i:s');

                echo "{$datav1} comment->{$cek[0]['comment']} active->{$activetime} exp->{$exp} => Exists\n";

                // Update the database with active and expired time
                updateVoucher($pdo, $iddatav1, $activetime, $exp);
            } else {
                // Mark the voucher as checked
                markVoucherChecked($pdo, $iddatav1);
            }
        } else {
            // If voucher does not exist, calculate expiration time based on creation date
            $aktif = $cekv1['create_time'];
            $Tgl = new DateTime($aktif);
            $Tgl->add($inter);
            $exp = $Tgl->format('Y-m-d H:i:s');

            echo "{$datav1} active->{$aktif} exp->{$exp} => Does not exist\n"; 

            // Update the database with active and expired time
            updateVoucher($pdo, $iddatav1, $aktif, $exp);
        }

        echo "{$cekv1['voucher']}\n";
    }
} else {
    echo "Unable to connect to router: {$m_ip}\n";
}

// Disconnect the API session
$API->disconnect();

// Function to convert duration string to DateInterval
function convertDurationToInterval($durasi) {
    if (substr($durasi, -1) == 'H') {
        return new DateInterval("PT" . rtrim($durasi, 'H') . "H"); // For hours
    } elseif (substr($durasi, -1) == 'D') {
        return new DateInterval("P" . rtrim($durasi, 'D') . "D"); // For days
    } elseif (substr($durasi, -1) == 'M') {
        return new DateInterval("PT" . rtrim($durasi, 'M') . "M"); // For minutes
    } else {
        return false; // Invalid duration format
    }
}

// Function to process the comment and extract valid activation time
function processCommentDate($comment) {
    $modifiedDateTime = substr($comment, 6);
    if (substr($modifiedDateTime, 0, 4) == date('Y')) {
        return $modifiedDateTime;
    } else {
        $date = date_create_from_format("M/d/Y H:i:s", $modifiedDateTime);
        if ($date !== false) {
            return date_format($date, "Y-m-d H:i:s");
        } else {
            echo "Invalid date format: {$modifiedDateTime}\n";
            return null;
        }
    }
}

// Function to update the voucher in the database
function updateVoucher($pdo, $iddatav1, $activetime, $exp) {
    $updateQuery = "UPDATE ganerate_voucher SET active_time = :activetime, expaired_time = :exp WHERE id = :id";
    $stmt = $pdo->prepare($updateQuery);
    $stmt->execute([
        ':activetime' => $activetime,
        ':exp' => $exp,
        ':id' => $iddatav1
    ]);
}

// Function to mark voucher as checked in the database
function markVoucherChecked($pdo, $iddatav1) {
    $updateQuery = "UPDATE ganerate_voucher SET status_cek = '1' WHERE id = :id";
    $stmt = $pdo->prepare($updateQuery);
    $stmt->execute([':id' => $iddatav1]);
}
?>
