<?php
/**
 * YeePDF Forminator Integration form settings.
 * Handles the per-form wizard shown on the Integrations tab of the form builder.
 */
if (!defined('ABSPATH'))
    exit; // Exit if accessed directly

class Forminator_Yeepdf_Form_Settings extends Forminator_Integration_Form_Settings
{
    /**
     * Stable connection id. This integration allows a single PDF connection
     * per form (is_allow_multi_on_form = false), so we use a fixed multi_id
     * to always overwrite the same connection instead of accumulating new ones.
     */
    const CONNECTION_ID = 'yeepdf';

    /**
     * Settings wizard steps for a form.
     *
     * @return array
     */
    public function module_settings_wizards()
    {
        return array(
            array(
                'callback'     => array($this, 'setup_template'),
                'is_completed' => array($this, 'setup_template_is_completed'),
            ),
        );
    }

    /**
     * Use a fixed connection id for single-connection semantics.
     *
     * @return string
     */
    public function generate_multi_id()
    {
        return self::CONNECTION_ID;
    }

    /**
     * Choose the PDF template and options for this form.
     *
     * @param array $submitted_data Submitted data.
     *
     * @return array
     */
    public function setup_template($submitted_data)
    {
        $this->addon_settings = $this->get_settings_values();

        $multi_id = $this->generate_multi_id();
        if (isset($submitted_data['multi_id'])) {
            $multi_id = $submitted_data['multi_id'];
        }
        unset($submitted_data['multi_id']);

        $is_submit = !empty($submitted_data);

        $current_data = array(
            'template_id'  => '',
            'file_name'    => '',
            'password'     => '',
            'save_dropbox' => 0,
        );
        foreach ($current_data as $key => $value) {
            if (isset($submitted_data[$key])) {
                $current_data[$key] = $submitted_data[$key];
            } elseif (isset($this->addon_settings[$multi_id][$key])) {
                $current_data[$key] = $this->addon_settings[$multi_id][$key];
            }
        }

        $templates            = $this->get_templates();
        $dropbox_connected    = yeepdf_forminator_dropbox_connected();
        $error_message        = '';
        $input_error_messages = array();
        $notification         = array();

        try {
            if ($is_submit) {
                $template_id = isset($submitted_data['template_id']) ? (int) $submitted_data['template_id'] : 0;
                if ($template_id <= 0 || !isset($templates[$template_id])) {
                    $input_exceptions = new Forminator_Integration_Settings_Exception();
                    $input_exceptions->add_input_exception(esc_html__('Please select a PDF template.', 'pdf-for-wpforms'), 'template_id');
                    throw $input_exceptions;
                }

                $save_dropbox = (!empty($submitted_data['save_dropbox']) && $dropbox_connected) ? 1 : 0;

                $this->addon_settings = array_merge(
                    $this->addon_settings,
                    array(
                        $multi_id => array(
                            'name'         => $templates[$template_id],
                            'template_id'  => $template_id,
                            'file_name'    => sanitize_text_field($current_data['file_name']),
                            'password'     => sanitize_text_field($current_data['password']),
                            'save_dropbox' => $save_dropbox,
                        ),
                    )
                );
                $this->save_module_settings_values();

                $notification = array(
                    'type' => 'success',
                    'text' => '<strong>' . $this->addon->get_title() . '</strong> ' . esc_html__('Successfully connected to this form.', 'pdf-for-wpforms'),
                );
            }
        } catch (Forminator_Integration_Settings_Exception $e) {
            $input_error_messages = $e->get_input_exceptions();
        } catch (Forminator_Integration_Exception $e) {
            $error_message = $e->get_error_notice();
        }

        $buttons = array();
        if ($this->setup_template_is_completed(array('multi_id' => $multi_id))) {
            $buttons['disconnect']['markup'] = Forminator_Integration::get_button_markup(
                esc_html__('Deactivate', 'forminator'),
                'sui-button-ghost sui-tooltip sui-tooltip-top-center forminator-addon-form-disconnect',
                esc_html__('Deactivate PDF Templates from this form.', 'pdf-for-wpforms')
            );
        }
        $buttons['next']['markup'] = '<div class="sui-actions-right">' .
            Forminator_Integration::get_button_markup(esc_html__('Save', 'forminator'), 'sui-button-primary forminator-addon-finish') .
            '</div>';

        $template_error = isset($input_error_messages['template_id']) ? $input_error_messages['template_id'] : '';

        $html  = '<div class="forminator-integration-popup__header">';
        $html .= '<h3 class="sui-box-title sui-lg" id="dialogTitle2">' . esc_html__('Set Up PDF Template', 'pdf-for-wpforms') . '</h3>';
        $html .= '<p class="sui-description">' . esc_html__('Choose the PDF template to generate and attach to the email notifications of this form.', 'pdf-for-wpforms') . '</p>';
        $html .= $error_message;
        $html .= '</div>';
        $html .= '<form enctype="multipart/form-data">';
        if (empty($templates)) {
            $html .= '<p class="sui-description">' . sprintf(
                /* translators: 1: anchor start, 2: anchor end. */
                esc_html__('No PDF template found. %1$sCreate a PDF template%2$s first, then come back here.', 'pdf-for-wpforms'),
                '<a href="' . esc_url(admin_url('post-new.php?post_type=yeepdf')) . '" target="_blank">',
                '</a>'
            ) . '</p>';
        } else {
            // PDF template.
            $html .= '<div class="sui-form-field' . ($template_error ? ' sui-form-field-error' : '') . '">';
            $html .= '<label class="sui-label">' . esc_html__('PDF Template', 'pdf-for-wpforms') . '</label>';
            $html .= '<select name="template_id" class="sui-select">';
            $html .= '<option value="">' . esc_html__('Select a template', 'pdf-for-wpforms') . '</option>';
            foreach ($templates as $id => $title) {
                $html .= '<option value="' . esc_attr($id) . '" ' . selected($current_data['template_id'], $id, false) . '>' . esc_html($title) . '</option>';
            }
            $html .= '</select>';
            if ($template_error) {
                $html .= '<span class="sui-error-message">' . esc_html($template_error) . '</span>';
            }
            $html .= '</div>';

            // File name.
            $html .= '<div class="sui-form-field">';
            $html .= '<label class="sui-label">' . esc_html__('File Name', 'pdf-for-wpforms') . '</label>';
            $html .= '<input type="text" name="file_name" placeholder="' . esc_attr__('e.g. invoice-{form_id}', 'pdf-for-wpforms') . '" value="' . esc_attr($current_data['file_name']) . '" class="sui-form-control" />';
            $html .= '<span class="sui-description">' . esc_html__('Name of the generated PDF file (without extension). Leave empty to auto-generate. You can use form field merge tags, e.g. {name-1}.', 'pdf-for-wpforms') . '</span>';
            $html .= '</div>';

            // Password.
            $html .= '<div class="sui-form-field">';
            $html .= '<label class="sui-label">' . esc_html__('Password Protection', 'pdf-for-wpforms') . '</label>';
            $html .= '<input type="text" name="password" placeholder="' . esc_attr__('Leave empty for no password', 'pdf-for-wpforms') . '" value="' . esc_attr($current_data['password']) . '" class="sui-form-control" />';
            $html .= '<span class="sui-description">' . esc_html__('Encrypt the generated PDF with this password. Merge tags are supported.', 'pdf-for-wpforms') . '</span>';
            $html .= '</div>';

            // Save to Dropbox.
            $html .= '<div class="sui-form-field">';
            $html .= '<label class="sui-toggle">';
            $html .= '<input type="checkbox" name="save_dropbox" value="1" id="forminator-yeepdf-save-dropbox" ' . checked(1, $current_data['save_dropbox'], false) . ' ' . disabled($dropbox_connected, false, false) . ' />';
            $html .= '<span class="sui-toggle-slider"></span>';
            $html .= '<span class="sui-toggle-label">' . esc_html__('Save a copy to Dropbox', 'pdf-for-wpforms') . '</span>';
            $html .= '</label>';
            if ($dropbox_connected) {
                $html .= '<span class="sui-description" style="margin-left: 0;">' . esc_html__('Upload each generated PDF to your connected Dropbox account.', 'pdf-for-wpforms') . '</span>';
            } else {
                $html .= '<span class="sui-description" style="margin-left: 0;">' . sprintf(
                    /* translators: 1: anchor start, 2: anchor end. */
                    esc_html__('Connect Dropbox in the %1$sPDF Templates settings%2$s to enable this option.', 'pdf-for-wpforms'),
                    '<a href="' . esc_url(admin_url('edit.php?post_type=yeepdf&page=yeepdf-settings')) . '" target="_blank">',
                    '</a>'
                ) . '</span>';
            }
            $html .= '</div>';
        }
        $html .= '<input type="hidden" name="multi_id" value="' . esc_attr($multi_id) . '" />';
        $html .= '</form>';

        return array(
            'html'         => $html,
            'redirect'     => false,
            'is_close'     => ($is_submit && empty($error_message) && empty($input_error_messages)),
            'buttons'      => $buttons,
            'has_errors'   => (!empty($error_message) || !empty($input_error_messages)),
            'notification' => $notification,
        );
    }

    /**
     * Check if the template step is completed.
     *
     * @param array $submitted_data Submitted data.
     *
     * @return bool
     */
    public function setup_template_is_completed($submitted_data)
    {
        $multi_id = isset($submitted_data['multi_id']) ? $submitted_data['multi_id'] : '';
        if (empty($multi_id)) {
            return false;
        }
        $settings = $this->get_settings_values();

        return !empty($settings[$multi_id]['template_id']);
    }

    /**
     * Published yeepdf templates as id => title.
     *
     * @return array
     */
    private function get_templates()
    {
        $posts = get_posts(
            array(
                'post_type'      => 'yeepdf',
                'posts_per_page' => -1,
                'post_status'    => 'publish',
            )
        );
        $list  = array();
        foreach ($posts as $post) {
            $list[$post->ID] = $post->post_title;
        }

        return $list;
    }
}
