<x-app-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 x-data="{activeTab:'ADVERTISE'}" class="tabs flex flex-col">
        <div
          class="is-scrollbar-hidden overflow-x-auto rounded-lg bg-slate-200 text-slate-600 dark:bg-navy-800 dark:text-navy-200"
        >
          <div class="tabs-list flex px-1.5 py-1">
            <button
              @click="activeTab = 'ADVERTISE'"
              :class="activeTab === 'ADVERTISE' ? 'bg-white shadow dark:bg-navy-500 dark:text-navy-100' : 'hover:text-slate-800 focus:text-slate-800 dark:hover:text-navy-100 dark:focus:text-navy-100'"
              class="btn shrink-0 space-x-2 px-3 py-1.5 font-medium"
            >
            <i class="fas fa-bullhorn"></i>
              <span>Advertise</span>
            </button>
              <div
                x-data="usePopper({placement:'bottom-start',offset:4})"
                @click.outside="isShowPopper && (isShowPopper = false)"
                class="inline-flex ml-4"
              >
                <button
                  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"
                  x-ref="popperRef"
                  @click="isShowPopper = !isShowPopper"
                ><i class="fas fa-link"></i>
                  <span>My Ads</span>
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    class="size-4 transition-transform duration-200"
                    :class="isShowPopper && 'rotate-180'"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    stroke-width="2"
                  >
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      d="M19 9l-7 7-7-7"
                    />
                  </svg>
                </button>
                <div x-ref="popperRoot" class="popper-root" :class="isShowPopper && 'show'">
                  <div
                    class="popper-box rounded-md border border-slate-150 bg-white py-1.5 font-inter dark:border-navy-500 dark:bg-navy-700"
                  >
                    <ul>
                      <li>
                        <a
                          @click="activeTab = 'MYAD'"
                          id="pending-ad"
                          href="javascript:void(0);"
                          class="flex h-8 items-center px-3 pr-8 font-medium tracking-wide outline-none transition-all hover:bg-primary hover:text-white focus:bg-primary focus:text-white dark:hover:bg-accent dark:focus:bg-accent"
                          >Pending</a
                        >
                      </li>
                      <li>
                        <a
                          @click="activeTab = 'MYAD'"
                          id="active-ad"
                          href="javascript:void(0);"
                          class="flex h-8 items-center px-3 pr-8 font-medium tracking-wide outline-none transition-all hover:bg-primary hover:text-white focus:bg-primary focus:text-white dark:hover:bg-accent dark:focus:bg-accent"
                          >Active</a
                        >
                      </li>
                      <li>
                        <a
                          @click="activeTab = 'MYAD'"
                          id="rejected-ad"
                          href="javascript:void(0);"
                          class="flex h-8 items-center px-3 pr-8 font-medium tracking-wide outline-none transition-all hover:bg-primary hover:text-white focus:bg-primary focus:text-white dark:hover:bg-accent dark:focus:bg-accent"
                          >Rejected</a
                        >
                      </li>
                      <li>
                        <a
                          @click="activeTab = 'MYAD'"
                          id="ended-ad"
                          href="javascript:void(0);"
                          class="flex h-8 items-center px-3 pr-8 font-medium tracking-wide outline-none transition-all hover:bg-primary hover:text-white focus:bg-primary focus:text-white dark:hover:bg-accent dark:focus:bg-accent"
                          >Ended</a
                        >
                      </li>
                    </ul>
                  </div>
                </div>
              </div>
          </div>
        </div>
        <div class="tab-content pt-4">
          <div
            x-show="activeTab === 'ADVERTISE'"
            x-transition:enter="transition-all duration-500 easy-in-out"
            x-transition:enter-start="opacity-0 [transform:translate3d(1rem,0,0)]"
            x-transition:enter-end="opacity-100 [transform:translate3d(0,0,0)]"
          >
              <div class="card px-4 pb-4 sm:px-5">
                  <div
                    x-data="usePopper({
                       offset: 12,
                       placement: 'right-start',
                       modifiers: [
                          {name: 'flip', options: {fallbackPlacements: ['bottom','top']}},
                          {name: 'preventOverflow', options: {padding: 10}}
                       ]
                    })"
                    @click.outside="isShowPopper && (isShowPopper = false)"
                    class="flex"
                  >
                    <button
                      class="mt-4 btn 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"
                      x-ref="popperRef"
                      @click="isShowPopper = !isShowPopper"
                    >
                      Advertising Rate Calculation
                    </button>
                    <div x-ref="popperRoot" class="popper-root" :class="isShowPopper && 'show'">
                      <div class="popper-box max-w-xs">
                        <div
                          class="rounded-md border border-slate-150 bg-white p-4 dark:border-navy-600 dark:bg-navy-700"
                        >
                          <h3
                            class="text-base font-medium tracking-wide text-slate-700 line-clamp-1 dark:text-navy-100"
                          >
                            Advertising Rate Calculation
                          </h3>
                            <div class="text-sm mt-3">
                                <p><b>The cost is based on the reward.</b></p>
                                <p><b>Minimum Reward:</b></p>
                                <p class="ml-4">{!! balanceAndSymbol(get_setting('link_min_reward')/get_setting('currency_rate')) !!}</p>
                                <p><b>Minimum Views:</b></p>
                                <p class="ml-4">{{ get_setting('link_minimum_limit') }}</p>
                                <p><b>Fee:</b></p>
                                <p class="ml-4">{{ get_setting('link_fee') }}%</p>
                            </div>
                        </div>
                        <div class="size-4" data-popper-arrow>
                          <svg
                            viewBox="0 0 16 9"
                            xmlns="http://www.w3.org/2000/svg"
                            class="absolute size-4"
                            fill="currentColor"
                          >
                            <path
                              class="text-slate-150 dark:text-navy-600"
                              d="M1.5 8.357s-.48.624 2.754-4.779C5.583 1.35 6.796.01 8 0c1.204-.009 2.417 1.33 3.76 3.578 3.253 5.43 2.74 4.78 2.74 4.78h-13z"
                            />
                            <path
                              class="text-white dark:text-navy-700"
                              d="M0 9s1.796-.017 4.67-4.648C5.853 2.442 6.93 1.293 8 1.286c1.07-.008 2.147 1.14 3.343 3.066C14.233 9.006 15.999 9 15.999 9H0z"
                            />
                          </svg>
                        </div>
                      </div>
                    </div>
                  </div>
                  
                <form action="/advertise/link/store" method="POST" class="mt-4">
                  @csrf
                  <div class="space-y-4">
                    <div> 
                      <label class="block text-sm font-medium py-3">Name:</label>
                      <input id="name" name="name" type="text" placeholder="Website Name" 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" required/>
                    </div>
                    <div> 
                      <label class="block text-sm font-medium py-3">URL:</label>
                      <input id="url" name="url" type="url" placeholder="https://example.com/api?api=abcd&url=" 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" required/>
                      <small><b>Example: https://example.com/api?api=abcd&url=</b></small>
                    </div>
                    <div>
                        <label class="block text-sm font-medium py-3">Select Countries:</label>
                          <div class="flex items-center space-x-3">
                            <label class="inline-flex items-center space-x-2">
                              <input type="hidden" name="select_all" value="0" />
                              <input
                                id="selectAllCountries"
                                name="select_all"
                                type="checkbox"
                                value="1"
                                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">Select All</span>
                          
                            <label class="block w-full" id="countrySelectContainer">
                                <select 
                                    id="countrySelect"
                                    x-init="$el._tom = new Tom($el)"
                                    class="mt-1.5 w-full"
                                    name="countries[]"
                                    multiple
                                    placeholder="Select a country..."
                                    autocomplete="off"
                                >
                                    @foreach(get_setting('countries') as $code => $country)
                                        <option value="{{ $code }}">{{ $country }}</option>
                                    @endforeach
                                </select>
                            </label>
                        </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">Reward ({{ get_setting('currency_name') }}):</label>
                          <input id="reward" name="reward" type="number" step="0.000001" placeholder="{{ get_setting('link_min_reward') }}" min="{{ 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" required/>
                        </div>
                        <div> 
                          <label class="block text-sm font-medium py-3">Views:</label>
                          <input id="views" name="views" type="views" placeholder="{{ get_setting('link_minimum_limit') }}" min="{{ 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" required/>
                        </div>
                        <div> 
                          <label class="block text-sm font-medium py-3">Daily Limit:</label>
                          <input id="limit_per_day" name="limit_per_day" type="number" placeholder="1" min="1" 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" required/>
                        </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">Submit</button>
                  </div>
                </form>
                <div class="mt-4">
                    <label class="block text-sm font-medium py-3">Estimated Price:</label>
                    <p class="text-lg font-semibold text-primary" id="estimatedPrice">$0.00</p>
                </div>
              </div>
          </div>
          <div
            x-show="activeTab === 'MYAD'"
            x-transition:enter="transition-all duration-500 easy-in-out"
            x-transition:enter-start="opacity-0 [transform:translate3d(1rem,0,0)]"
            x-transition:enter-end="opacity-100 [transform:translate3d(0,0,0)]"
          >
            <div class="overflow-x-auto">
              <table class="is-hoverable w-full text-left">
                <thead>
                  <tr>
                    <th class="whitespace-nowrap rounded-tl-lg bg-slate-200 px-4 py-3 font-semibold uppercase text-slate-800 dark:bg-navy-800 dark:text-navy-100 lg:px-5"> # </th>
                    <th class="whitespace-nowrap bg-slate-200 px-4 py-3 font-semibold uppercase text-slate-800 dark:bg-navy-800 dark:text-navy-100 lg:px-5"> Name </th>
                    <th class="whitespace-nowrap bg-slate-200 px-4 py-3 font-semibold uppercase text-slate-800 dark:bg-navy-800 dark:text-navy-100 lg:px-5"> Url </th>
                    <th class="whitespace-nowrap bg-slate-200 px-4 py-3 font-semibold uppercase text-slate-800 dark:bg-navy-800 dark:text-navy-100 lg:px-5"> Remaining Views </th>
                    <th class="whitespace-nowrap bg-slate-200 px-4 py-3 font-semibold uppercase text-slate-800 dark:bg-navy-800 dark:text-navy-100 lg:px-5"> Today Views </th>
                    <th class="whitespace-nowrap bg-slate-200 px-4 py-3 font-semibold uppercase text-slate-800 dark:bg-navy-800 dark:text-navy-100 lg:px-5"> Total Views </th>
                  </tr>
                </thead>
                <tbody id="ad-table">
                  <tr>
                    <td colspan="6" class="text-center py-4"><div class="w-full px-6 py-4"><div class="skeleton animate-wave h-3 w-full rounded bg-slate-150 dark:bg-navy-500"></div><div class="skeleton animate-wave mt-4 h-3 w-8/12 rounded bg-slate-150 dark:bg-navy-500"></div></div></td>
                  </tr>
                </tbody>
              </table>
            </div>
            
            <!-- Pagination -->
            <div id="pagination" class="mt-4 flex justify-center"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
@push('scripts')
<script>
var feePercentage = {{ get_setting('link_fee') }};
var currencyRate = {{ get_setting('currency_rate') }};

document.addEventListener("DOMContentLoaded", function () {
    const selectAllCheckbox = document.getElementById("selectAllCountries");
    const countrySelectContainer = document.getElementById("countrySelectContainer");

    selectAllCheckbox.addEventListener("change", function () {
        if (this.checked) {
            countrySelectContainer.style.display = "none";
        } else {
            countrySelectContainer.style.display = "block";
        }
    });
});

$(document).ready(function() {
    function calculatePrice() {
        var reward = parseFloat($("#reward").val()) || 0;
        var views = parseInt($("#views").val()) || 0;

        var basePrice = (reward / currencyRate) * views;
        var feeAmount = (basePrice * feePercentage) / 100;
        var totalPrice = (basePrice + feeAmount).toFixed(6);

        $("#estimatedPrice").text(`$${totalPrice}`);
    }

    $("#reward, #views").on("input", calculatePrice);

    calculatePrice();
    
    let curStatus = 0;
    function loadAd(page = 1, status = 0) {
      curStatus = status;
      $.ajax({
        url: "/advertise/link/load/"+status,
        type: "GET",
        data: { page: page },
        dataType: "json",
        beforeSend: function () {
            $("#ad-table").html('<tr><td colspan="6" class="text-center py-4"><div class="w-full px-6 py-4"><div class="skeleton animate-wave h-3 w-full rounded bg-slate-150 dark:bg-navy-500"></div><div class="skeleton animate-wave mt-4 h-3 w-8/12 rounded bg-slate-150 dark:bg-navy-500"></div></div></td></tr>');
        },
        success: function (data) {
            var html = "";
            if (data.records.length > 0) {
                data.records.forEach(function (item) {
                  html += `
                    <tr class="border-y border-transparent border-b-slate-200 dark:border-b-navy-500">
                      <td class="whitespace-nowrap px-4 py-3 sm:px-5">${item.id}</td>
                      <td class="whitespace-nowrap px-4 py-3 sm:px-5">${item.name}</td>
                      <td class="whitespace-nowrap px-4 py-3 sm:px-5">${item.url}</td>
                      <td class="whitespace-nowrap px-4 py-3 sm:px-5">${item.remaining_views}</td>
                      <td class="whitespace-nowrap px-4 py-3 sm:px-5">${item.today_views}</td>
                      <td class="whitespace-nowrap px-4 py-3 sm:px-5">${item.views}</td>
                    </tr>`;
                });
          } else {
            html = '<tr><td colspan="6" class="text-center py-4">No data available</td></tr>';
          }
          $("#ad-table").html(html);

        var paginationHtml = `
            <ol class="pagination">
                <li class="rounded-l-full bg-slate-150 dark:bg-navy-500">
                    <a href="#" class="pagination-btn flex size-8 items-center justify-center rounded-full text-slate-500 transition-colors hover:bg-slate-300 focus:bg-slate-300 active:bg-slate-300/80 dark:text-navy-200 dark:hover:bg-navy-450 dark:focus:bg-navy-450 dark:active:bg-navy-450/90" data-page="${data.prev_page}" ${data.prev_page ? "" : "disabled"}>
                        <svg xmlns="http://www.w3.org/2000/svg" class="size-4" fill="none" viewbox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7"/>
                        </svg>
                    </a>
                </li>`;
        
        var startPage = Math.max(1, data.current_page - 2);
        var endPage = Math.min(data.total_pages, startPage + 4);
        
        if (startPage > 1) {
            paginationHtml += `<li class="bg-slate-150 dark:bg-navy-500">
                <a href="#" class="pagination-btn flex h-8 min-w-[2rem] items-center justify-center rounded-full px-3 leading-tight transition-colors hover:bg-slate-300 focus:bg-slate-300 active:bg-slate-300/80 dark:hover:bg-navy-450 dark:focus:bg-navy-450 dark:active:bg-navy-450/90" data-page="1">1</a>
            </li>`;
            if (startPage > 2) {
                paginationHtml += `<li class="bg-slate-150 dark:bg-navy-500">...</li>`;
            }
        }
        
        for (var i = startPage; i <= endPage; i++) {
            paginationHtml += `<li class="bg-slate-150 dark:bg-navy-500">
                <a href="#" class="pagination-btn flex h-8 min-w-[2rem] items-center justify-center rounded-full px-3 ${i === data.current_page ? 'bg-primary px-3 leading-tight text-white transition-colors 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' : 'leading-tight transition-colors hover:bg-slate-300 focus:bg-slate-300 active:bg-slate-300/80 dark:hover:bg-navy-450 dark:focus:bg-navy-450 dark:active:bg-navy-450/90'}" data-page="${i}">${i}</a>
            </li>`;
        }
        
        if (endPage < data.total_pages) {
            if (endPage < data.total_pages - 1) {
                paginationHtml += `<li class="bg-slate-150 dark:bg-navy-500">...</li>`;
            }
            paginationHtml += `<li class="bg-slate-150 dark:bg-navy-500">
                <a href="#" class="pagination-btn flex h-8 min-w-[2rem] items-center justify-center rounded-full px-3 leading-tight transition-colors hover:bg-slate-300 focus:bg-slate-300 active:bg-slate-300/80 dark:hover:bg-navy-450 dark:focus:bg-navy-450 dark:active:bg-navy-450/90" data-page="${data.total_pages}">${data.total_pages}</a>
            </li>`;
        }
        
        paginationHtml += `
            <li class="rounded-r-full bg-slate-150 dark:bg-navy-500">
                <a href="#" class="pagination-btn flex size-8 items-center justify-center rounded-full text-slate-500 transition-colors hover:bg-slate-300 focus:bg-slate-300 active:bg-slate-300/80 dark:text-navy-200 dark:hover:bg-navy-450 dark:focus:bg-navy-450 dark:active:bg-navy-450/90" data-page="${data.next_page}" ${data.next_page ? "" : "disabled"}>
                    <svg xmlns="http://www.w3.org/2000/svg" class="size-4" fill="none" viewbox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                    </svg>
                </a>
            </li>
        </ol>`;
        
        $("#pagination").html(paginationHtml);

        },
      });
    }

    $("#pending-ad").click(function() {
        loadAd(1, 0);
    });

    $("#active-ad").click(function() {
        loadAd(1, 1);
    });
    
    $("#rejected-ad").click(function() {
        loadAd(1, 2);
    });
    
    $("#ended-ad").click(function() {
        loadAd(1, 3);
    });
    
    $(document).on("click", ".pagination-btn", function (e) {
      e.preventDefault();
      var page = $(this).data("page");
      if (page) loadAd(page, curStatus);
    });
});
</script>

@endpush
</x-app-layout>
