<?php
/*-----------------------------------------------*/
/* EXTHEM.ES - PREMIUM WORDPRESS THEMES */
/* Manual Short Link Metabox - FINAL VERSION (Vanilla JS) */
/* Update: 28 Desember 2025 */
/* Converted to Vanilla JavaScript (no jQuery dependency) */
/*-----------------------------------------------*/
if ( ! defined( 'ABSPATH' ) ) exit;

function add_shortlink_metaboxes() { 
        add_meta_box(
            'box_shortlink',
            __('Manual Short Link', THEMES_NAMES),
            'plug_short_link',
            'post',
            'normal',
            'low'
        ); 
}
add_action('add_meta_boxes', 'add_shortlink_metaboxes', 10);

function plug_short_link() {
    global $opt_themes;
    $ouo_apikey 		= $opt_themes['ouo_apikey'] ?? '';
    $shrinkearn_apikey 	= $opt_themes['shrinkearn_apikey'] ?? '';
    $paid4link_apikey 	= $opt_themes['paid4link_apikey'] ?? '';
    $adurl_apikey 		= $opt_themes['adurl_apikey'] ?? '';
    $slink_url 			= get_template_directory_uri() . '/libs/addons/inc/slink.php';
    ?>
    <div class="admin-inside-box clearfix">
        <div class="aps-wrap">
            <div class="aps-tabs-container">
                <div id="aps-tb-shortlink" class="aps-tab-contents active">
                    <div class="aps-group-inputs">
                        <ul class="aps-features">
								<!--
								<li>
                                <div class="aps-col-6" style="text-transform:uppercase">
                                    <span style="font-size: small;"><a href="http://ouo.io/ref/mH4aOrLs" target="_blank"><b style="color:#2271b1;">Register on OUO.IO</b></a> to get your Token</span>
                                </div>
                            </li>
                            <li>
                                <div class="aps-col-6" style="text-transform:uppercase">
                                    <span style="font-size: small;"><a href="https://shrinkearn.com/ref/exthemes" target="_blank"><b style="color:#2271b1;">Register on SHRINKEARN.COM</b></a> to get your Token</span>
                                </div>
                            </li>
                            <li>
                                <div class="aps-col-6" style="text-transform:uppercase">
                                    <span style="font-size: small;"><a href="https://paid4link.com/ref/exthemes" target="_blank"><b style="color:#2271b1;">Register on PAID4LINK.COM</b></a> to get your Token</span>
                                </div>
                            </li>
                            <li>
                                <div class="aps-col-6" style="text-transform:uppercase">
                                    <span style="font-size: small;"><a href="https://adurl.io/ref/exthemes" target="_blank"><b style="color:#2271b1;">Register on ADURL.IO</b></a> to get your Token</span>
                                </div>
                            </li>
								-->	
                            <li>
                                <div class="aps-col-12" style="text-align:center;margin:30px 0;">
                                    <button type="button" class="button button-primary modal-toggle">
                                        CLICK HERE TO SHORTEN YOUR LINK
                                    </button>
                                </div>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal -->
    <div class="modal">
        <div class="modal-overlay"></div>
        <div class="modal-wrapper modal-transition">
            <div class="modal-header">
                <button type="button" class="modal-close">×</button>
                <h2 class="modal-heading">Shorten Your Link</h2>
            </div>
            <div class="modal-body">
                <div class="modal-content">
                    <div id="results" style="margin-bottom:20px; display:none;"></div>
                    <form id="myForm">
                        <div class="form-row">
                            <label for="service">Service <span class="text-danger">*</span></label>
                            <select name="service" id="service" class="form-control">
                                <option value="ouo">OUO.IO</option>
                                <option value="shrinkearn">ShrinkEarn</option>
                                <option value="paid4link">Paid4Link</option>
                                <option value="adurl">AdURL</option>
                                <option value="more">more (contact exthem.es)</option>
                            </select>
                        </div>
                        <div class="form-row">
                            <label for="apikey">Token / API Key:</label>
                            <input readonly type="text" class="aps-text-input" name="apikey" id="apikey" />
                            <small>The token will be automatically filled based on the selected service, you can add Token / API Key on option themes</small>
                        </div>
                        <div class="form-row">
                            <label for="longurl">Long URL:</label>
                            <input type="text" class="aps-text-input" name="longurl" id="longurl" placeholder="https://example.com/very-long-url"  />
                        </div>
                        <button type="button" id="submitFormData" class="button button-primary">
                            Submit & Shorten
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <?php
    // Hidden inputs untuk auto-fill token
    echo '<input type="hidden" id="ouo_key" value="' . esc_attr($ouo_apikey) . '">';
    echo '<input type="hidden" id="shrinkearn_key" value="' . esc_attr($shrinkearn_apikey) . '">';
    echo '<input type="hidden" id="paid4link_key" value="' . esc_attr($paid4link_apikey) . '">';
    echo '<input type="hidden" id="adurl_key" value="' . esc_attr($adurl_apikey) . '">';
    echo '<input type="hidden" id="slink_url" value="' . esc_attr($slink_url) . '">';
}
add_action('admin_enqueue_scripts', 'shortlink_metabox_scripts');

function shortlink_metabox_scripts($hook) {
    global $post, $opt_themes;
    if ($hook !== 'post.php' && $hook !== 'post-new.php') return;
    if ($post->post_type !== 'post') return;
    if (empty($opt_themes['shortlink_post'])) return;

    // Only add custom CSS (no jQuery needed)
    wp_add_inline_style('wp-admin', '
        .modal {display:none;position:fixed;z-index:10000;top:0;left:0;width:100%;height:100%;background:hsla(0,0%,0%,0.5);}
        .modal.is-visible {display:block;}
        .modal-wrapper {position:absolute;top:10%;left:50%;transform:translateX(-50%);width:90%;max-width:550px;background:#fff;box-shadow:0 0 30px rgba(0,0,0,0.4);border-radius:10px;overflow:hidden;}
        .modal-header {padding:15px 20px;background:#f7f7f7;border-bottom:1px solid #ddd;position:relative;}
        .modal-close {position:absolute;top:8px;right:15px;background:none;border:none;font-size:32px;cursor:pointer;color:#999;width:40px;height:40px;line-height:36px;border-radius:50%;transition:all .2s;}
        .modal-close:hover {color:#000;background:#f0f0f0;}
        .modal-heading {margin:0;font-size:1.4em;}
        .modal-body {padding:30px;}
        .form-row {margin-bottom:20px;}
        .form-row label {display:block;margin-bottom:8px;font-weight:bold;}
        .aps-text-input, .form-control {width:100%;padding:12px;border:1px solid #ccc;border-radius:6px;box-sizing:border-box;font-size:14px;}
        #results {padding:15px;background:#f9f9f9;border:1px solid #ddd;border-radius:6px;min-height:60px;font-size:14px;line-height:1.5;}
        @media (max-width:782px) {.modal-wrapper {top:5%;width:95%;}}
    ');

    // Vanilla JavaScript (no jQuery)
    wp_add_inline_script('jquery', '
        document.addEventListener("DOMContentLoaded", function() {
            const modal = document.querySelector(".modal");
            const modalToggle = document.querySelector(".modal-toggle");
            const modalClose = document.querySelector(".modal-close");
            const overlay = document.querySelector(".modal-overlay");
            const serviceSelect = document.getElementById("service");
            const apikeyInput = document.getElementById("apikey");
            const longurlInput = document.getElementById("longurl");
            const resultsDiv = document.getElementById("results");
            const submitBtn = document.getElementById("submitFormData");
            const slinkUrl = document.getElementById("slink_url").value;

            // Open modal
            if (modalToggle) {
                modalToggle.addEventListener("click", function(e) {
                    e.preventDefault();
                    modal.classList.add("is-visible");
                    longurlInput.focus();
                    resultsDiv.style.display = "none";
                    resultsDiv.innerHTML = "";
                });
            }

            // Close modal
            function closeModal() {
                modal.classList.remove("is-visible");
            }
            if (modalClose) modalClose.addEventListener("click", closeModal);
            if (overlay) overlay.addEventListener("click", closeModal);
            modal.addEventListener("click", function(e) {
                if (e.target === modal) closeModal();
            });
            document.addEventListener("keyup", function(e) {
                if (e.key === "Escape" && modal.classList.contains("is-visible")) closeModal();
            });
            document.querySelector(".modal-wrapper").addEventListener("click", function(e) {
                e.stopPropagation();
            });

            // Auto-fill API key
            function updateApikey() {
                let service = serviceSelect.value;
                let key = "";
                if (service === "ouo") key = document.getElementById("ouo_key").value;
                else if (service === "shrinkearn") key = document.getElementById("shrinkearn_key").value;
                else if (service === "paid4link") key = document.getElementById("paid4link_key").value;
                else if (service === "adurl") key = document.getElementById("adurl_key").value;
                else if (service === "more") {
                    key = "";
                    resultsDiv.innerHTML = "<p style=\\"color:#2271b1;font-weight:bold;\\">Contact exthem.es for additional services.</p>";
                    resultsDiv.style.display = "block";
                }
                apikeyInput.value = key;
            }
            serviceSelect.addEventListener("change", updateApikey);
            updateApikey(); // Initial fill

            // Submit & Shorten
            submitBtn.addEventListener("click", function() {
                let longurl = longurlInput.value.trim();
                let service = serviceSelect.value;
                let apikey = apikeyInput.value.trim();

                if (service === "more") {
                    resultsDiv.innerHTML = "<p style=\\"color:#2271b1;font-weight:bold;\\">Please select a valid service or contact exthem.es.</p>";
                    resultsDiv.style.display = "block";
                    return;
                }
                if (!longurl) {
                    resultsDiv.innerHTML = "<p style=\\"color:red;font-weight:bold;\\">Please enter a Long URL.</p>";
                    resultsDiv.style.display = "block";
                    return;
                }
                if (!/^https?:\/\//i.test(longurl)) {
                    resultsDiv.innerHTML = "<p style=\\"color:red;font-weight:bold;\\">Invalid URL: Must start with http:// or https://</p>";
                    resultsDiv.style.display = "block";
                    return;
                }
                if (!apikey) {
                    resultsDiv.innerHTML = "<p style=\\"color:red;font-weight:bold;\\">API Key/Token is empty for this service.</p>";
                    resultsDiv.style.display = "block";
                    return;
                }

                resultsDiv.innerHTML = "<p style=\\"padding:15px;background:#e3f2fd;color:#1976d2;border-radius:6px;text-align:center;\\"><strong>Processing your link...</strong></p>";
                resultsDiv.style.display = "block";

                fetch(slinkUrl, {
                    method: "POST",
                    headers: { "Content-Type": "application/x-www-form-urlencoded" },
                    body: new URLSearchParams({
                        longurl: longurl,
                        apikey: apikey,
                        service: service
                    })
                })
                .then(response => response.text())
                .then(data => {
                    longurlInput.value = "";
                    resultsDiv.innerHTML = data;
                    // Add copy button if short link present
                    let shortInput = resultsDiv.querySelector("input[type=\\"text\\"][value*=\\"http\\"]");
                    if (shortInput) {
                        shortInput.focus();
                        shortInput.select();
                        let copyBtn = document.getElementById("copy-btn");
                        if (!copyBtn) {
                            copyBtn = document.createElement("button");
                            copyBtn.type = "button";
                            copyBtn.id = "copy-btn";
                            copyBtn.className = "button button-secondary";
                            copyBtn.style.marginTop = "12px";
                            copyBtn.textContent = "Copy to Clipboard";
                            shortInput.insertAdjacentElement("afterend", document.createElement("br"));
                            shortInput.insertAdjacentElement("afterend", copyBtn);
                        } else {
                            copyBtn.textContent = "Copy to Clipboard";
                            copyBtn.className = "button button-secondary";
                            copyBtn.disabled = false;
                        }
                        copyBtn.onclick = function() {
                            navigator.clipboard.writeText(shortInput.value).then(() => {
                                copyBtn.textContent = "Copied! ✓";
                                copyBtn.className = "button button-primary";
                                copyBtn.disabled = true;
                                setTimeout(() => {
                                    copyBtn.textContent = "Copy to Clipboard";
                                    copyBtn.className = "button button-secondary";
                                    copyBtn.disabled = false;
                                }, 2000);
                            }).catch(() => {
                                alert("Copy failed. Please copy manually.");
                            });
                        };
                    }
                })
                .catch(() => {
                    resultsDiv.innerHTML = "<p style=\\"color:red;padding:15px;background:#ffebee;border:1px solid #fcc;border-radius:6px;\\"><strong>Connection Failed!</strong><br>Unable to reach server. Check internet or slink.php file.</p>";
                });
            });
        });
    ', 'after');
}