<?php
session_start();

include "include.php";
include "session.php";

$result = array();
$result['error'] = 1;
$result['message'] = "Something went wrong. Please try again.";

$action = $_POST['action'] ?? '';

switch ($action) {

    case 'toggle':
        // Toggle enable/disable
        $auto_refill_id = intval($_POST['auto_refill_id']);
        $status = intval($_POST['status']);

        if ($auto_refill_id > 0) {
            $sql = "UPDATE auto_refill SET is_enabled = $status, updated_at = '" . todaysDate() . "' WHERE auto_refill_id = $auto_refill_id";
            setXbyY($sql);

            $result['error'] = 0;
            $result['message'] = "Auto refill " . ($status == 1 ? "enabled" : "disabled") . " successfully!";
        }
        break;

    case 'delete':
        // Soft delete
        $auto_refill_id = intval($_POST['auto_refill_id']);

        if ($auto_refill_id > 0) {
            $sql = "UPDATE auto_refill SET is_active = 0, updated_at = '" . todaysDate() . "' WHERE auto_refill_id = $auto_refill_id";
            setXbyY($sql);

            $result['error'] = 0;
            $result['message'] = "Auto refill configuration deleted successfully!";
        }
        break;

    case 'manual_refill':
        // Manual trigger for a specific user
        $user_id = intval($_POST['user_id']);

        if ($user_id > 0) {
            // Get auto refill settings
            $sql = "SELECT * FROM auto_refill WHERE user_id = $user_id AND is_active = 1";
            $res = getXbyY($sql);

            if (count($res) == 0) {
                $result['message'] = "Auto refill is not configured for this user.";
                break;
            }

            $ar = $res[0];

            // Get user current balance
            $user = $factory->get_object($user_id, "users", "user_id");

            // Get source admin
            $source_user = $factory->get_object($ar['source_user_id'], "users", "user_id");

            // Check if source has enough balance
            if ($source_user->amount_balance < $ar['refill_amount']) {
                $result['message'] = "Source admin does not have enough balance. Available: ₹" . number_format($source_user->amount_balance, 2);
                break;
            }

            // Process the refill
            $refill_result = process_auto_refill($user, $source_user, $ar, $factory, $insertor, $updater);

            if ($refill_result['success']) {
                $result['error'] = 0;
                $result['message'] = "Manual refill successful! ₹" . number_format($ar['refill_amount'], 2) . " added to " . $user->name . "'s wallet.";
            } else {
                $result['message'] = $refill_result['message'];
            }
        }
        break;

    default:
        $result['message'] = "Invalid action.";
}

echo json_encode($result);

// Function to process auto refill
function process_auto_refill($user, $source_user, $ar, $factory, $insertor, $updater) {
    global $res_site;

    $result = array('success' => false, 'message' => 'Unknown error');

    try {
        $refill_amount = floatval($ar['refill_amount']);

        // 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 ₹" . number_format($ar['min_balance'], 2);
        $o_wallet->transaction_date = todaysDate();
        $o_wallet->month_year = date("Y-m");
        $o_wallet->status = "Success";
        $o_wallet->recharge_path = "Auto";
        $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 = "Auto";
        $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 refill
        $log = new auto_refill_logs();
        $log->auto_refill_id = $ar['auto_refill_id'];
        $log->user_id = $user->user_id;
        $log->user_name = $user->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 = $ar['min_balance'];
        $log->source_user_id = $source_user->user_id;
        $log->source_user_name = $source_user->user_name . " - " . $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 triggered. 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
        $today = date("Y-m-d");
        $last_refill_date = $ar['last_refill_date'];

        // Reset counter if new day
        if ($last_refill_date != $today) {
            $new_count = 1;
        } else {
            $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);

        $result['success'] = true;
        $result['message'] = "Refill successful";

    } catch (Exception $e) {
        $result['message'] = "Error: " . $e->getMessage();
    }

    return $result;
}
?>
