<?php
session_start();

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

$tables = 0;

// Check if editing existing user
$edit_mode = false;
$ar = new auto_refill();

if (isset($_GET['aid']) && $_GET['aid'] > 0) {
    $user_id = $_GET['aid'];

    // Check if auto_refill exists for this user
    $sql_check = "SELECT * FROM auto_refill WHERE user_id = $user_id AND is_active = 1";
    $res_check = getXbyY($sql_check);

    if (count($res_check) > 0) {
        $edit_mode = true;
        $ar->auto_refill_id = $res_check[0]['auto_refill_id'];
        $ar->user_id = $res_check[0]['user_id'];
        $ar->user_name = $res_check[0]['user_name'];
        $ar->is_enabled = $res_check[0]['is_enabled'];
        $ar->min_balance = $res_check[0]['min_balance'];
        $ar->refill_amount = $res_check[0]['refill_amount'];
        $ar->max_refill_per_day = $res_check[0]['max_refill_per_day'];
        $ar->source_user_id = $res_check[0]['source_user_id'];
    } else {
        // New entry for this user
        $ar->user_id = $user_id;
        $user_data = $factory->get_object($user_id, "users", "user_id");
        $ar->user_name = $user_data->user_name;
    }
}

// Get all users for dropdown (excluding Admin)
$sql_users = "SELECT user_id, user_name, name, mobile, user_type, amount_balance
              FROM users
              WHERE user_type != 'Admin' AND is_active = 1
              ORDER BY name";
$res_users = getXbyY($sql_users);

// Get Admin users as source (fund providers)
$sql_admins = "SELECT user_id, user_name, name, amount_balance
               FROM users
               WHERE user_type = 'Admin' AND is_active = 1";
$res_admins = getXbyY($sql_admins);

include "html/includes/header.php";
?>

<div class="container-fluid">
    <h1 class="h3 mb-2 text-gray-800">
        <i class="fas fa-sync-alt"></i> Auto Refill Settings
        <?= $edit_mode ? '- Edit' : '- Add New' ?>
    </h1>

    <div class="row">
        <div class="col-lg-8">
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <?= $edit_mode ? 'Edit Auto Refill Configuration' : 'Configure Auto Refill for User' ?>
                    </h6>
                </div>
                <div class="card-body">
                    <form id="autoRefillForm" method="POST">
                        <input type="hidden" name="auto_refill_id" value="<?= $ar->auto_refill_id ?? 0 ?>">
                        <input type="hidden" name="edit_mode" value="<?= $edit_mode ? 1 : 0 ?>">

                        <!-- Select User -->
                        <div class="form-group row">
                            <label class="col-sm-3 col-form-label">Select User <span class="text-danger">*</span></label>
                            <div class="col-sm-9">
                                <select name="user_id" id="user_id" class="form-control" <?= $edit_mode ? 'disabled' : 'required' ?>>
                                    <option value="">-- Select User --</option>
                                    <?php foreach($res_users as $user) { ?>
                                        <option value="<?= $user['user_id'] ?>"
                                                data-balance="<?= $user['amount_balance'] ?>"
                                                <?= ($ar->user_id == $user['user_id']) ? 'selected' : '' ?>>
                                            <?= $user['name'] ?> (<?= $user['user_name'] ?>) - <?= $user['user_type'] ?> - Balance: ₹<?= number_format($user['amount_balance'], 2) ?>
                                        </option>
                                    <?php } ?>
                                </select>
                                <?php if($edit_mode) { ?>
                                    <input type="hidden" name="user_id" value="<?= $ar->user_id ?>">
                                <?php } ?>
                            </div>
                        </div>

                        <!-- Current Balance Display -->
                        <div class="form-group row" id="balanceDisplay" style="display: <?= $ar->user_id ? 'flex' : 'none' ?>">
                            <label class="col-sm-3 col-form-label">Current Balance</label>
                            <div class="col-sm-9">
                                <div class="alert alert-info mb-0">
                                    <strong id="currentBalance">
                                        <?php
                                        if($ar->user_id) {
                                            $user_bal = $factory->get_object($ar->user_id, "users", "user_id");
                                            echo '₹ ' . number_format($user_bal->amount_balance, 2);
                                        }
                                        ?>
                                    </strong>
                                </div>
                            </div>
                        </div>

                        <!-- Enable/Disable -->
                        <div class="form-group row">
                            <label class="col-sm-3 col-form-label">Auto Refill Status</label>
                            <div class="col-sm-9">
                                <div class="custom-control custom-switch">
                                    <input type="checkbox" class="custom-control-input" id="is_enabled" name="is_enabled" value="1"
                                           <?= ($ar->is_enabled == 1) ? 'checked' : '' ?>>
                                    <label class="custom-control-label" for="is_enabled">
                                        <span id="statusText"><?= ($ar->is_enabled == 1) ? 'Enabled' : 'Disabled' ?></span>
                                    </label>
                                </div>
                            </div>
                        </div>

                        <!-- Minimum Balance Threshold -->
                        <div class="form-group row">
                            <label class="col-sm-3 col-form-label">Minimum Balance <span class="text-danger">*</span></label>
                            <div class="col-sm-9">
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">₹</span>
                                    </div>
                                    <input type="number" class="form-control" name="min_balance" id="min_balance"
                                           value="<?= $ar->min_balance ?? 500 ?>" min="0" step="100" required>
                                </div>
                                <small class="form-text text-muted">When user balance goes below this amount, auto refill will trigger</small>
                            </div>
                        </div>

                        <!-- Refill Amount -->
                        <div class="form-group row">
                            <label class="col-sm-3 col-form-label">Refill Amount <span class="text-danger">*</span></label>
                            <div class="col-sm-9">
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">₹</span>
                                    </div>
                                    <input type="number" class="form-control" name="refill_amount" id="refill_amount"
                                           value="<?= $ar->refill_amount ?? 1000 ?>" min="100" step="100" required>
                                </div>
                                <small class="form-text text-muted">Amount to add to user's wallet when triggered</small>
                            </div>
                        </div>

                        <!-- Max Refills Per Day -->
                        <div class="form-group row">
                            <label class="col-sm-3 col-form-label">Max Refills/Day <span class="text-danger">*</span></label>
                            <div class="col-sm-9">
                                <select name="max_refill_per_day" class="form-control" required>
                                    <?php for($i = 1; $i <= 10; $i++) { ?>
                                        <option value="<?= $i ?>" <?= ($ar->max_refill_per_day == $i) ? 'selected' : '' ?>>
                                            <?= $i ?> time<?= $i > 1 ? 's' : '' ?>
                                        </option>
                                    <?php } ?>
                                </select>
                                <small class="form-text text-muted">Maximum number of auto refills allowed per day</small>
                            </div>
                        </div>

                        <!-- Source User (Admin who will fund) -->
                        <div class="form-group row">
                            <label class="col-sm-3 col-form-label">Fund Source (Admin) <span class="text-danger">*</span></label>
                            <div class="col-sm-9">
                                <select name="source_user_id" class="form-control" required>
                                    <option value="<?= $o->user_id ?>" selected>
                                        <?= $o->name ?> (Current Admin) - Balance: ₹<?= number_format($o->amount_balance, 2) ?>
                                    </option>
                                    <?php foreach($res_admins as $admin) {
                                        if($admin['user_id'] != $o->user_id) { ?>
                                            <option value="<?= $admin['user_id'] ?>"
                                                    <?= ($ar->source_user_id == $admin['user_id']) ? 'selected' : '' ?>>
                                                <?= $admin['name'] ?> - Balance: ₹<?= number_format($admin['amount_balance'], 2) ?>
                                            </option>
                                    <?php }
                                    } ?>
                                </select>
                                <small class="form-text text-muted">Admin account from which refill amount will be deducted</small>
                            </div>
                        </div>

                        <hr>

                        <div class="form-group row">
                            <div class="col-sm-9 offset-sm-3">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i> <?= $edit_mode ? 'Update Settings' : 'Save Settings' ?>
                                </button>
                                <a href="auto_refill_list" class="btn btn-secondary">
                                    <i class="fas fa-arrow-left"></i> Back to List
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <!-- How it works -->
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-info">
                        <i class="fas fa-info-circle"></i> How Auto Refill Works
                    </h6>
                </div>
                <div class="card-body">
                    <ol class="mb-0">
                        <li class="mb-2">System checks user balance periodically (via cron job)</li>
                        <li class="mb-2">If balance falls below <strong>Minimum Balance</strong>, auto refill triggers</li>
                        <li class="mb-2"><strong>Refill Amount</strong> is added to user's wallet</li>
                        <li class="mb-2">Amount is deducted from <strong>Admin/Source</strong> account</li>
                        <li class="mb-2">Maximum <strong>Max Refills/Day</strong> times per day</li>
                        <li>Transaction is logged in wallet history</li>
                    </ol>
                </div>
            </div>

            <!-- Quick Settings -->
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-success">
                        <i class="fas fa-bolt"></i> Quick Presets
                    </h6>
                </div>
                <div class="card-body">
                    <button type="button" class="btn btn-outline-primary btn-block mb-2" onclick="applyPreset(500, 1000, 2)">
                        Standard: Min ₹500, Refill ₹1000, 2/day
                    </button>
                    <button type="button" class="btn btn-outline-success btn-block mb-2" onclick="applyPreset(1000, 2000, 3)">
                        Premium: Min ₹1000, Refill ₹2000, 3/day
                    </button>
                    <button type="button" class="btn btn-outline-warning btn-block" onclick="applyPreset(2000, 5000, 5)">
                        Heavy User: Min ₹2000, Refill ₹5000, 5/day
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Toggle status text
    $('#is_enabled').change(function() {
        $('#statusText').text(this.checked ? 'Enabled' : 'Disabled');
    });

    // Show balance when user selected
    $('#user_id').change(function() {
        var balance = $(this).find(':selected').data('balance');
        if(balance !== undefined) {
            $('#currentBalance').text('₹ ' + parseFloat(balance).toLocaleString('en-IN', {minimumFractionDigits: 2}));
            $('#balanceDisplay').show();
        } else {
            $('#balanceDisplay').hide();
        }
    });

    // Form submission
    $('#autoRefillForm').submit(function(e) {
        e.preventDefault();

        var formData = $(this).serialize();
        if(!$('#is_enabled').is(':checked')) {
            formData += '&is_enabled=0';
        }

        $.ajax({
            url: 'auto_refill_save.php',
            type: 'POST',
            data: formData,
            success: function(response) {
                var result = JSON.parse(response);
                if(result.error == 0) {
                    swal("Success!", result.message, "success").then(() => {
                        window.location.href = 'auto_refill_list';
                    });
                } else {
                    swal("Error!", result.message, "error");
                }
            },
            error: function() {
                swal("Error!", "Something went wrong. Please try again.", "error");
            }
        });
    });
});

function applyPreset(minBalance, refillAmount, maxPerDay) {
    $('#min_balance').val(minBalance);
    $('#refill_amount').val(refillAmount);
    $('select[name="max_refill_per_day"]').val(maxPerDay);
    swal("Preset Applied!", "Settings have been filled. Click Save to apply.", "info");
}
</script>

<?php
include "html/includes/footer.php";
?>
