<?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) {

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'];

        $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>" . $pset['username'] . "</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 15");
            $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
                if (substr($durasi, -1) == 'H') {
                    $inter = "PT" . rtrim($durasi, 'H') . "H"; // For hours
                } elseif (substr($durasi, -1) == 'D') {
                    $inter = "P" . rtrim($durasi, 'D') . "D"; // For days
                } elseif (substr($durasi, -1) == 'M') {
                    $inter = "PT" . rtrim($durasi, 'M') . "M"; // For minutes
                } else {
                    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', array("?name" => $datav1));

                if ($cek) {
                    // If voucher exists, check the comment
                    if (isset($cek[0]['comment']) && $cek[0]['comment'] != '') {
                        $modifiedDateTime = substr($cek[0]['comment'], 6);
                        if (substr($modifiedDateTime, 0, 4) == date('Y')) {
                            $activetime = $modifiedDateTime;
                        } else {
                            $date = date_create_from_format("M/d/Y H:i:s", $modifiedDateTime);
                            if ($date !== false) {
                                $activetime = date_format($date, "Y-m-d H:i:s");
                            } else {
                                echo "Format tanggal tidak valid: $modifiedDateTime\n";
                                continue; // Skip iteration if the format is invalid
                            }
                        }
                        $Tgl = new DateTime($activetime);
                        $interval = new DateInterval($inter); // Add the duration (in the correct format)
                        $Tgl->add($interval);
                        $exp = $Tgl->format('Y-m-d H:i:s');

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

                        // Update the database using prepared statement
                        $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
                        ]);
                    } else {
                        // Mark the voucher as checked in the database
                        $updateQuery = "UPDATE ganerate_voucher SET status_cek = '1' WHERE id = :id";
                        $stmt = $pdo->prepare($updateQuery);
                        $stmt->execute([':id' => $iddatav1]);
                    }
                } else {
                    // If voucher does not exist, calculate expiration time
                    $aktif = $cekv1['create_time'];
                    $date1 = date_create($aktif);

                    // Ensure that the duration is numeric and valid
                    if (!empty($durasi) && is_numeric(rtrim($durasi, 'HDM'))) {
                        // Calculate expiration date using DateTime and DateInterval
                        try {
                            $Tgl = new DateTime($aktif);
                            $interval = new DateInterval($inter); // Add the duration (in the correct format)
                            $Tgl->add($interval);
                            $exp = $Tgl->format('Y-m-d H:i:s');

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

                            // Update the database using prepared statement
                            $updateQuery = "UPDATE ganerate_voucher SET active_time = :aktif, expaired_time = :exp WHERE id = :id";
                            $stmt = $pdo->prepare($updateQuery);
                            $stmt->execute([
                                ':aktif' => $aktif,
                                ':exp' => $exp,
                                ':id' => $iddatav1
                            ]);
                        } catch (Exception $e) {
                            echo "Error processing duration for voucher $datav1: " . $e->getMessage() . "\n";
                        }
                    } else {
                        // Handle case if 'durasi' is not valid or not numeric
                        echo "Invalid or missing 'durasi' value for voucher $datav1.\n";
                    }
                }

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

        // Disconnect the API session
        $API->disconnect();
    }
} 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";
    }
}
?>