<?php
/**
 * Auto Refill Cron Job
 *
 * This script should be run via cron job every 5-10 minutes
 * Cron Example: */5 * * * * php /path/to/cron_auto_refill.php
 *
 * What it does:
 * 1. Checks all users with auto refill enabled
 * 2. If user balance < min_balance threshold
 * 3. And daily refill count < max allowed
 * 4. Then triggers auto refill
 */

// Prevent browser access
if (php_sapi_name() !== 'cli' && !isset($_GET['key'])) {
    // Allow access with secret key for testing
    die("Access denied. This script should be run via cron.");
}

// Secret key for testing via browser (change this!)
$secret_key = "auto_refill_2024_secret";
if (isset($_GET['key']) && $_GET['key'] !== $secret_key) {
    die("Invalid key.");
}

include "core/dbInfo.php";
include_once "core/dbFunctions.php";
include_once "core/core_classes.php";
include_once "core/get_classes.php";
include_once "core/insert_classes.php";
include_once "core/update_classes.php";

// Initialize
$factory = new TypeFactory($dbName);
$insertor = new TypeInsertor($dbName);
$updater = new TypeUpdater($dbName);

$today = date("Y-m-d");
$log_file = "auto_refill_cron_" . date("Y-m-d") . ".log";

// Log function
function cron_log($message) {
    global $log_file;
    $timestamp = date("Y-m-d H:i:s");
    $log_message = "[$timestamp] $message\n";
    // Uncomment below line to enable file logging
    // file_put_contents($log_file, $log_message, FILE_APPEND);
    echo $log_message;
}

cron_log("=== Auto Refill Cron Started ===");

// Reset daily counters if new day
$sql_reset = "UPDATE auto_refill
              SET refill_count_today = 0
              WHERE last_refill_date < '$today' OR last_refill_date IS NULL";
setXbyY($sql_reset);
cron_log("Daily counters reset check completed.");

// Get all enabled auto refill users
$sql = "SELECT ar.*, u.amount_balance, u.name as user_full_name
        FROM auto_refill ar
        LEFT JOIN users u ON ar.user_id = u.user_id
        WHERE ar.is_active = 1
        AND ar.is_enabled = 1
        AND ar.refill_count_today < ar.max_refill_per_day
        AND u.is_active = 1";

$res = getXbyY($sql);
$count = count($res);

cron_log("Found $count users with auto refill enabled and eligible for refill.");

$refills_done = 0;
$refills_skipped = 0;
$refills_failed = 0;

foreach ($res as $ar) {
    $user_id = $ar['user_id'];
    $user_name = $ar['user_name'];
    $current_balance = floatval($ar['amount_balance']);
    $min_balance = floatval($ar['min_balance']);
    $refill_amount = floatval($ar['refill_amount']);
    $source_user_id = $ar['source_user_id'];

    cron_log("Checking user: $user_name (ID: $user_id) - Balance: $current_balance, Threshold: $min_balance");

    // Check if balance is below threshold
    if ($current_balance >= $min_balance) {
        cron_log("  -> Balance is above threshold. Skipping.");
        $refills_skipped++;
        continue;
    }

    cron_log("  -> Balance is BELOW threshold. Processing refill...");

    // Get user object
    $user = $factory->get_object($user_id, "users", "user_id");
    if ($user->user_id <= 0) {
        cron_log("  -> ERROR: User not found. Skipping.");
        $refills_failed++;
        continue;
    }

    // Get source admin
    $source_user = $factory->get_object($source_user_id, "users", "user_id");
    if ($source_user->user_id <= 0) {
        cron_log("  -> ERROR: Source admin not found. Skipping.");
        $refills_failed++;
        continue;
    }

    // Check source balance
    if ($source_user->amount_balance < $refill_amount) {
        cron_log("  -> ERROR: Source admin has insufficient balance. Available: " . $source_user->amount_balance . ", Required: $refill_amount");
        $refills_failed++;

        // Log the failure
        $log = new auto_refill_logs();
        $log->auto_refill_id = $ar['auto_refill_id'];
        $log->user_id = $user_id;
        $log->user_name = $user_name;
        $log->old_balance = $current_balance;
        $log->refill_amount = $refill_amount;
        $log->new_balance = $current_balance;
        $log->min_balance_threshold = $min_balance;
        $log->source_user_id = $source_user_id;
        $log->source_user_name = $ar['source_user_name'];
        $log->source_old_balance = $source_user->amount_balance;
        $log->source_new_balance = $source_user->amount_balance;
        $log->wallet_id = 0;
        $log->status = "Failed";
        $log->remarks = "Source admin insufficient balance. Required: $refill_amount, Available: " . $source_user->amount_balance;
        $log->refill_date = todaysDate();
        $log->is_active = 1;
        $insertor->insert_object($log, "auto_refill_logs");

        continue;
    }

    // Process the refill
    try {
        // Record old balances
        $user_old_balance = $user->amount_balance;
        $source_old_balance = $source_user->amount_balance;

        // Create wallet entry for user (credit)
        $o_wallet = new wallet();
        $o_wallet->user_id = $user->user_id;
        $o_wallet->user_name = $user->user_name;
        $o_wallet->user_1_id = $source_user->user_id;
        $o_wallet->user_1_name = $source_user->user_name . " - " . $source_user->name;
        $o_wallet->transaction_type = "Auto Refill";
        $o_wallet->wallet_type = "Wallet";
        $o_wallet->cash_credit = "Credit";
        $o_wallet->user_old_balance = $user_old_balance;
        $o_wallet->total_amount = $refill_amount;
        $o_wallet->amount = $refill_amount;
        $o_wallet->user_new_balance = $user_old_balance + $refill_amount;
        $o_wallet->transaction_details = "Auto Refill - Balance was below threshold (₹" . number_format($min_balance, 2) . ")";
        $o_wallet->transaction_date = todaysDate();
        $o_wallet->month_year = date("Y-m");
        $o_wallet->status = "Success";
        $o_wallet->recharge_path = "Cron";
        $o_wallet->send_type = "Auto Refill";
        $o_wallet->parent_user_id = $user->parent_id;
        $o_wallet->is_active = 1;
        $o_wallet->created_at = todaysDate();

        $o_wallet->wallet_id = $insertor->insert_object($o_wallet, "wallet");

        // Update user balance
        $user->amount_balance = $user_old_balance + $refill_amount;
        $updater->update_object($user, "users");

        // Deduct from source admin
        $source_user->amount_balance = $source_old_balance - $refill_amount;
        $updater->update_object($source_user, "users");

        // Create wallet entry for source (debit)
        $o_wallet_source = new wallet();
        $o_wallet_source->user_id = $source_user->user_id;
        $o_wallet_source->user_name = $source_user->user_name;
        $o_wallet_source->user_1_id = $user->user_id;
        $o_wallet_source->user_1_name = $user->user_name . " - " . $user->name;
        $o_wallet_source->transaction_type = "Auto Refill Transfer";
        $o_wallet_source->wallet_type = "Wallet";
        $o_wallet_source->cash_credit = "Debit";
        $o_wallet_source->user_old_balance = $source_old_balance;
        $o_wallet_source->total_amount = $refill_amount;
        $o_wallet_source->amount = $refill_amount;
        $o_wallet_source->user_new_balance = $source_old_balance - $refill_amount;
        $o_wallet_source->transaction_details = "Auto Refill sent to " . $user->name;
        $o_wallet_source->transaction_date = todaysDate();
        $o_wallet_source->month_year = date("Y-m");
        $o_wallet_source->status = "Success";
        $o_wallet_source->recharge_path = "Cron";
        $o_wallet_source->send_type = "Auto Refill";
        $o_wallet_source->is_active = 1;
        $o_wallet_source->created_at = todaysDate();

        $insertor->insert_object($o_wallet_source, "wallet");

        // Log the success
        $log = new auto_refill_logs();
        $log->auto_refill_id = $ar['auto_refill_id'];
        $log->user_id = $user->user_id;
        $log->user_name = $user_name;
        $log->old_balance = $user_old_balance;
        $log->refill_amount = $refill_amount;
        $log->new_balance = $user->amount_balance;
        $log->min_balance_threshold = $min_balance;
        $log->source_user_id = $source_user->user_id;
        $log->source_user_name = $ar['source_user_name'];
        $log->source_old_balance = $source_old_balance;
        $log->source_new_balance = $source_user->amount_balance;
        $log->wallet_id = $o_wallet->wallet_id;
        $log->status = "Success";
        $log->remarks = "Auto refill via cron. User balance was ₹" . number_format($user_old_balance, 2);
        $log->refill_date = todaysDate();
        $log->is_active = 1;

        $insertor->insert_object($log, "auto_refill_logs");

        // Update auto_refill counters
        $new_count = intval($ar['refill_count_today']) + 1;
        $new_total = floatval($ar['total_refilled']) + $refill_amount;

        $sql_update = "UPDATE auto_refill SET
                       refill_count_today = $new_count,
                       last_refill_date = '$today',
                       total_refilled = $new_total,
                       updated_at = '" . todaysDate() . "'
                       WHERE auto_refill_id = " . $ar['auto_refill_id'];
        setXbyY($sql_update);

        cron_log("  -> SUCCESS! Refilled ₹$refill_amount. New balance: ₹" . $user->amount_balance);
        $refills_done++;

    } catch (Exception $e) {
        cron_log("  -> ERROR: " . $e->getMessage());
        $refills_failed++;
    }
}

cron_log("=== Auto Refill Cron Completed ===");
cron_log("Summary: Done=$refills_done, Skipped=$refills_skipped, Failed=$refills_failed");
cron_log("=========================================\n");
?>
