<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=links" method="POST" class="mt-4">
              @csrf
              <div class="space-y-4">
                <div>
                  <label class="block text-sm font-medium py-3">Shortlink Status</label>
                  <div class="flex items-center space-x-3">
                    <span class="text-sm">Off</span>
                    <label class="inline-flex items-center space-x-2">
                      <input type="hidden" name="shortlink_status" value="off" />
                      <input
                        id="shortlink_status"
                        name="shortlink_status"
                        type="checkbox"
                        value="on"
                        @checked(get_setting('shortlink_status') == 'on')
                        class="form-switch h-5 w-10 rounded-full bg-slate-300 before:rounded-full before:bg-slate-50 checked:bg-primary checked:before:bg-white dark:bg-navy-900 dark:before:bg-navy-300 dark:checked:bg-accent dark:checked:before:bg-white"
                      />
                    </label>
                    <span class="text-sm">On</span>
                  </div>
                </div>
                <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 items-center">
                    <div> 
                      <label class="block text-sm font-medium py-3">Minimum Advertise Reward ({{ get_setting('currency_name') }}):</label>
                      <input id="link_min_reward" name="link_min_reward" type="number" step="0.000001" value="{{ get_setting('link_min_reward') }}" 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">Minimum Advertise Views:</label>
                      <input id="link_minimum_limit" name="link_minimum_limit" type="number" step="1" value="{{ get_setting('link_minimum_limit') }}" 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">Advertise Fee (%):</label>
                      <input id="link_fee" name="link_fee" type="number" step="1" value="{{ get_setting('link_fee') }}" 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 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">Name</th>
                            <th class="bg-slate-200 px-4 py-3 text-slate-800 dark:bg-navy-800 dark:text-navy-100">Reward</th>
                            <th class="bg-slate-200 px-4 py-3 text-slate-800 dark:bg-navy-800 dark:text-navy-100">Limit</th>
                            <th class="bg-slate-200 px-4 py-3 text-slate-800 dark:bg-navy-800 dark:text-navy-100">Api Url</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="link-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>
</div>

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

        function loadLinks() {
            $.ajax({
                url: "/admin/links/load",
                type: "GET",
                dataType: "json",
                success: function (data) {
                    let rows = "";
                    data.forEach((link, index) => {
                        rows += `
                            <tr data-id="${link.id}">
                                <td class="whitespace-nowrap px-4 py-3 sm:px-5">${index + 1}</td>
                                <td><input type="text" value="${link.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="name"></td>
                                <td><input type="number" value="${link.reward}" 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="reward"></td>
                                <td><input type="number" value="${link.limit}" 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="limit"></td>
                                <td><input type="text" value="${link.api_url}" 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_url"></td>
                                <td class="flex items-center">
                                    <button class="mt-1 edit-btn 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">Edit</button>
                                    <button onclick="deleteLink(${link.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>
                        `;
                    });
                    $("#link-list").html(rows);
                },
                error: function (xhr) {
                    alert("Error fetching data!");
                }
            });
        }

        $(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() }}" };
        
            // Ambil nilai input
            row.find(".editable").each(function () {
                let field = $(this).data("field");
                let value = $(this).val();
                data[field] = value;
            });
        
            $.ajax({
                url: "/admin/link/update/" + id,
                type: "PUT",
                data: data,
                success: function () {
                    loadLinks();
                        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.deleteLink = function (id) {
            if (confirm("Are you sure you want to delete this link?")) {
                $.ajax({
                    url: "/admin/link/delete/" + id,
                    type: "DELETE",
                    data: { _token: "{{ csrf_token() }}" },
                    success: function (response) {
                        loadLinks();
                    },
                    error: function (xhr) {
                        alert("Error deleting link!");
                    }
                });
            }
        };

        window.addNewRow = function () {
            let newRow = `
                <tr data-id="new">
                    <td class="whitespace-nowrap px-4 py-3 sm:px-5">#<input type="hidden" value="0" class="new-input" data-field="user_id"></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="number" placeholder="Reward" step="0.000001" 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="reward"></td>
                    <td><input type="number" placeholder="Limit" 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="limit"></td>
                    <td><input type="text" placeholder="Api URL" 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_url"></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>
            `;
            $("#link-list").prepend(newRow);
        };
        
        window.cancelNewRow = function (button) {
            $(button).closest("tr").remove();
        };
        
        window.saveNewRow = function (button) {
            let row = $(button).closest("tr");
            let data = {
                _token: $('meta[name="csrf-token"]').attr("content")
            };

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

            $.ajax({
                url: "/admin/link/add",
                type: "POST",
                data: data,
                success: function () {
                    loadLinks();
                },
                error: function () {
                    alert("Error adding link!");
                }
            });
        };
    });
</script>
@endpush
</x-admin-layout>
