<?php

namespace GriffinForms\Admin\Html\Modals;

class PublishForm extends \GriffinForms\Admin\Html\Modals\Format
{
    protected $placement_service;
    protected $page_options = [];
    protected $post_options = [];

    protected function setPlacementService()
    {
        $this->placement_service = \GriffinForms\Includes\Onboarding\PlacementService::getInstance();
    }

    protected function headerText()
    {
        return __('Publish Form', 'griffinforms-form-builder');
    }

    protected function modalContent()
    {
        $form_id = absint($this->data['form_id'] ?? 0);
        $shortcode = $form_id > 0 ? $this->placement_service->getShortcode($form_id) : '';
        $this->page_options = $this->placement_service->getContentOptions('page');
        $this->post_options = $this->placement_service->getContentOptions('post');

        echo '<div class="gf-publish-form-modal" data-gf-publish-form-modal="true">';
        echo '<div class="gf-publish-form-modal__intro mb-3">';
        echo '<p class="small text-muted mb-0">' . esc_html__('Choose where to place this form. You can also copy the shortcode for manual placement.', 'griffinforms-form-builder') . '</p>';
        echo '</div>';

        echo '<input type="hidden" id="griffinforms-publish-form-id" value="' . esc_attr($form_id) . '">';

        echo '<div class="mb-3">';
        echo '<label class="form-label fw-semibold" for="griffinforms-publish-form-shortcode">' . esc_html__('Shortcode', 'griffinforms-form-builder') . '</label>';
        echo '<div class="input-group input-group-sm">';
        echo '<input type="text" readonly class="form-control" id="griffinforms-publish-form-shortcode" value="' . esc_attr($shortcode) . '">';
        echo '<button type="button" class="button" id="griffinforms-publish-form-copy-shortcode">' . esc_html__('Copy', 'griffinforms-form-builder') . '</button>';
        echo '</div>';
        echo '</div>';

        echo '<div class="mb-3">';
        echo '<div class="small fw-semibold mb-2">' . esc_html__('Placement', 'griffinforms-form-builder') . '</div>';
        echo '<div class="d-grid gap-2">';
        $this->renderPlacementChoice('create_and_add_to_new_page', __('Create new page', 'griffinforms-form-builder'), true);
        $this->renderPlacementChoice('create_and_add_to_new_post', __('Create new post', 'griffinforms-form-builder'));
        $this->renderPlacementChoice('add_to_existing_content', __('Add to existing content', 'griffinforms-form-builder'));
        echo '</div>';
        echo '</div>';

        echo '<div class="gf-publish-form-modal__fields">';
        echo '<div class="gf-publish-form-modal__group" data-gf-placement-fields="create_and_add_to_new_page">';
        echo '<label class="form-label" for="griffinforms-publish-new-page-title">' . esc_html__('Page title', 'griffinforms-form-builder') . '</label>';
        echo '<input type="text" class="form-control form-control-sm" id="griffinforms-publish-new-page-title" value="">';
        echo '</div>';

        echo '<div class="gf-publish-form-modal__group d-none" data-gf-placement-fields="create_and_add_to_new_post">';
        echo '<label class="form-label" for="griffinforms-publish-new-post-title">' . esc_html__('Post title', 'griffinforms-form-builder') . '</label>';
        echo '<input type="text" class="form-control form-control-sm" id="griffinforms-publish-new-post-title" value="">';
        echo '</div>';

        echo '<div class="gf-publish-form-modal__group d-none" data-gf-placement-fields="add_to_existing_content">';
        echo '<div class="row g-2">';
        echo '<div class="col-md-4">';
        echo '<label class="form-label" for="griffinforms-publish-target-type">' . esc_html__('Target type', 'griffinforms-form-builder') . '</label>';
        echo '<select class="form-select form-select-sm" id="griffinforms-publish-target-type">';
        echo '<option value="page">' . esc_html__('Page', 'griffinforms-form-builder') . '</option>';
        echo '<option value="post">' . esc_html__('Post', 'griffinforms-form-builder') . '</option>';
        echo '</select>';
        echo '</div>';
        echo '<div class="col-md-8">';
        echo '<label class="form-label" for="griffinforms-publish-target-id">' . esc_html__('Select content', 'griffinforms-form-builder') . '</label>';
        echo '<select class="form-select form-select-sm" id="griffinforms-publish-target-id">';
        echo '<option value="0">' . esc_html__('Select content', 'griffinforms-form-builder') . '</option>';
        foreach ($this->page_options as $option) {
            echo '<option value="' . absint($option['id']) . '" data-gf-target-type="page">' . esc_html('[Page] ' . $option['title'] . ' (' . $option['status'] . ')') . '</option>';
        }
        foreach ($this->post_options as $option) {
            echo '<option value="' . absint($option['id']) . '" data-gf-target-type="post">' . esc_html('[Post] ' . $option['title'] . ' (' . $option['status'] . ')') . '</option>';
        }
        echo '</select>';
        echo '</div>';
        echo '</div>';
        echo '</div>';
        echo '</div>';

        echo '<div class="gf-publish-form-modal__result mt-3" id="griffinforms-publish-form-result" style="display:none;"></div>';
        echo '</div>';
    }

    protected function renderPlacementChoice(string $value, string $label, bool $checked = false): void
    {
        $id = 'griffinforms-publish-choice-' . sanitize_key($value);
        echo '<label class="gf-publish-choice p-2 d-flex align-items-center gap-2">';
        echo '<input type="radio" name="placement_action" value="' . esc_attr($value) . '"' . checked($checked, true, false) . '>';
        echo '<span class="small fw-semibold">' . esc_html($label) . '</span>';
        echo '</label>';
    }

    protected function modalFooter()
    {
        echo '<div class="modal-footer border-top-0 gap-2">';
        echo '<button type="button" class="button" data-bs-dismiss="modal">' . esc_html($this->lang->getText('cancel_btn')) . '</button>';
        echo '<button type="button" class="button button-primary" id="griffinforms-publish-form-submit">' . esc_html__('Publish', 'griffinforms-form-builder') . '</button>';
        echo '</div>';
    }

    public function modalJs()
    {
        $js  = 'jQuery(document).ready(function($){' . PHP_EOL;
        $js .= 'const placementNonce = "' . esc_js(wp_create_nonce('griffinforms_place_form')) . '";' . PHP_EOL;
        $js .= 'const modalId = "' . esc_js($this->id) . '";' . PHP_EOL;
        $js .= 'const $modal = $("#" + modalId);' . PHP_EOL;
        $js .= 'const $result = $("#griffinforms-publish-form-result");' . PHP_EOL;
        $js .= 'const $shortcode = $("#griffinforms-publish-form-shortcode");' . PHP_EOL;
        $js .= 'const $formId = $("#griffinforms-publish-form-id");' . PHP_EOL;
        $js .= 'const $actionInputs = $modal.find(\'input[name="placement_action"]\');' . PHP_EOL;
        $js .= 'const $targetType = $("#griffinforms-publish-target-type");' . PHP_EOL;
        $js .= 'const $targetId = $("#griffinforms-publish-target-id");' . PHP_EOL;
        $js .= 'const $newPageTitle = $("#griffinforms-publish-new-page-title");' . PHP_EOL;
        $js .= 'const $newPostTitle = $("#griffinforms-publish-new-post-title");' . PHP_EOL;
        $js .= 'let inFlight = false;' . PHP_EOL;
        $js .= 'function showMessage(type, message, payload) {' . PHP_EOL;
        $js .= '  const links = [];' . PHP_EOL;
        $js .= '  if (payload && payload.edit_url) { links.push(\'<a href="\' + payload.edit_url + \'" target="_blank" rel="noopener noreferrer">Edit</a>\'); }' . PHP_EOL;
        $js .= '  if (payload && payload.view_url) { links.push(\'<a href="\' + payload.view_url + \'" target="_blank" rel="noopener noreferrer">View</a>\'); }' . PHP_EOL;
        $js .= '  const noticeType = type === "success" ? "success" : (type === "warning" ? "warning" : "danger");' . PHP_EOL;
        $js .= '  const html = \'<div class="gf-notice gf-notice-\' + noticeType + \'" role="alert"><div>\' + message + (links.length ? \' <span class="ms-2">\' + links.join(\' | \') + \'</span>\' : \'\') + \'</div></div>\';' . PHP_EOL;
        $js .= '  const $notice = $(html);' . PHP_EOL;
        $js .= '  $result.html($notice).show();' . PHP_EOL;
        $js .= '  if (type === "success") {' . PHP_EOL;
        $js .= '    const $headerTarget = $(".wp-header-end").first();' . PHP_EOL;
        $js .= '    if ($headerTarget.length) {' . PHP_EOL;
        $js .= '      const pageNoticeHtml = \'<div class="notice notice-success is-dismissible"><p>\' + message + (links.length ? \' <span class="ms-2">\' + links.join(\' | \') + \'</span>\' : \'\') + \'</p><button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button></div>\';' . PHP_EOL;
        $js .= '      const $pageNotice = $(pageNoticeHtml).insertBefore($headerTarget);' . PHP_EOL;
        $js .= '      $pageNotice.on("click", ".notice-dismiss", function() { $pageNotice.remove(); });' . PHP_EOL;
        $js .= '    }' . PHP_EOL;
        $js .= '    const modalInstance = window.bootstrap && bootstrap.Modal ? bootstrap.Modal.getInstance($modal[0]) || bootstrap.Modal.getOrCreateInstance($modal[0]) : null;' . PHP_EOL;
        $js .= '    if (modalInstance) {' . PHP_EOL;
        $js .= '      modalInstance.hide();' . PHP_EOL;
        $js .= '    }' . PHP_EOL;
        $js .= '  }' . PHP_EOL;
        $js .= '}' . PHP_EOL;
        $js .= 'function setPlacementFields() {' . PHP_EOL;
        $js .= '  const selected = $actionInputs.filter(":checked").val() || "create_and_add_to_new_page";' . PHP_EOL;
        $js .= '  $modal.find("[data-gf-placement-fields]").each(function() {' . PHP_EOL;
        $js .= '    $(this).toggleClass("d-none", $(this).attr("data-gf-placement-fields") !== selected);' . PHP_EOL;
        $js .= '  });' . PHP_EOL;
        $js .= '}' . PHP_EOL;
        $js .= 'function filterTargets() {' . PHP_EOL;
        $js .= '  const targetType = $targetType.val();' . PHP_EOL;
        $js .= '  $targetId.find("option").each(function() {' . PHP_EOL;
        $js .= '    const optionType = $(this).attr("data-gf-target-type");' . PHP_EOL;
        $js .= '    if (!optionType) { return; }' . PHP_EOL;
        $js .= '    $(this).prop("hidden", optionType !== targetType);' . PHP_EOL;
        $js .= '  });' . PHP_EOL;
        $js .= '  if ($targetId.find("option:selected").prop("hidden")) { $targetId.val("0"); }' . PHP_EOL;
        $js .= '}' . PHP_EOL;
        $js .= '$modal.on("show.bs.modal", function(event) {' . PHP_EOL;
        $js .= '  $result.hide().empty();' . PHP_EOL;
        $js .= '  const trigger = event.relatedTarget ? $(event.relatedTarget) : $();' . PHP_EOL;
        $js .= '  const formId = trigger.data("gfFormId") || trigger.attr("data-gf-form-id") || 0;' . PHP_EOL;
        $js .= '  const shortcode = trigger.data("gfShortcode") || trigger.attr("data-gf-shortcode") || "";' . PHP_EOL;
        $js .= '  $formId.val(formId);' . PHP_EOL;
        $js .= '  if (shortcode) { $shortcode.val(shortcode); }' . PHP_EOL;
        $js .= '  $actionInputs.filter("[value=create_and_add_to_new_page]").prop("checked", true);' . PHP_EOL;
        $js .= '  $newPageTitle.val(trigger.data("gfPageTitle") || trigger.attr("data-gf-page-title") || "");' . PHP_EOL;
        $js .= '  $newPostTitle.val(trigger.data("gfPostTitle") || trigger.attr("data-gf-post-title") || "");' . PHP_EOL;
        $js .= '  $targetType.val("page");' . PHP_EOL;
        $js .= '  $targetId.val("0");' . PHP_EOL;
        $js .= '  setPlacementFields();' . PHP_EOL;
        $js .= '  filterTargets();' . PHP_EOL;
        $js .= '});' . PHP_EOL;
        $js .= '$actionInputs.on("change", setPlacementFields);' . PHP_EOL;
        $js .= '$targetType.on("change", filterTargets);' . PHP_EOL;
        $js .= 'function copyShortcode() {' . PHP_EOL;
        $js .= '  const value = $shortcode.val();' . PHP_EOL;
        $js .= '  if (!value) { return; }' . PHP_EOL;
        $js .= '  if (navigator.clipboard && navigator.clipboard.writeText) {' . PHP_EOL;
        $js .= '    navigator.clipboard.writeText(value);' . PHP_EOL;
        $js .= '  } else {' . PHP_EOL;
        $js .= '    const textarea = document.createElement("textarea"); textarea.value = value; textarea.style.position = "fixed"; textarea.style.opacity = "0"; document.body.appendChild(textarea); textarea.select(); document.execCommand("copy"); document.body.removeChild(textarea);' . PHP_EOL;
        $js .= '  }' . PHP_EOL;
        $js .= '  const $copyBtn = $("#griffinforms-publish-form-copy-shortcode");' . PHP_EOL;
        $js .= '  const originalText = $copyBtn.text();' . PHP_EOL;
        $js .= '  $copyBtn.text("' . esc_js(__('Copied', 'griffinforms-form-builder')) . '");' . PHP_EOL;
        $js .= '  setTimeout(function() { $copyBtn.text(originalText); }, 1600);' . PHP_EOL;
        $js .= '}' . PHP_EOL;
        $js .= '$modal.on("click", "#griffinforms-publish-form-copy-shortcode", function(e) { e.preventDefault(); copyShortcode(); });' . PHP_EOL;
        $js .= '$modal.on("click", "#griffinforms-publish-form-submit", function(e) {' . PHP_EOL;
        $js .= '  e.preventDefault();' . PHP_EOL;
        $js .= '  if (inFlight) { return; }' . PHP_EOL;
        $js .= '  const formId = parseInt($formId.val(), 10) || 0;' . PHP_EOL;
        $js .= '  const placementAction = $actionInputs.filter(":checked").val() || "create_and_add_to_new_page";' . PHP_EOL;
        $js .= '  const targetType = $targetType.val() || "page";' . PHP_EOL;
        $js .= '  const targetId = parseInt($targetId.val(), 10) || 0;' . PHP_EOL;
        $js .= '  const pageTitle = placementAction === "create_and_add_to_new_post" ? $newPostTitle.val() : $newPageTitle.val();' . PHP_EOL;
        $js .= '  if (!formId) { showMessage("danger", "' . esc_js(__('Unable to resolve the selected form.', 'griffinforms-form-builder')) . '"); return; }' . PHP_EOL;
        $js .= '  if ((placementAction === "add_to_existing_content" && targetId < 1) || ((placementAction === "create_and_add_to_new_page" || placementAction === "create_and_add_to_new_post") && !pageTitle.trim())) {' . PHP_EOL;
        $js .= '    showMessage("warning", "' . esc_js(__('Please enter a page title or post title before publishing.', 'griffinforms-form-builder')) . '");' . PHP_EOL;
        $js .= '    return;' . PHP_EOL;
        $js .= '  }' . PHP_EOL;
        $js .= '  inFlight = true;' . PHP_EOL;
        $js .= '  $.post(ajaxurl, {' . PHP_EOL;
        $js .= '    action: "griffinforms_place_form",' . PHP_EOL;
        $js .= '    form_id: formId,' . PHP_EOL;
        $js .= '    placement_action: placementAction,' . PHP_EOL;
        $js .= '    placement_target_type: targetType,' . PHP_EOL;
        $js .= '    placement_target_id: targetId,' . PHP_EOL;
        $js .= '    page_title: pageTitle,' . PHP_EOL;
        $js .= '    nonce: placementNonce' . PHP_EOL;
        $js .= '  }, function(response) {' . PHP_EOL;
        $js .= '    if (response && response.success && response.data) {' . PHP_EOL;
        $js .= '      showMessage("success", response.data.message || "' . esc_js(__('Form placed successfully.', 'griffinforms-form-builder')) . '", response.data);' . PHP_EOL;
        $js .= '      if (response.data.post_id) { sessionStorage.setItem("highlightItemId", response.data.post_id); }' . PHP_EOL;
        $js .= '      return;' . PHP_EOL;
        $js .= '    }' . PHP_EOL;
        $js .= '    const message = response && response.data && response.data.message ? response.data.message : "' . esc_js(__('Publishing failed.', 'griffinforms-form-builder')) . '";' . PHP_EOL;
        $js .= '    showMessage("danger", message);' . PHP_EOL;
        $js .= '  }).fail(function() {' . PHP_EOL;
        $js .= '    showMessage("danger", "' . esc_js(__('Network request failed. Try again later.', 'griffinforms-form-builder')) . '");' . PHP_EOL;
        $js .= '  }).always(function() {' . PHP_EOL;
        $js .= '    inFlight = false;' . PHP_EOL;
        $js .= '  });' . PHP_EOL;
        $js .= '});' . PHP_EOL;
        $js .= '});';

        wp_add_inline_script('griffinforms-global-js', $js);
    }
}
