<?php
if (!defined("ABSPATH")) exit;

// Pinery Flow — Affiliate URL Metabox & Editor Panel

// Register the meta field (needed for Gutenberg REST API access)
add_action('init', function() {
    register_meta('post', 'affiliate_url', [
        'show_in_rest'    => true,
        'single'          => true,
        'type'            => 'string',
        'auth_callback'   => function() { return current_user_can('edit_posts'); },
        'sanitize_callback'=> 'esc_url_raw',
    ]);
});

// Gutenberg sidebar panel
add_action('enqueue_block_editor_assets', function() {
    $js = '
(function(wp) {
  var el = wp.element.createElement;
  var editPost = wp.data.dispatch("core/editor").editPost;
  var useSelect = wp.data.useSelect;
  var PluginDocumentSettingPanel = wp.editPost.PluginDocumentSettingPanel;
  var registerPlugin = wp.plugins.registerPlugin;

  function AffiliatePanel() {
    var meta = useSelect(function(s) {
      return s("core/editor").getEditedPostAttribute("meta");
    });
    var url = (meta && meta.affiliate_url) || "";

    return el(PluginDocumentSettingPanel, {
      name: "pinery-affiliate-panel",
      title: "Affiliate Link",
      initialOpen: false
    },
      el("div", { style: { marginTop: "8px" } },
        el("p", { style: { fontSize: "12px", color: "#757575", marginBottom: "8px" } },
          "Add the Amazon affiliate/product URL for this post."
        ),
        el("input", {
          type: "url",
          value: url,
          placeholder: "https://www.amazon.com/dp/...",
          onChange: function(e) { editPost({ meta: { affiliate_url: e.target.value } }); },
          style: { width: "100%", padding: "8px 10px", border: "1px solid #ddd", borderRadius: "2px", fontSize: "13px", marginBottom: "8px" }
        }),
        url ? el("a", { href: url, target: "_blank", style: { fontSize: "12px", color: "#0073aa", textDecoration: "none" } }, "Test link ↗") : null
      )
    );
  }

  registerPlugin("pinery-affiliate-link", { render: AffiliatePanel });
})(window.wp);
';
    wp_add_inline_script('wp-plugins', $js);
});

// Classic editor metabox
add_action('add_meta_boxes', function() {
    add_meta_box(
        'pinery_affiliate_url',
        __('Affiliate Link', 'pinery-flow'),
        'pinery_flow_affiliate_metabox_callback',
        'post',
        'side',
        'default'
    );
});

function pinery_flow_affiliate_metabox_callback($post) {
    wp_nonce_field('pinery_affiliate_url_save', 'pinery_affiliate_nonce');
    $url = get_post_meta($post->ID, 'affiliate_url', true);
    echo '<input type="url" name="pinery_affiliate_url" value="' . esc_url($url) . '"
        placeholder="https://www.amazon.com/dp/..."
        style="width:100%;padding:6px 8px;border:1px solid #ddd;border-radius:2px;margin-top:4px;">';
    echo '<p style="font-size:11px;color:#757575;margin-top:6px;">' . __('Amazon affiliate/product link for the lightbox Buy button.', 'pinery-flow') . '</p>';
    if ($url) {
        echo '<p><a href="' . esc_url($url) . '" target="_blank" style="font-size:11px;">' . __('Test link ↗', 'pinery-flow') . '</a></p>';
    }
}

add_action('save_post', function($post_id) {
    if (!isset($_POST['pinery_affiliate_nonce'])) return;
    if (!wp_verify_nonce($_POST['pinery_affiliate_nonce'], 'pinery_affiliate_url_save')) return;
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;
    if (isset($_POST['pinery_affiliate_url'])) {
        update_post_meta($post_id, 'affiliate_url', esc_url_raw($_POST['pinery_affiliate_url']));
    }
});
