<?php

include dirname(__DIR__) . "/init.php";
$isCli = true;
if (php_sapi_name() !== 'cli') {
    $isCli = false;
    echo "<pre>";
}

// Start cron logging
$logId = CronLog::start('main');
$expiredUsersFound = 0;
$expiredUsersProcessed = 0;
$notificationsSent = 0;
$autoRenewalsAttempted = 0;
$autoRenewalsSuccessful = 0;

echo "PHP Time\t" . date('Y-m-d H:i:s') . "\n";
$res = ORM::raw_execute('SELECT NOW() AS WAKTU;');
$statement = ORM::get_last_statement();
$rows = array();
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
    echo "MYSQL Time\t" . $row['WAKTU'] . "\n";
}

$_c = $config;

$textExpired = Lang::getNotifText('expired');

// Retrieve routers that are online
$onlineRouters = ORM::for_table('tbl_routers')->where('status', 'online')->find_many();

// Convert the ORM result set to a regular array
$onlineRoutersArray = $onlineRouters->as_array();

// Extract router names using array_map
$onlineRouterNames = array_map(function($router) {
    return $router['name'];
}, $onlineRoutersArray);

// If no online routers are found, skip processing user recharges
if (empty($onlineRouterNames)) {
    echo "No online routers found. Skipping user recharge processing.\n";
    exit; // Skip further processing
}

echo "Found " . count($onlineRouters) . " online routers.\n";

// First, handle suspended users that have reached their suspension time
$suspendedUsers = ORM::for_table('tbl_user_recharges')->where('status', 'suspended')->where_lte('expiration', date("Y-m-d"))
    ->where_in('routers', $onlineRouterNames)
    ->find_many();

echo "Found " . count($suspendedUsers) . " suspended user(s) to process.\n";

foreach ($suspendedUsers as $susUser) {
    $date_now = strtotime(date("Y-m-d H:i:s"));
    $expiration = strtotime($susUser['expiration'] . ' ' . $susUser['time']);
    
    if ($date_now >= $expiration) {
        echo "Suspending user: " . (($isCli) ? $susUser['username'] : Lang::maskText($susUser['username'])) . "\n";
        
        $u = ORM::for_table('tbl_user_recharges')->where('id', $susUser['id'])->find_one();
        $c = ORM::for_table('tbl_customers')->where('id', $susUser['customer_id'])->find_one();
        $m = ORM::for_table('tbl_routers')->where('name', $susUser['routers'])->find_one();
        $p = ORM::for_table('tbl_plans')->where('id', $u['plan_id'])->find_one();
        
        if ($p['is_radius']) {
            if (empty($p['pool_expired'])) {
                print_r(Radius::customerDeactivate($c['username']));
            } else {
                Radius::upsertCustomerAttr($c['username'], 'Framed-Pool', $p['pool_expired'], ':=');
                print_r(Radius::disconnectCustomer($c['username']));
            }
        } else {
            $client = Mikrotik::getClient($m['ip_address'], $m['username'], $m['password']);
            if ($susUser['type'] == 'Hotspot') {
                if (!empty($p['pool_expired'])) {
                    Mikrotik::setHotspotUserPlan($client, $c['username'], 'EXPIRED NUXBILL ' . $p['pool_expired']);
                } else {
                    Mikrotik::removeHotspotUser($client, $c['username']);
                }
                Mikrotik::removeHotspotActiveUser($client, $c['username']);
            } else if ($susUser['type'] == 'PPPOE') {
                if (!empty($p['pool_expired'])) {
                    Mikrotik::setPpoeUserPlan($client, $c['username'], 'EXPIRED NUXBILL ' . $p['pool_expired']);
                } else {
                    Mikrotik::removePpoeUser($client, $c['username']);
                }
                Mikrotik::removePpoeActive($client, $c['username']);
            }
        }
        
        // Update status to 'off' (suspended)
        $u->status = 'off';
        $u->save();
        
        echo "User " . $susUser['username'] . " has been suspended.\n";
    }
}

// Retrieve user recharges with status 'on' and expiration less than or equal to today
$d = ORM::for_table('tbl_user_recharges')->where('status', 'on')->where_lte('expiration', date("Y-m-d"))
    ->where_in('routers', $onlineRouterNames)  // Filter by routers that are online
    ->find_many();

echo "Found " . count($d) . " user(s) on online routers.\n";

run_hook('cronjob'); #HOOK

foreach ($d as $ds) {
    if ($ds['type'] == 'Hotspot') { # HOTSPOT
        $date_now = strtotime(date("Y-m-d H:i:s"));
        $expiration = strtotime($ds['expiration'] . ' ' . $ds['time']);
        echo $ds['expiration'] . " : " . (($isCli) ? $ds['username'] : Lang::maskText($ds['username']));
        if ($date_now >= $expiration) {
            echo " : EXPIRED \r\n";
            $expiredUsersFound++;
            $u = ORM::for_table('tbl_user_recharges')->where('id', $ds['id'])->find_one();
            $c = ORM::for_table('tbl_customers')->where('id', $ds['customer_id'])->find_one();
            $m = Mikrotik::info($ds['routers']);
            
            // Now no need to check the router status again because the query already filters offline routers
            $p = ORM::for_table('tbl_plans')->where('id', $u['plan_id'])->find_one();
            if ($p['is_radius']) {
                if (empty($p['pool_expired'])) {
                    print_r(Radius::customerDeactivate($c['username']));
                } else {
                    Radius::upsertCustomerAttr($c['username'], 'Framed-Pool', $p['pool_expired'], ':=');
                    print_r(Radius::disconnectCustomer($c['username']));
                }
            } else {
                $client = Mikrotik::getClient($m['ip_address'], $m['username'], $m['password']);
                if (!empty($p['pool_expired'])) {
                    Mikrotik::setHotspotUserPackage($client, $c['username'], 'EXPIRED NUXBILL ' . $p['pool_expired']);
                } else {
                    Mikrotik::removeHotspotUser($client, $c['username']);
                }
                Mikrotik::removeHotspotActiveUser($client, $c['username']);
            }
            echo Message::sendPackageNotification($c, $u['namebp'], $p['price'], 'expired', $config['user_notification_expired'], $p['type']) . "\n";
            $notificationsSent++;
            
            // Update database user with status off
            $u->status = 'off';
            $u->save();
            $expiredUsersProcessed++;

            // Autoreneewal from deposit
            if ($config['enable_balance'] == 'yes' && $c['auto_renewal']) {
                $autoRenewalsAttempted++;
                list($bills, $add_cost) = User::getBills($ds['customer_id']);
                if ($add_cost > 0) {
                    if (!empty($add_cost)) {
                        $p['price'] += $add_cost;
                    }
                }
                if ($p && $p['enabled'] && $c['balance'] >= $p['price']) {
                    if (Package::rechargeUser($ds['customer_id'], $ds['routers'], $p['id'], 'Customer', 'Balance')) {
                        // if success, then get the balance
                        Balance::min($ds['customer_id'], $p['price']);
                        $autoRenewalsSuccessful++;
                        echo "plan enabled: $p[enabled] | User balance: $c[balance] | price $p[price]\n";
                        echo "auto renewall Success\n";
                    } else {
                        echo "plan enabled: $p[enabled] | User balance: $c[balance] | price $p[price]\n";
                        echo "auto renewall Failed\n";
                        Message::sendTelegram("FAILED RENEWAL #cron\n\n#u$c[username] #buy #Hotspot \n" . $p['name_plan'] .
                            "\nRouter: " . $p['routers'] .
                            "\nPrice: " . $p['price']);
                    }
                } else {
                    echo "no renewall | plan enabled: $p[enabled] | User balance: $c[balance] | price $p[price]\n";
                }
            } else {
                echo "no renewall | balance $config[enable_balance] auto_renewal $c[auto_renewal]\n";
            }
        } else
            echo " : ACTIVE \r\n";
    } else { # PPPOE
        $date_now = strtotime(date("Y-m-d H:i:s"));
        $expiration = strtotime($ds['expiration'] . ' ' . $ds['time']);
        echo $ds['expiration'] . " : " . (($isCli) ? $ds['username'] : Lang::maskText($ds['username']));
        if ($date_now >= $expiration) {
            echo " : EXPIRED \r\n";
            $expiredUsersFound++;
            $u = ORM::for_table('tbl_user_recharges')->where('id', $ds['id'])->find_one();
            $c = ORM::for_table('tbl_customers')->where('id', $ds['customer_id'])->find_one();
            $m = ORM::for_table('tbl_routers')->where('name', $ds['routers'])->find_one();
            
            // No need to check router status here, as we've already filtered offline routers
            $p = ORM::for_table('tbl_plans')->where('id', $u['plan_id'])->find_one();
            if ($p['is_radius']) {
                if (empty($p['pool_expired'])) {
                    print_r(Radius::customerDeactivate($c['username']));
                } else {
                    Radius::upsertCustomerAttr($c['username'], 'Framed-Pool', $p['pool_expired'], ':=');
                    print_r(Radius::disconnectCustomer($c['username']));
                }
            } else {
                $client = Mikrotik::getClient($m['ip_address'], $m['username'], $m['password']);
                if (!empty($p['pool_expired'])) {
                    Mikrotik::setPpoeUserPlan($client, $c['username'], 'EXPIRED NUXBILL ' . $p['pool_expired']);
                } else {
                    Mikrotik::removePpoeUser($client, $c['username']);
                }
                Mikrotik::removePpoeActive($client, $c['username']);
            }
            echo Message::sendPackageNotification($c, $u['namebp'], $p['price'], 'expired', $config['user_notification_expired'], $p['type']) . "\n";
            $notificationsSent++;

            // Update database user with status off
            $u->status = 'off';
            $u->save();
            $expiredUsersProcessed++;

            // Autoreneewal from deposit
            if ($config['enable_balance'] == 'yes' && $c['auto_renewal']) {
                $autoRenewalsAttempted++;
                list($bills, $add_cost) = User::getBills($ds['customer_id']);
                if ($add_cost > 0) {
                    if (!empty($add_cost)) {
                        $p['price'] += $add_cost;
                    }
                }
                if ($p && $p['enabled'] && $c['balance'] >= $p['price']) {
                    if (Package::rechargeUser($ds['customer_id'], $ds['routers'], $p['id'], 'Customer', 'Balance')) {
                        // if success, then get the balance
                        Balance::min($ds['customer_id'], $p['price']);
                        $autoRenewalsSuccessful++;
                        echo "plan enabled: $p[enabled] | User balance: $c[balance] | price $p[price]\n";
                        echo "auto renewall Success\n";
                    } else {
                        echo "plan enabled: $p[enabled] | User balance: $c[balance] | price $p[price]\n";
                        echo "auto renewall Failed\n";
                        Message::sendTelegram("FAILED RENEWAL #cron\n\n#u$c[username] #buy #PPPOE \n" . $p['name_plan'] .
                            "\nRouter: " . $p['routers'] .
                            "\nPrice: " . $p['price']);
                    }
                } else {
                    echo "no renewall | plan enabled: $p[enabled] | User balance: $c[balance] | price $p[price]\n";
                }
            } else {
                echo "no renewall | balance $config[enable_balance] auto_renewal $c[auto_renewal]\n";
            }
        } else
            echo " : ACTIVE \r\n";
    }
}

// Complete cron logging
echo "\n=== CRON JOB SUMMARY ===\n";
echo "Expired users found: $expiredUsersFound\n";
echo "Expired users processed: $expiredUsersProcessed\n";
echo "Notifications sent: $notificationsSent\n";
echo "Auto-renewals attempted: $autoRenewalsAttempted\n";
echo "Auto-renewals successful: $autoRenewalsSuccessful\n";

// Update final statistics and complete logging
CronLog::complete([
    'expired_users_found' => $expiredUsersFound,
    'expired_users_processed' => $expiredUsersProcessed,
    'notifications_sent' => $notificationsSent,
    'auto_renewals_attempted' => $autoRenewalsAttempted,
    'auto_renewals_successful' => $autoRenewalsSuccessful
]);

echo "Cron job completed successfully!\n";
