jQuery(function ($) {

  const currency = (window.SIMPINBY_DATA && SIMPINBY_DATA.currency_symbol) ? SIMPINBY_DATA.currency_symbol : "₹";

  // --- Helper ---
  function money(n) {
    n = parseFloat(n || 0);
    return n.toFixed(2);
  }

  function addRow(productName = "", qty = 1, price = 0) {
    const rowIndex = $("#siItemsBody tr").length;

    const tr = $(`
      <tr>
        <td>
          <input type="text" name="items[${rowIndex}][product_name]" class="simpinby_product_name regular-text" autocomplete="off" value="${productName}">
          <input type="hidden" name="items[${rowIndex}][product_id]" class="simpinby_product_id">
          <div class="simpinby-product-suggestions simpinby-suggestions"></div>
        </td>
        <td><input type="number" name="items[${rowIndex}][qty]" class="simpinby_qty" value="${qty}" min="1"></td>
        <td><input type="number" step="0.01" name="items[${rowIndex}][price]" class="simpinby_price" value="${price}"></td>
        <td>${currency} <span class="simpinby_row_total">0.00</span></td>
        <td><button type="button" class="button simpinby_remove_row">X</button></td>
      </tr>
    `);

    $("#siItemsBody").append(tr);
    calculateTotals();
  }

  function calculateTotals() {
    let subtotal = 0;

    $("#siItemsBody tr").each(function () {
      const qty = parseFloat($(this).find(".simpinby_qty").val() || 0);
      const price = parseFloat($(this).find(".simpinby_price").val() || 0);
      const rowTotal = qty * price;

      $(this).find(".simpinby_row_total").text(money(rowTotal));
      subtotal += rowTotal;
    });

    const discount = parseFloat($("#simpinby_discount").val() || 0);
    let afterDiscount = subtotal - discount;
    if (afterDiscount < 0) afterDiscount = 0;

    // Tax %
    let taxPercent = 0;
    const selectedTaxText = $("#simpinby_tax_id option:selected").text();
    const match = selectedTaxText.match(/\(([\d.]+)%\)/);
    if (match) taxPercent = parseFloat(match[1]);

    const taxTotal = (afterDiscount * taxPercent) / 100;
    const total = afterDiscount + taxTotal;

    $("#simpinby_subtotal").text(money(subtotal));
    $("#simpinby_tax_total").text(money(taxTotal));
    $("#simpinby_total").text(money(total));
  }

  // --- Initial row ---
  addRow();

  // Add row button
  $("#siAddRowBtn").on("click", function () {
    addRow();
  });

  // Remove row
  $(document).on("click", ".simpinby_remove_row", function () {
    $(this).closest("tr").remove();
    calculateTotals();
  });

  // Calculate on change
  $(document).on("input", ".simpinby_qty, .simpinby_price, #simpinby_discount, #simpinby_tax_id", function () {
    calculateTotals();
  });

  // --- Customer Search ---
  let customerTimer = null;

  $("#simpinby_customer_name").on("input", function () {
    clearTimeout(customerTimer);
    const q = $(this).val().trim();

    customerTimer = setTimeout(() => {
      if (q.length < 2) {
        $("#simpinby_customer_suggestions").html("");
        return;
      }

      $.post(SIMPINBY_DATA.ajax_url, {
          action: "simpinby_search_customers",
          nonce: SIMPINBY_DATA.nonce,
          q: q
      }, function (res) {
        if (!res.success) return;

        let html = `<div class="simpinby-suggestions-box">`;
        res.data.forEach(c => {
          html += `<div class="simpinby-suggestion-item" 
                      data-id="${c.id}" 
                      data-name="${c.name}" 
                      data-phone="${c.phone || ''}" 
                      data-email="${c.email || ''}"
                      data-address="${c.address || ''}">
                      ${c.name} ${c.phone ? "(" + c.phone + ")" : ""}
                  </div>`;
        });
        html += `</div>`;

        $("#simpinby_customer_suggestions").html(html);
      });

    }, 250);
  });

 $(document).on("click", "#simpinby_customer_suggestions .simpinby-suggestion-item", function () {

      $("#simpinby_customer_id").val($(this).data("id"));
      $("#simpinby_customer_name").val($(this).data("name"));
      $("#simpinby_customer_email").val($(this).data("email"));
      $("#simpinby_customer_address").val($(this).data("address"));

      let rawPhone = ($(this).data("phone") || "").toString();

      let phone = rawPhone.replace(/\D/g, '');

      let countryCodeSelect = $("#simpinby_country_code");

    
      let detectedCode = null;

      for (let i = 1; i <= 4; i++) {
          let code = phone.substring(0, i);

          if (countryCodeSelect.find(`option[value="${code}"]`).length) {
              detectedCode = code;
          }
      }

    
      if (detectedCode) {
          countryCodeSelect.val(detectedCode);
          phone = phone.substring(detectedCode.length); // remove code from number
      }

      $("#simpinby_customer_phone").val(phone);

      $("#simpinby_customer_suggestions").html("");
  });

  // --- Product Search ---
  let productTimer = null;

  $(document).on("input", ".simpinby_product_name", function () {
    const input = $(this);
    const q = input.val().trim();
    const box = input.closest("td").find(".simpinby-product-suggestions");

    clearTimeout(productTimer);

    productTimer = setTimeout(() => {
      if (q.length < 2) {
        box.html("");
        return;
      }

      $.post(SIMPINBY_DATA.ajax_url, {
          action: "simpinby_search_products",
          nonce: SIMPINBY_DATA.nonce,
          q: q
      }, function (res) {
        if (!res.success) return;

        let html = `<div class="simpinby-suggestions-box">`;
        res.data.forEach(p => {
          html += `<div class="simpinby-suggestion-item" data-id="${p.id}" data-name="${p.name}">
                    ${p.name}
                  </div>`;
        });
        html += `</div>`;
        box.html(html);
      });

    }, 250);
  });

  $(document).on("click", ".simpinby-product-suggestions .simpinby-suggestion-item", function () {
    const td = $(this).closest("td");
    td.find(".simpinby_product_id").val($(this).data("id"));
    td.find(".simpinby_product_name").val($(this).data("name"));
    td.find(".simpinby-product-suggestions").html("");
  });

    // -----------------------------
  // PDF Logo Upload (Media Uploader)
  // -----------------------------
  let siLogoFrame;

  $("#simpinby_upload_logo_btn").on("click", function (e) {
    e.preventDefault();

    if (siLogoFrame) {
      siLogoFrame.open();
      return;
    }

    siLogoFrame = wp.media({
      title: "Select Company Logo",
      button: { text: "Use this logo" },
      multiple: false
    });

    siLogoFrame.on("select", function () {
      const attachment = siLogoFrame.state().get("selection").first().toJSON();
      $("#simpinby_logo_url").val(attachment.url);

      $("#simpinby_logo_preview").attr("src", attachment.url).show();
    });

    siLogoFrame.open();
  });

  $("#simpinby_remove_logo_btn").on("click", function () {
    $("#simpinby_logo_url").val("");
    $("#simpinby_logo_preview").attr("src", "").hide();
  });

    // -----------------------------
  // Front-end validation before submit
  // -----------------------------
  $("#siInvoiceForm").on("submit", function (e) {
      let ok = true;
      let msg = "";

      $("#siItemsBody tr").each(function () {
          const pname = ($(this).find(".simpinby_product_name").val() || "").trim();
          const qty = parseFloat($(this).find(".simpinby_qty").val() || 0);
          const price = parseFloat($(this).find(".simpinby_price").val() || 0);

          if (!pname) {
              ok = false;
              msg = "Product name is required in all rows.";
              return false;
          }

          if (!qty || qty < 1) {
              ok = false;
              msg = "Quantity must be at least 1 for all products.";
              return false;
          }

          if (!price || price <= 0) {
              ok = false;
              msg = "Price must be greater than 0 for all products.";
              return false;
          }
      });

      if (!ok) {
          e.preventDefault();
          alert(msg);
          return false;
      }

      // PHONE NORMALIZATION (SMART PART)
      let phoneInput = $("#simpinby_customer_phone");
      let countryCode = $("#simpinby_country_code").val() || "91";

      let phone = (phoneInput.val() || "").replace(/\D/g, '');

      if (phone) {
          // If number doesn't start with country code → attach it
          if (!phone.startsWith(countryCode)) {
              phone = countryCode + phone;
          }

          phoneInput.val(phone);
      }

  });

   function siUpdatePaidProgressBar() {
    let totalAll  = parseInt($("#simpinby_total_all").text(), 10) || 0;
    let totalPaid = parseInt($("#simpinby_total_paid").text(), 10) || 0;

    let percent = 0;
    if (totalAll > 0) {
        percent = Math.round((totalPaid / totalAll) * 100);
    }

    $("#simpinby_paid_progress_bar").css("width", percent + "%");
    $("#simpinby_paid_progress_bar_text").text(percent + " % Paid");
   
    }

    // Toggle Paid/Unpaid
    $(document).on("click", ".simpinby-toggle-status", function () {
        const btn = $(this);
        const invoiceId = btn.data("id");

        btn.prop("disabled", true).text("Updating...");

        $.post(SIMPINBY_DATA.ajax_url, {
            action: "simpinby_toggle_status",
            nonce: SIMPINBY_DATA.nonce,
            invoice_id: invoiceId
        }, function (res) {

            if (!res || !res.success) {
            alert((res && res.data && res.data.message) ? res.data.message : "Failed to update status");
            btn.prop("disabled", false).text("Try Again");
            return;
            }

            const row = $("#simpinby-invoice-row-" + invoiceId);
            const statusCell = row.find(".simpinby-status-text");

            if (res.data.new_status === "paid") {
            statusCell.html('<span style="color:green; font-weight:700;">PAID</span>');
            btn.text("Mark Unpaid");
            } else {
            statusCell.html('<span style="color:#d63638; font-weight:700;">UNPAID</span>');
            btn.text("Mark Paid");
            }

            btn.prop("disabled", false);

            // Update widgets counts + progress bar
            if (res.data.counts) {
            $("#simpinby_total_all").text(res.data.counts.total_all);
            $("#simpinby_total_paid").text(res.data.counts.total_paid);
            $("#simpinby_total_unpaid").text(res.data.counts.total_unpaid);

            siUpdatePaidProgressBar();
            }

        }).fail(function (xhr) {
            console.log("AJAX ERROR:", xhr.responseText);
            alert("AJAX failed. Check console (F12).");
            btn.prop("disabled", false).text("Try Again");
        });
    });


    // Toggle Archive/Unarchive
    $(document).on("click", ".simpinby-toggle-archive", function () {
        const btn = $(this);
        const invoiceId = btn.data("id");

        btn.prop("disabled", true).text("Updating...");

        $.post(SIMPINBY_DATA.ajax_url, {
            action: "simpinby_toggle_archive",
            nonce: SIMPINBY_DATA.nonce,
            invoice_id: invoiceId
        }, function (res) {

            if (!res || !res.success) {
            alert(res?.data?.message || "Failed to update archive");
            btn.prop("disabled", false).text("Try Again");
            return;
            }

            // remove row from current view
            $("#simpinby-invoice-row-" + invoiceId).fadeOut(200, function () {
            $(this).remove();
            });

            // Update widgets counts + progress bar
            if (res.data.counts) {
            $("#simpinby_total_all").text(res.data.counts.total_all);
            $("#simpinby_total_paid").text(res.data.counts.total_paid);
            $("#simpinby_total_unpaid").text(res.data.counts.total_unpaid);

            siUpdatePaidProgressBar();
            }

            btn.prop("disabled", false);

        }).fail(function (xhr) {
            console.log("AJAX ERROR:", xhr.responseText);
            alert("AJAX failed. Check console (F12).");
            btn.prop("disabled", false).text("Try Again");
        });
    });

    if (!$("#simpinby-full-loader").length) {
      $("body").append(`
        <div id="simpinby-full-loader">
          <div class="simpinby-loader-box">
            <span class="spinner is-active"></span>
            <p id="simpinby-loader-text">Processing...</p>
          </div>
        </div>
      `);
    }

    function showLoader(text = "Processing...") {
      $("#simpinby-loader-text").text(text);
      $("#simpinby-full-loader").fadeIn(150);
    }

    $("#siInvoiceForm").on("submit", function () {
      const activeBtn = document.activeElement;

      if (activeBtn && activeBtn.name === "simpinby_save_send_invoice") {
        showLoader("Saving & sending email...");
      }
    });

    $(document).on("click", "a[href*='send_email=1']", function () {
      $(this).addClass("disabled").text("Sending...");
      showLoader("Sending email...");
    });

    // 🌍 COUNTRY AUTO-DETECT (FIXED)
    const countrySelect = document.getElementById("simpinby_country_code");

    function setCountryByISO(countryCode) {
        let found = false;

        Array.from(countrySelect.options).forEach(opt => {
            if (opt.dataset.country === countryCode) {
                countrySelect.value = opt.value;
                found = true;
            }
        });

        if (!found) {
            console.log("❌ Country not found:", countryCode);
        } else {
            console.log("✅ Country detected:", countryCode);
        }
    }

    // Primary API
    fetch("https://ipapi.co/json/")
    .then(res => res.json())
    .then(data => {
        console.log("API1:", data);

        if (data && data.country) {
            setCountryByISO(data.country);
        } else {
            throw "No country";
        }
    })
    .catch(() => {

        console.log("⚠️ Fallback API...");

        // Fallback
        fetch("https://ipwho.is/")
        .then(res => res.json())
        .then(data => {
            console.log("API2:", data);

            if (data && data.country_code) {
                setCountryByISO(data.country_code);
            }
        })
        .catch(() => {
            console.log("❌ All APIs failed");
        });

    });


});
