<x-admin-layout>
@section('title', $page . ' | ' . get_setting('site_name'))
<div class="mt-4 grid grid-cols-12 gap-4 sm:mt-5 sm:gap-5 lg:mt-6 lg:gap-6">
    <div class="col-span-12">
        <div class="card px-4 pb-4 sm:px-5">
            <div class="space-y-4">
                <h2 class="text-2xl font-semibold text-slate-600 dark:text-navy-100 mt-4 mb-4">
                    {{ $page }}
                </h2>
                @if(session('success'))
                  <div class="alert flex items-center overflow-hidden rounded-lg border border-success text-success">
                    <div class="px-4 py-3 sm:px-5">
                        <strong>{{ session('success') }}</strong>
                    </div>
                  </div>
                @endif
                @if(session('error'))
                  <div class="alert flex items-center overflow-hidden rounded-lg border border-error text-error">
                    <div class="px-4 py-3 sm:px-5">
                        <strong>{{ session('error') }}</strong>
                    </div>
                  </div>
                @endif
            </div>
            <form action="/admin/settings/update?route=withdraw" method="POST" class="mt-4">
              @csrf
              <div class="space-y-4">
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 items-center">
                    <div> 
                      <label class="block text-sm font-medium py-3">Maximum Daily Withdraw ($):</label>
                      <input id="maximum_withdraw" name="maximum_withdraw" type="number" step="0.000001" value="{{ get_setting('maximum_withdraw') }}" class="form-input peer w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 pl-4 placeholder:text-slate-400/70 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent" />
                    </div>
                    <div> 
                      <label class="block text-sm font-medium py-3">Pending if a user's today withdrawals reaches/more than ($):</label>
                      <input id="withdraw_pending_if" name="withdraw_pending_if" type="number" step="0.000001" value="{{ get_setting('withdraw_pending_if') }}" class="form-input peer w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 pl-4 placeholder:text-slate-400/70 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent" />
                    </div>
                </div>
                <button type="submit" class="btn space-x-2 bg-primary font-medium text-white hover:bg-primary-focus focus:bg-primary-focus active:bg-primary-focus/90 dark:bg-accent dark:hover:bg-accent-focus dark:focus:bg-accent-focus dark:active:bg-accent/90">Save</button>
              </div>
            </form>

            <div>
                <h3 class="font-semibold text-slate-600 dark:text-navy-100 mt-4 mb-4">
                    Currency List
                </h3>
            </div>
            <div class="overflow-x-auto mt-5">
                <table class="is-hoverable w-full text-left">
                    <thead>
                        <tr>
                            <th class="bg-slate-200 px-4 py-3 text-slate-800 dark:bg-navy-800 dark:text-navy-100">#</th>
                            <th class="bg-slate-200 px-4 py-3 text-slate-800 dark:bg-navy-800 dark:text-navy-100">Currency Name</th>
                            <th class="bg-slate-200 px-4 py-3 text-slate-800 dark:bg-navy-800 dark:text-navy-100">Currency Code</th>
                            <th class="bg-slate-200 px-4 py-3 text-slate-800 dark:bg-navy-800 dark:text-navy-100">USD Price</th>
                            <th class="bg-slate-200 px-4 py-3 text-slate-800 dark:bg-navy-800 dark:text-navy-100">Action</th>
                        </tr>
                    </thead>
                    <tbody id="currency-list">
                        <tr>
                            <td colspan="6" class="text-center py-4">Loading...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <button onclick="addNewRow()" class="mt-5 btn min-w-[7rem] rounded-full bg-primary font-medium text-white hover:bg-primary-focus focus:bg-primary-focus active:bg-primary-focus/90 dark:bg-accent dark:hover:bg-accent-focus dark:focus:bg-accent-focus dark:active:bg-accent/90">+ Add New</button>

        </div>
        <div class="card px-4 pb-4 sm:px-5 mt-4">
            <div>
                <h3 class="font-semibold text-slate-600 dark:text-navy-100 mt-4 mb-4">
                    Withdraw Options
                </h3>
            </div>
            <div class="overflow-x-auto mt-5">
                <table class="is-hoverable w-full text-left">
                    <thead>
                        <tr>
                            <th class="bg-slate-200 px-4 py-3 text-slate-800 dark:bg-navy-800 dark:text-navy-100">#</th>
                            <th class="bg-slate-200 px-4 py-3 text-slate-800 dark:bg-navy-800 dark:text-navy-100">Method Name</th>
                            <th class="bg-slate-200 px-4 py-3 text-slate-800 dark:bg-navy-800 dark:text-navy-100">Wallet</th>
                            <th class="bg-slate-200 px-4 py-3 text-slate-800 dark:bg-navy-800 dark:text-navy-100">API Key</th>
                            <th class="bg-slate-200 px-4 py-3 text-slate-800 dark:bg-navy-800 dark:text-navy-100">Currency</th>
                            <th class="bg-slate-200 px-4 py-3 text-slate-800 dark:bg-navy-800 dark:text-navy-100">Instant</th>
                            <th class="bg-slate-200 px-4 py-3 text-slate-800 dark:bg-navy-800 dark:text-navy-100">Min Withdraw</th>
                            <th class="bg-slate-200 px-4 py-3 text-slate-800 dark:bg-navy-800 dark:text-navy-100">Fee Type</th>
                            <th class="bg-slate-200 px-4 py-3 text-slate-800 dark:bg-navy-800 dark:text-navy-100">Fee</th>
                            <th class="bg-slate-200 px-4 py-3 text-slate-800 dark:bg-navy-800 dark:text-navy-100">Action</th>
                        </tr>
                    </thead>
                    <tbody id="withdraw-list">
                        <tr>
                            <td colspan="10" class="text-center py-4">Loading...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <button onclick="addNewWithdrawRow()" class="mt-5 btn min-w-[7rem] rounded-full bg-primary font-medium text-white hover:bg-primary-focus focus:bg-primary-focus active:bg-primary-focus/90 dark:bg-accent dark:hover:bg-accent-focus dark:focus:bg-accent-focus dark:active:bg-accent/90">+ Add New</button>

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

@push('scripts')
<script>
    $(document).ready(function () {
        loadCurrencies();

        function loadCurrencies() {
            $.ajax({
                url: "/admin/currency/load",
                type: "GET",
                dataType: "json",
                success: function (data) {
                    let rows = "";
                    data.forEach((currency, index) => {
                        rows += `
                            <tr data-id="${currency.id}">
                                <td class="whitespace-nowrap px-4 py-3 sm:px-5">${index + 1}</td>
                                <td><input type="text" value="${currency.currency_name}" class="currency-name form-input mt-1.5 w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 placeholder:text-slate-400/70 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent" data-field="name" readonly></td>
                                <td><input type="text" value="${currency.currency_code}" class="currency-code form-input mt-1.5 w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 placeholder:text-slate-400/70 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent" data-field="code" readonly></td>
                                <td><input type="number" value="${parseFloat(currency.usd)}" step="0.000001" class="editable form-input mt-1.5 w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 placeholder:text-slate-400/70 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent" data-field="price" readonly></td>
                                <td class="flex items-center">
                                    <button onclick="deleteCurrency(${currency.id})" class="mt-1 btn min-w-[7rem] rounded-full border border-slate-300 font-medium text-slate-800 hover:bg-slate-150 focus:bg-slate-150 active:bg-slate-150/80 dark:border-navy-450 dark:text-navy-50 dark:hover:bg-navy-500 dark:focus:bg-navy-500 dark:active:bg-navy-500/90">Delete</button>
                                </td>
                            </tr>
                        `;
                    });
                    $("#currency-list").html(rows);
                    loadWithdrawOptions();
                },
                error: function (xhr) {
                    alert("Error fetching data!");
                }
            });
        }

        window.deleteCurrency = function (id) {
            if (confirm("Are you sure you want to delete this currency?")) {
                $.ajax({
                    url: "/admin/currency/delete/" + id,
                    type: "DELETE",
                    data: { _token: "{{ csrf_token() }}" },
                    success: function (response) {
                        loadCurrencies();
                    },
                    error: function (xhr) {
                        alert("Error deleting currency!");
                    }
                });
            }
        };

        window.addNewRow = function () {
            let newRow = `
                <tr data-id="new">
                    <td class="whitespace-nowrap px-4 py-3 sm:px-5">#</td>
                    <td>
                        <input type="text" placeholder="Name" class="new-input form-input mt-1.5 w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 placeholder:text-slate-400/70 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent" data-field="name">
                    </td>
                    <td><input type="text" placeholder="Code" class="new-input form-input mt-1.5 w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 placeholder:text-slate-400/70 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent" data-field="code"></td>
                    <td>
                        <button onclick="saveNewRow(this)" class="mt-1 btn min-w-[7rem] rounded-full bg-primary font-medium text-white hover:bg-primary-focus focus:bg-primary-focus active:bg-primary-focus/90 dark:bg-accent dark:hover:bg-accent-focus dark:focus:bg-accent-focus dark:active:bg-accent/90">Save</button>
                        <button onclick="cancelNewRow(this)" class="mt-1 btn min-w-[7rem] rounded-full border border-slate-300 font-medium text-slate-800 hover:bg-slate-150 focus:bg-slate-150 active:bg-slate-150/80 dark:border-navy-450 dark:text-navy-50 dark:hover:bg-navy-500 dark:focus:bg-navy-500 dark:active:bg-navy-500/90">Cancel</button>
                    </td>
                </tr>
            `;
            $("#currency-list").prepend(newRow);
        };
        
        window.cancelNewRow = function (button) {
            $(button).closest("tr").remove();
        };


        window.saveNewRow = function (button) {
            let row = $(button).closest("tr");
            let data = {
                _token: "{{ csrf_token() }}"
            };

            row.find(".new-input").each(function () {
                let field = $(this).data("field");
                let value = $(this).val();
                data[field] = value;
            });

            $.ajax({
                url: "/admin/currency/add",
                type: "POST",
                data: data,
                success: function () {
                    loadCurrencies();
                },
                error: function () {
                    alert("Error adding currency!");
                }
            });
        };
        

        function loadWithdrawOptions() {
            $.ajax({
                url: "/admin/withdraw/load",
                type: "GET",
                success: function (response) {
                    let rows = response.map(option => `
                        <tr data-id="${option.id}">
                            <td class="whitespace-nowrap px-4 py-3 sm:px-5">${option.id}</td>
                            <td><input type="text" value="${option.name}" class="editable form-input mt-1.5 w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 placeholder:text-slate-400/70 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent" data-field="method_name"></td>
                            <td>
                                <select class="editable form-select mt-1.5 w-full rounded-lg border border-slate-300 bg-white px-3 py-2 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:bg-navy-700 dark:hover:border-navy-400 dark:focus:border-accent" data-field="wallet">
                                    <option value="faucetpay" ${option.wallet === "faucetpay" ? "selected" : ""}>FaucetPay</option>
                                </select>
                            </td>
                            <td><input type="text" value="${option.api_key || ''}" class="editable form-input mt-1.5 w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 placeholder:text-slate-400/70 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent" data-field="api_key"></td>
                            <td>
                                <select class="editable form-select mt-1.5 w-full rounded-lg border border-slate-300 bg-white px-3 py-2 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:bg-navy-700 dark:hover:border-navy-400 dark:focus:border-accent" data-field="currency_id">
                                    ${generateCurrencyOptions(option.currency_id)}
                                </select>
                            </td>
                            <td>
                                <select class="editable form-select mt-1.5 w-full rounded-lg border border-slate-300 bg-white px-3 py-2 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:bg-navy-700 dark:hover:border-navy-400 dark:focus:border-accent" data-field="instant">
                                    <option value="yes" ${option.instant === "yes" ? "selected" : ""}>Yes</option>
                                    <option value="no" ${option.instant === "no" ? "selected" : ""}>No</option>
                                </select>
                            </td>
                            <td><input type="number" value="${option.minimum_withdraw}" class="editable form-input mt-1.5 w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 placeholder:text-slate-400/70 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent" data-field="minimum_withdraw" min="0"></td>
                            <td>
                                <select class="editable form-select mt-1.5 w-full rounded-lg border border-slate-300 bg-white px-3 py-2 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:bg-navy-700 dark:hover:border-navy-400 dark:focus:border-accent" data-field="fee_type">
                                    <option value="percentage" ${option.fee_type === "percentage" ? "selected" : ""}>Percentage</option>
                                    <option value="fixed" ${option.fee_type === "fixed" ? "selected" : ""}>Fixed</option>
                                </select>
                            </td>
                            <td><input type="number" value="${option.fee}" class="editable form-input mt-1.5 w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 placeholder:text-slate-400/70 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent" data-field="fee" min="0"></td>
                            <td class="flex items-center">
                                <button class="edit-btn mt-1 btn min-w-[7rem] rounded-full bg-primary font-medium text-white hover:bg-primary-focus focus:bg-primary-focus active:bg-primary-focus/90 dark:bg-accent dark:hover:bg-accent-focus dark:focus:bg-accent-focus dark:active:bg-accent/90">Update</button>
                                <button onclick="deleteWithdrawOption(${option.id})" class="mt-1 btn min-w-[7rem] rounded-full border border-slate-300 font-medium text-slate-800 hover:bg-slate-150 focus:bg-slate-150 active:bg-slate-150/80 dark:border-navy-450 dark:text-navy-50 dark:hover:bg-navy-500 dark:focus:bg-navy-500 dark:active:bg-navy-500/90">Delete</button>
                            </td>
                        </tr>
                    `).join("");
        
                    $("#withdraw-list").html(rows);
                },
                error: function () {
                    alert("Failed to load withdraw options!");
                }
            });
        };
        
        function generateCurrencyOptions(selectedId) {
            return $("#currency-list tr").map(function () {
                let currencyId = $(this).data("id");
                let currencyName = $(this).find(".currency-name").val();
                let currencyCode = $(this).find(".currency-code").val();
                let isSelected = currencyId == selectedId ? "selected" : "";
                return `<option value="${currencyId}" ${isSelected}>${currencyName} (${currencyCode})</option>`;
            }).get().join("");
        }
        
        window.deleteWithdrawOption = function (id) {
            if (confirm("Are you sure you want to delete this withdraw option?")) {
                $.ajax({
                    url: "/admin/withdraw/delete/" + id,
                    type: "DELETE",
                    data: { _token: "{{ csrf_token() }}" },
                    success: function () {
                        loadWithdrawOptions();
                    },
                    error: function () {
                        alert("Error deleting withdraw option!");
                    }
                });
            }
        };
        $(document).on("click", ".edit-btn", function () {
            let theme = localStorage.getItem("_x_darkMode_on") === "true" ? "dark" : "light";
            let row = $(this).closest("tr");
            let id = row.data("id");
            let data = { _token: "{{ csrf_token() }}" };
                
            row.find(".editable").each(function () {
                let field = $(this).data("field");
                let value = $(this).val();
                data[field] = value;
            });
                
            $.ajax({
                url: "/admin/withdraw/update/" + id,
                type: "PUT",
                data: data,
                success: function () {
                    loadWithdrawOptions();
                                let swalOptions = {
                                    icon: "success",
                                    title: "Success!",
                                    html: `<p>Updated!</p>`,
                                    toast: true,
                                    position: "bottom-end",
                                    showConfirmButton: false,
                                    customClass: {
                                        popup: "toast-popup",
                                        title: "toast-title",
                                        content: "toast-content"
                                    },
                                    showCloseButton: true,
                                    closeButtonHtml: "<i class='fas fa-times'></i>"
                                };
                                
                                if (theme === "dark") {
                                    swalOptions.background = "#1E293B";
                                    swalOptions.color = "#F8FAFC";
                                    swalOptions.confirmButtonColor = "#4F46E5";
                                }
        
                                Swal.fire(swalOptions);
                },
                error: function () {
                    alert("Error updating data");
                }
            });
        });
        window.addNewWithdrawRow = function () {
            let currencyOptions = $("#currency-list tr").map(function () {
                let currencyId = $(this).data("id");
                let currencyName = $(this).find(".currency-name").val();
                let currencyCode = $(this).find(".currency-code").val();
                return `<option value="${currencyId}">${currencyName} (${currencyCode})</option>`;
            }).get().join("");
        
            let newRow = `
                <tr data-id="new">
                    <td class="whitespace-nowrap px-4 py-3 sm:px-5">#</td>
                    <td><input type="text" placeholder="Method Name" class="new-input form-input mt-1.5 w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 placeholder:text-slate-400/70 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent" data-field="method_name"></td>
                    <td>
                        <select class="new-input form-select mt-1.5 w-full rounded-lg border border-slate-300 bg-white px-3 py-2 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:bg-navy-700 dark:hover:border-navy-400 dark:focus:border-accent" data-field="wallet">
                            <option value="faucetpay">FaucetPay</option>
                        </select>
                    </td>
                    <td><input type="text" placeholder="API Key (Optional)" class="new-input form-input mt-1.5 w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 placeholder:text-slate-400/70 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent" data-field="api_key"></td>
                    <td>
                        <select class="new-input form-select mt-1.5 w-full rounded-lg border border-slate-300 bg-white px-3 py-2 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:bg-navy-700 dark:hover:border-navy-400 dark:focus:border-accent" data-field="currency_id">
                            ${currencyOptions}
                        </select>
                    </td>
                    <td>
                        <select class="new-input form-select mt-1.5 w-full rounded-lg border border-slate-300 bg-white px-3 py-2 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:bg-navy-700 dark:hover:border-navy-400 dark:focus:border-accent" data-field="instant">
                            <option value="yes">Yes</option>
                            <option value="no">No</option>
                        </select>
                    </td>
                    <td><input type="number" placeholder="Min Withdraw" class="new-input form-input mt-1.5 w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 placeholder:text-slate-400/70 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent" data-field="minimum_withdraw" min="0"></td>
                    <td>
                        <select class="new-input form-select mt-1.5 w-full rounded-lg border border-slate-300 bg-white px-3 py-2 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:bg-navy-700 dark:hover:border-navy-400 dark:focus:border-accent" data-field="fee_type">
                            <option value="percentage">Percentage</option>
                            <option value="fixed">Fixed</option>
                        </select>
                    </td>
                    <td><input type="number" placeholder="Fee" class="new-input form-input mt-1.5 w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 placeholder:text-slate-400/70 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent" data-field="fee" min="0"></td>
                    <td class="flex items-center">
                        <button onclick="saveNewWithdrawRow(this)" class="mt-1 btn min-w-[7rem] rounded-full bg-primary font-medium text-white hover:bg-primary-focus focus:bg-primary-focus active:bg-primary-focus/90 dark:bg-accent dark:hover:bg-accent-focus dark:focus:bg-accent-focus dark:active:bg-accent/90">Save</button>
                        <button onclick="cancelNewWithdrawRow(this)" class="mt-1 btn min-w-[7rem] rounded-full border border-slate-300 font-medium text-slate-800 hover:bg-slate-150 focus:bg-slate-150 active:bg-slate-150/80 dark:border-navy-450 dark:text-navy-50 dark:hover:bg-navy-500 dark:focus:bg-navy-500 dark:active:bg-navy-500/90">Cancel</button>
                    </td>
                </tr>
            `;
            $("#withdraw-list").prepend(newRow);
        };
        
        window.saveNewWithdrawRow = function (button) {
            let row = $(button).closest("tr");
            let requestData = {
                name: row.find("[data-field='method_name']").val(),
                wallet: row.find("[data-field='wallet']").val(),
                api_key: row.find("[data-field='api_key']").val(),
                currency_id: row.find("[data-field='currency_id']").val(),
                instant: row.find("[data-field='instant']").val(),
                minimum_withdraw: row.find("[data-field='minimum_withdraw']").val(),
                fee_type: row.find("[data-field='fee_type']").val(),
                fee: row.find("[data-field='fee']").val(),
                _token: "{{ csrf_token() }}"
            };
        
            if (!requestData.name || !requestData.wallet || !requestData.currency_id || !requestData.instant || !requestData.minimum_withdraw || !requestData.fee_type || !requestData.fee) {
                alert("Please fill in all required fields!");
                return;
            }
        
            $.ajax({
                url: "/admin/withdraw/add",
                type: "POST",
                data: requestData,
                success: function () {
                    loadWithdrawOptions();
                },
                error: function () {
                    alert("Error saving withdraw option!");
                }
            });
        };
        
        window.cancelNewWithdrawRow = function (button) {
            $(button).closest("tr").remove();
        };
    });
</script>
@endpush
</x-admin-layout>
