<?php
session_start();

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

$tables = 1;

// Get all auto refill settings with user details
$sql = "SELECT ar.*, u.name, u.mobile, u.email, u.amount_balance, u.user_type
        FROM auto_refill ar
        LEFT JOIN users u ON ar.user_id = u.user_id
        WHERE ar.is_active = 1
        ORDER BY ar.is_enabled DESC, ar.updated_at DESC";
$res = getXbyY($sql);
$rows = count($res);

// Get statistics
$sql_stats = "SELECT
    COUNT(*) as total_users,
    SUM(CASE WHEN is_enabled = 1 THEN 1 ELSE 0 END) as enabled_users,
    SUM(total_refilled) as total_refilled_amount
    FROM auto_refill WHERE is_active = 1";
$res_stats = getXbyY($sql_stats);

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 - All Users
    </h1>

    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Total Configured Users</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?= $res_stats[0]['total_users'] ?? 0 ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-users fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Auto Refill Enabled</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?= $res_stats[0]['enabled_users'] ?? 0 ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-check-circle fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card border-left-info shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Total Amount Refilled</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">₹ <?= number_format($res_stats[0]['total_refilled_amount'] ?? 0, 2) ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-rupee-sign fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="card shadow mb-4">
        <div class="card-header py-3 d-flex justify-content-between align-items-center">
            <h6 class="m-0 font-weight-bold text-primary">Auto Refill Configured Users</h6>
            <a href="auto_refill_settings" class="btn btn-primary btn-sm">
                <i class="fas fa-plus"></i> Add New User
            </a>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                    <thead style="color:#fff;background-color:#034ea1">
                        <tr>
                            <th>S.No</th>
                            <th>User Details</th>
                            <th>Current Balance</th>
                            <th>Min Balance</th>
                            <th>Refill Amount</th>
                            <th>Max/Day</th>
                            <th>Today Count</th>
                            <th>Total Refilled</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php for ($i = 0; $i < $rows; $i++) { ?>
                            <tr>
                                <td><?= $i + 1 ?></td>
                                <td>
                                    <strong><?= $res[$i]['name'] ?></strong><br>
                                    <small><?= $res[$i]['user_name'] ?></small><br>
                                    <small class="text-muted"><?= $res[$i]['mobile'] ?></small><br>
                                    <span class="badge badge-info"><?= $res[$i]['user_type'] ?></span>
                                </td>
                                <td>
                                    <strong class="<?= ($res[$i]['amount_balance'] < $res[$i]['min_balance']) ? 'text-danger' : 'text-success' ?>">
                                        ₹ <?= number_format($res[$i]['amount_balance'], 2) ?>
                                    </strong>
                                    <?php if($res[$i]['amount_balance'] < $res[$i]['min_balance']) { ?>
                                        <br><small class="text-danger">Below threshold!</small>
                                    <?php } ?>
                                </td>
                                <td>₹ <?= number_format($res[$i]['min_balance'], 2) ?></td>
                                <td>₹ <?= number_format($res[$i]['refill_amount'], 2) ?></td>
                                <td><?= $res[$i]['max_refill_per_day'] ?></td>
                                <td>
                                    <span class="badge badge-<?= ($res[$i]['refill_count_today'] >= $res[$i]['max_refill_per_day']) ? 'danger' : 'success' ?>">
                                        <?= $res[$i]['refill_count_today'] ?>
                                    </span>
                                </td>
                                <td>₹ <?= number_format($res[$i]['total_refilled'], 2) ?></td>
                                <td>
                                    <?php if($res[$i]['is_enabled'] == 1) { ?>
                                        <span class="badge badge-success">ON</span>
                                    <?php } else { ?>
                                        <span class="badge badge-danger">OFF</span>
                                    <?php } ?>
                                </td>
                                <td>
                                    <a href="auto_refill_settings?aid=<?= $res[$i]['user_id'] ?>" class="btn btn-primary btn-sm" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <button class="btn btn-<?= ($res[$i]['is_enabled'] == 1) ? 'warning' : 'success' ?> btn-sm"
                                            onclick="toggleAutoRefill(<?= $res[$i]['auto_refill_id'] ?>, <?= $res[$i]['is_enabled'] ?>)"
                                            title="<?= ($res[$i]['is_enabled'] == 1) ? 'Disable' : 'Enable' ?>">
                                        <i class="fas fa-<?= ($res[$i]['is_enabled'] == 1) ? 'pause' : 'play' ?>"></i>
                                    </button>
                                    <button class="btn btn-info btn-sm"
                                            onclick="manualRefill(<?= $res[$i]['user_id'] ?>, '<?= $res[$i]['name'] ?>')"
                                            title="Manual Refill Now">
                                        <i class="fas fa-sync"></i>
                                    </button>
                                    <button class="btn btn-danger btn-sm"
                                            onclick="deleteAutoRefill(<?= $res[$i]['auto_refill_id'] ?>, '<?= $res[$i]['name'] ?>')"
                                            title="Delete">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
function toggleAutoRefill(id, currentStatus) {
    var newStatus = currentStatus == 1 ? 0 : 1;
    var action = newStatus == 1 ? 'enable' : 'disable';

    swal({
        title: "Are you sure?",
        text: "Do you want to " + action + " auto refill for this user?",
        icon: "warning",
        buttons: true,
        dangerMode: true,
    }).then((willChange) => {
        if (willChange) {
            $.ajax({
                url: "auto_refill_action.php",
                type: "POST",
                data: {
                    action: 'toggle',
                    auto_refill_id: id,
                    status: newStatus
                },
                success: function(response) {
                    var result = JSON.parse(response);
                    if(result.error == 0) {
                        swal("Success!", result.message, "success").then(() => {
                            location.reload();
                        });
                    } else {
                        swal("Error!", result.message, "error");
                    }
                }
            });
        }
    });
}

function manualRefill(userId, userName) {
    swal({
        title: "Manual Refill",
        text: "Do you want to manually trigger auto refill for " + userName + "?",
        icon: "info",
        buttons: true,
    }).then((willRefill) => {
        if (willRefill) {
            $.ajax({
                url: "auto_refill_action.php",
                type: "POST",
                data: {
                    action: 'manual_refill',
                    user_id: userId
                },
                success: function(response) {
                    var result = JSON.parse(response);
                    if(result.error == 0) {
                        swal("Success!", result.message, "success").then(() => {
                            location.reload();
                        });
                    } else {
                        swal("Error!", result.message, "error");
                    }
                }
            });
        }
    });
}

function deleteAutoRefill(id, userName) {
    swal({
        title: "Delete Auto Refill",
        text: "Are you sure you want to delete auto refill settings for " + userName + "?",
        icon: "warning",
        buttons: true,
        dangerMode: true,
    }).then((willDelete) => {
        if (willDelete) {
            $.ajax({
                url: "auto_refill_action.php",
                type: "POST",
                data: {
                    action: 'delete',
                    auto_refill_id: id
                },
                success: function(response) {
                    var result = JSON.parse(response);
                    if(result.error == 0) {
                        swal("Deleted!", result.message, "success").then(() => {
                            location.reload();
                        });
                    } else {
                        swal("Error!", result.message, "error");
                    }
                }
            });
        }
    });
}
</script>

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