<?php
// ---------------- FETCH RESELLER LIST ----------------
$resellers = $obj->rawSql("SELECT UserId, UserName FROM _reseller_createuser ORDER BY UserName ASC");

// ---------------- AJAX HANDLE ----------------


// ---------------- FETCH TABLE DATA ----------------
$dataList = $obj->rawSql("
    SELECT 
        s.*,
        IFNULL(r.UserName, 'N/A') AS UserName
    FROM re_sms_setting s
    LEFT JOIN _reseller_createuser r 
        ON r.UserId = s.reseller_id
    ORDER BY s.re_se_id  DESC
");


?>


<div class="card">
    <div class="card-header d-flex justify-content-between">
        <h3 class="card-title">Reseller SMS Settings</h3>
        <button class="btn btn-success" onclick="openModal()">+ Add</button>
    </div>

    <div class="card-body">
        <table class="table table-bordered" id="datatable">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Username</th>
                    <th>Reseller</th>
                    <th>Sender Id</th>
                    <th>API key</th>
                    <th>Status</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php $i = 1;
                foreach ($dataList as $row) { ?>
                    <tr>
                        <td><?= $i++ ?></td>
                        <td><?= $row['username'] ?></td>
                        <td><?= $row['UserName'] ?></td>
                        <td><?= $row['sender_id'] ?></td>
                        <td><?= $row['api_key'] ?></td>
                        <td>
                            <?= $row['status'] == 1 ? '<span class="text text-success">Active</span>' : '<span class="text text-danger">Inactive</span>' ?>
                        </td>
                        <td>
                            <button class="btn btn-sm btn-primary" onclick="editData(<?= $row['re_se_id'] ?>)">Edit</button>
                            <button class="btn btn-sm btn-danger" onclick="deleteData(<?= $row['re_se_id'] ?>)">Delete</button>
                        </td>
                    </tr>
                <?php } ?>
            </tbody>
        </table>
    </div>
</div>

<!-- MODAL -->
<div class="modal fade" id="dataModal">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">SMS Setting</h5>
            </div>

            <div class="modal-body">
                <input type="hidden" id="id">

                <div class="row">
                    <div class="col-md-4">
                        <label>Username</label>
                        <input type="text" id="username" class="form-control">
                    </div>

                    <div class="col-md-4">
                        <label>API Key</label>
                        <input type="text" id="api_key" class="form-control">
                    </div>

                    <div class="col-md-4">
                        <label>Sender ID</label>
                        <input type="text" id="sender_id" class="form-control">
                    </div>
                </div>

                <div class="row mt-2">
                    <div class="col-md-4">
                        <label>Reseller</label>
                        <select id="reseller_id" class="form-control">
                            <?php foreach ($resellers as $r) { ?>
                                <option value="<?= $r['UserId'] ?>"><?= $r['UserName'] ?></option>
                            <?php } ?>
                        </select>
                    </div>

                    <div class="col-md-4">
                        <label>Status</label>
                        <select id="status" class="form-control">
                            <option value="1">Active</option>
                            <option value="0">Inactive</option>
                        </select>
                    </div>
                </div>

            </div>

            <div class="modal-footer">
                <button class="btn btn-primary" onclick="saveData()">Save</button>
            </div>

        </div>
    </div>
</div>



<?php $obj->start_script(); ?>
<script>
    $('#datatable').DataTable();

    function openModal() {
        $('#id').val('');
        $('#dataModal input, #dataModal select').val('');
        $('#dataModal').modal('show');
    }

    function saveData() {


        $.ajax({
            url: 'pages/admin_reseller/ajax_reseller_sms_settings.php',
            type: 'POST',
            dataType: 'json',
            data: {
                ajax: 'save',
                id: $('#id').val(),
                username: $('#username').val(),
                api_key: $('#api_key').val(),
                reseller_id: $('#reseller_id').val(),
                sender_id: $('#sender_id').val(),
                status: $('#status').val()
            },
            success: function(res) {
                Swal.fire('Success', res.msg, 'success').then(() => location.reload());
            },
            error: function(error) {
                console.log(error);
            }
        });


    }

    function editData(id) {

    if (!id) {
        Swal.fire('Error', 'Invalid ID', 'error');
        return;
    }

    $.ajax({
        url: 'pages/admin_reseller/ajax_reseller_sms_settings.php',
        type: 'POST',
        dataType: 'json',
        data: {
            ajax: 'get',
            id: id
        },
        success: function (d) {

            console.log(d);

            if (!d || typeof d !== 'object') {
                Swal.fire('Error', 'No data found', 'error');
                return;
            }

            if (typeof d.re_se_id === 'undefined') {
                Swal.fire('Error', 'Invalid response from server', 'error');
                return;
            }

            $('#id').val(d.re_se_id || '');
            $('#username').val(d.username || '');
            $('#api_key').val(d.api_key || '');
            $('#reseller_id').val(d.reseller_id || '');
            $('#sender_id').val(d.sender_id || '');
            $('#status').val(d.status ?? 1);

            $('#dataModal').modal('show');
        },

        error: function (xhr) {
            Swal.fire({
                icon: 'error',
                title: 'AJAX Error',
                text: xhr.responseText || 'Something went wrong'
            });
        }
    });
}


    function deleteData(id) {

        Swal.fire({
                title: 'Are you sure?',
                icon: 'warning',
                showCancelButton: true
            })

            .then((r) => {

                if (r.isConfirmed) {



                    // 5️⃣ Ajax request
                    $.ajax({
                        url: 'pages/admin_reseller/ajax_reseller_sms_settings.php',
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            ajax: 'delete',
                            id: id
                        },
                        success: function(res) {
                            Swal.fire('Deleted', '', 'success').then(() => location.reload());
                        },
                        error: function(error) {
                            Swal.fire('Error', error.responseText, 'error');
                        }
                    });
                }
            });
    }
</script>
<?php $obj->end_script(); ?>