<?php
/**
 * Plugin Name: Sincotechs Custom Forms
 * Description: Custom drag & drop form builder with file upload, conditional logic, confirmation message/redirect and autoresponder email. Protected by Sincotechs license server.
 * Version: 1.0.0
 * Author: Sincotechs
 * Requires PHP: 7.4
 */

if (!defined('ABSPATH')) {
    exit;
}

// Adjust this to your real domain if different
if (!defined('SINCOTECHS_LICENSE_SERVER_URL')) {
    define('SINCOTECHS_LICENSE_SERVER_URL', 'https://sincotechs.com/wp-json/sincotechs-license/v1/verify');
}
if (!defined('SINCOTECHS_PLUGIN_SLUG')) {
    define('SINCOTECHS_PLUGIN_SLUG', 'sincotechs-custom-forms');
}

class Sincotechs_Custom_Forms {

    public function __construct() {
        // License
        add_action('admin_menu', [$this, 'add_admin_menus']);
        add_action('admin_init', [$this, 'register_license_setting']);
        add_action('admin_notices', [$this, 'maybe_show_license_notice']);

        // Post types
        add_action('init', [$this, 'register_post_types']);

        // Form builder
        add_action('add_meta_boxes', [$this, 'add_form_builder_metabox']);
        add_action('save_post', [$this, 'save_form_builder_meta']);

        // Assets
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
        add_action('wp_enqueue_scripts', [$this, 'enqueue_front_assets']);

        // Shortcode & submission
        add_shortcode('custom_form', [$this, 'render_form_shortcode']);
        add_action('init', [$this, 'handle_form_submission']);

        // List table column + copy shortcode
        add_filter('manage_cwf_form_posts_columns', [$this, 'add_shortcode_column']);
        add_action('manage_cwf_form_posts_custom_column', [$this, 'render_shortcode_column'], 10, 2);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_list_copy_script']);
    }

    /**
     * License validation with caching
     */
    public static function is_license_valid($force = false) {
        $license_key = get_option('sincotechs_license_key', '');
        if (empty($license_key)) {
            return false;
        }

        $last_check = get_option('sincotechs_license_last_check', 0);
        $last_valid = get_option('sincotechs_license_last_valid', 0);

        if (!$force && (time() - $last_check) < 12 * HOUR_IN_SECONDS) {
            return (bool) $last_valid;
        }

        $body = [
            'license_key' => $license_key,
            'site_url'    => home_url(),
            'plugin_slug' => SINCOTECHS_PLUGIN_SLUG,
        ];

        $response = wp_remote_post(SINCOTECHS_LICENSE_SERVER_URL, [
            'timeout' => 10,
            'body'    => $body,
        ]);

        $valid = false;

        if (!is_wp_error($response)) {
            $code = wp_remote_retrieve_response_code($response);
            $data = json_decode(wp_remote_retrieve_body($response), true);
            if ($code === 200 && is_array($data) && !empty($data['valid'])) {
                $valid = true;
            }
        } else {
            // Server unreachable: fall back to previous status
            return (bool) $last_valid;
        }

        update_option('sincotechs_license_last_check', time());
        update_option('sincotechs_license_last_valid', $valid ? 1 : 0);

        return $valid;
    }

    /**
     * Admin menus
     */
    public function add_admin_menus() {
        add_menu_page(
            'Sincotechs Forms',
            'Sincotechs Forms',
            'manage_options',
            'sincotechs_forms_main',
            [$this, 'render_main_page'],
            'dashicons-feedback',
            26
        );

        add_submenu_page(
            'sincotechs_forms_main',
            'Forms',
            'Forms',
            'manage_options',
            'edit.php?post_type=cwf_form'
        );

        add_submenu_page(
            'sincotechs_forms_main',
            'Entries',
            'Entries',
            'manage_options',
            'edit.php?post_type=cwf_entry'
        );

        add_submenu_page(
            'sincotechs_forms_main',
            'License',
            'License',
            'manage_options',
            'sincotechs_forms_license',
            [$this, 'render_license_page']
        );
    }

    public function render_main_page() {
        ?>
        <div class="wrap">
            <h1>Sincotechs Custom Forms</h1>
            <p>Use the <strong>Forms</strong> menu item to create and manage your forms.</p>
            <p>Make sure your license key is valid, otherwise the plugin will be disabled.</p>
        </div>
        <?php
    }

    public function register_license_setting() {
        register_setting('sincotechs_license_group', 'sincotechs_license_key');
    }

    public function render_license_page() {
        if (!current_user_can('manage_options')) {
            return;
        }

        if (isset($_POST['sincotechs_force_check']) && check_admin_referer('sincotechs_force_check_action', 'sincotechs_force_check_nonce')) {
            self::is_license_valid(true);
        }

        $key       = get_option('sincotechs_license_key', '');
        $valid     = self::is_license_valid();
        $last_check = get_option('sincotechs_license_last_check', 0);
        ?>
        <div class="wrap">
            <h1>License Settings</h1>
            <p>Enter your license key issued by Sincotechs.</p>

            <form method="post" action="options.php">
                <?php settings_fields('sincotechs_license_group'); ?>
                <?php do_settings_sections('sincotechs_license_group'); ?>

                <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row"><label for="sincotechs_license_key">License key</label></th>
                        <td>
                            <input type="text" id="sincotechs_license_key" name="sincotechs_license_key" value="<?php echo esc_attr($key); ?>" style="width: 320px;">
                            <?php if ($valid): ?>
                                <p style="color: green; font-weight: bold; margin-top: 5px;">License status: VALID ✅</p>
                            <?php else: ?>
                                <p style="color: red; font-weight: bold; margin-top: 5px;">License status: INVALID ❌</p>
                            <?php endif; ?>
                            <?php if (!empty($last_check)): ?>
                                <p><small>Last checked: <?php echo esc_html(date('Y-m-d H:i:s', $last_check)); ?></small></p>
                            <?php endif; ?>
                        </td>
                    </tr>
                </table>

                <?php submit_button('Save License Key'); ?>
            </form>

            <form method="post" style="margin-top: 10px;">
                <?php wp_nonce_field('sincotechs_force_check_action', 'sincotechs_force_check_nonce'); ?>
                <input type="hidden" name="sincotechs_force_check" value="1">
                <?php submit_button('Force license check now', 'secondary'); ?>
            </form>

            <hr>

            <h2>How to use</h2>
            <ol>
                <li>Install <strong>Sincotechs License Server</strong> on your main site.</li>
                <li>Create a new License, the <strong>Title</strong> is your license key.</li>
                <li>Give that key to your client.</li>
                <li>The client enters the key here and saves.</li>
            </ol>
        </div>
        <?php
    }

    /**
     * Admin notice when license invalid
     */
    public function maybe_show_license_notice() {
        if (!current_user_can('manage_options')) {
            return;
        }

        $screen = get_current_screen();
        if (!$screen) {
            return;
        }

        if ($screen->id === 'settings_page_sincotechs_forms_license') {
            return;
        }

        if ($screen->post_type !== 'cwf_form' && $screen->post_type !== 'cwf_entry' && strpos($screen->id, 'sincotechs_forms') === false) {
            return;
        }

        if (!self::is_license_valid()) {
            ?>
            <div class="notice notice-error">
                <p><strong>Sincotechs Custom Forms:</strong> license key is invalid or missing. Go to <a href="<?php echo esc_url(admin_url('admin.php?page=sincotechs_forms_license')); ?>">License Settings</a> to enter a valid key.</p>
            </div>
            <?php
        }
    }

    /**
     * Register form & entry post types
     */
    public function register_post_types() {
        register_post_type('cwf_form', [
            'labels' => [
                'name'          => 'Forms',
                'singular_name' => 'Form',
                'add_new'       => 'Add New Form',
                'add_new_item'  => 'Create New Form',
                'edit_item'     => 'Edit Form',
                'menu_name'     => 'Forms',
            ],
            'public'      => false,
            'show_ui'     => true,
            'show_in_menu'=> 'sincotechs_forms_main',
            'supports'    => ['title'],
        ]);

        register_post_type('cwf_entry', [
            'labels' => [
                'name'          => 'Form Entries',
                'singular_name' => 'Entry',
                'menu_name'     => 'Entries',
            ],
            'public'      => false,
            'show_ui'     => true,
            'show_in_menu'=> 'sincotechs_forms_main',
            'supports'    => ['title'],
        ]);
    }

    /**
     * Form builder metabox
     */
    public function add_form_builder_metabox() {
        add_meta_box(
            'sincotechs_form_builder',
            'Form Builder & Settings',
            [$this, 'render_form_builder_metabox'],
            'cwf_form',
            'normal',
            'high'
        );
    }

    public function render_form_builder_metabox($post) {
        if (!self::is_license_valid()) {
            echo '<p><strong>License required.</strong> Please enter a valid license key in <a href="' . esc_url(admin_url('admin.php?page=sincotechs_forms_license')) . '">License Settings</a>.</p>';
            return;
        }

        wp_nonce_field('sincotechs_save_form_builder', 'sincotechs_form_builder_nonce');

        $fields_json = get_post_meta($post->ID, '_sincotechs_form_fields', true);
        $fields = !empty($fields_json) ? json_decode($fields_json, true) : [];

        $confirmation_type     = get_post_meta($post->ID, '_sincotechs_confirmation_type', true);
        $confirmation_message  = get_post_meta($post->ID, '_sincotechs_confirmation_message', true);
        $confirmation_redirect = get_post_meta($post->ID, '_sincotechs_confirmation_redirect', true);

        $send_autoresponder        = get_post_meta($post->ID, '_sincotechs_send_autoresponder', true);
        $autoresponder_email_field = get_post_meta($post->ID, '_sincotechs_autoresponder_email_field', true);
        $autoresponder_subject     = get_post_meta($post->ID, '_sincotechs_autoresponder_subject', true);
        $autoresponder_message     = get_post_meta($post->ID, '_sincotechs_autoresponder_message', true);

        ?>
        <div id="sincotechs-form-builder">
            <p>Create your form fields below. Drag &amp; drop to change the order.</p>

            <button type="button" class="button button-primary" id="sincotechs-add-field">
                + Add Field
            </button>

            <ul id="sincotechs-fields-list">
                <?php if (!empty($fields) && is_array($fields)): ?>
                    <?php foreach ($fields as $field): ?>
                        <?php
                        $field_label    = isset($field['label']) ? $field['label'] : '';
                        $field_name     = isset($field['name']) ? $field['name'] : '';
                        $field_type     = isset($field['type']) ? $field['type'] : 'text';
                        $field_required = !empty($field['required']);
                        $field_options  = isset($field['options']) && is_array($field['options']) ? implode(',', $field['options']) : '';
                        $cond_field     = isset($field['cond_field']) ? $field['cond_field'] : '';
                        $cond_value     = isset($field['cond_value']) ? $field['cond_value'] : '';
                        ?>
                        <li class="sincotechs-field-item">
                            <span class="sincotechs-drag-handle">☰</span>
                            <input type="text" class="sincotechs-field-label" placeholder="Label" value="<?php echo esc_attr($field_label); ?>">
                            <input type="text" class="sincotechs-field-name" placeholder="Name (slug)" value="<?php echo esc_attr($field_name); ?>">

                            <select class="sincotechs-field-type">
                                <?php
                                $types = [
                                    'text'     => 'Text',
                                    'email'    => 'Email',
                                    'textarea' => 'Textarea',
                                    'select'   => 'Dropdown',
                                    'file'     => 'File Upload',
                                ];
                                foreach ($types as $type_key => $type_label):
                                    ?>
                                    <option value="<?php echo esc_attr($type_key); ?>" <?php selected($field_type, $type_key); ?>>
                                        <?php echo esc_html($type_label); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>

                            <label class="sincotechs-inline">
                                <input type="checkbox" class="sincotechs-field-required" <?php checked($field_required, 1); ?>>
                                Required
                            </label>

                            <input type="text" class="sincotechs-field-options" placeholder="Options (for dropdown, comma separated)" value="<?php echo esc_attr($field_options); ?>">

                            <div class="sincotechs-conditional-wrapper">
                                <span>Show this field when</span>
                                <input type="text" class="sincotechs-cond-field" placeholder="Field name" value="<?php echo esc_attr($cond_field); ?>">
                                <span>equals</span>
                                <input type="text" class="sincotechs-cond-value" placeholder="Value" value="<?php echo esc_attr($cond_value); ?>">
                            </div>

                            <button type="button" class="button sincotechs-remove-field">Remove</button>
                        </li>
                    <?php endforeach; ?>
                <?php endif; ?>
            </ul>

            <input type="hidden" id="sincotechs-fields-json" name="sincotechs_fields_json" value="<?php echo esc_attr($fields_json); ?>">
        </div>

        <hr>

        <h3>Confirmation Settings</h3>
        <p>Choose what happens after a successful form submission.</p>

        <p>
            <label>
                <input type="radio" name="sincotechs_confirmation_type" value="message" <?php checked($confirmation_type, 'message'); ?>>
                Show confirmation message
            </label><br>
            <label>
                <input type="radio" name="sincotechs_confirmation_type" value="redirect" <?php checked($confirmation_type, 'redirect'); ?>>
                Redirect to URL
            </label>
        </p>

        <p>
            <label for="sincotechs_confirmation_message"><strong>Confirmation message</strong></label><br>
            <textarea name="sincotechs_confirmation_message" id="sincotechs_confirmation_message" rows="3" style="width:100%;"><?php echo esc_textarea($confirmation_message); ?></textarea>
        </p>

        <p>
            <label for="sincotechs_confirmation_redirect"><strong>Redirect URL</strong></label><br>
            <input type="text" name="sincotechs_confirmation_redirect" id="sincotechs_confirmation_redirect" style="width:100%;" value="<?php echo esc_attr($confirmation_redirect); ?>">
        </p>

        <hr>

        <h3>Autoresponder Email (to visitor)</h3>
        <p>Send a confirmation email to the visitor after form submission.</p>

        <p>
            <label>
                <input type="checkbox" name="sincotechs_send_autoresponder" value="1" <?php checked($send_autoresponder, '1'); ?>>
                Enable autoresponder email
            </label>
        </p>

        <p>
            <label for="sincotechs_autoresponder_email_field"><strong>Email field name</strong></label><br>
            <input type="text" name="sincotechs_autoresponder_email_field" id="sincotechs_autoresponder_email_field" style="width:100%;" value="<?php echo esc_attr($autoresponder_email_field); ?>">
            <small>Use the <em>name (slug)</em> of the field that contains the visitor's email address.</small>
        </p>

        <p>
            <label for="sincotechs_autoresponder_subject"><strong>Email subject</strong></label><br>
            <input type="text" name="sincotechs_autoresponder_subject" id="sincotechs_autoresponder_subject" style="width:100%;" value="<?php echo esc_attr($autoresponder_subject); ?>">
        </p>

        <p>
            <label for="sincotechs_autoresponder_message"><strong>Email message</strong></label><br>
            <textarea name="sincotechs_autoresponder_message" id="sincotechs_autoresponder_message" rows="4" style="width:100%;"><?php echo esc_textarea($autoresponder_message); ?></textarea>
        </p>

        <?php
    }

    /**
     * Save form builder & settings
     */
    public function save_form_builder_meta($post_id) {
        if (!self::is_license_valid()) {
            return;
        }

        if (!isset($_POST['sincotechs_form_builder_nonce']) ||
            !wp_verify_nonce($_POST['sincotechs_form_builder_nonce'], 'sincotechs_save_form_builder')) {
            return;
        }

        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        if (isset($_POST['post_type']) && 'cwf_form' === $_POST['post_type']) {
            if (!current_user_can('edit_post', $post_id)) {
                return;
            }
        }

        if (isset($_POST['sincotechs_fields_json'])) {
            $json = wp_unslash($_POST['sincotechs_fields_json']);
            update_post_meta($post_id, '_sincotechs_form_fields', $json);
        }

        $confirmation_type = isset($_POST['sincotechs_confirmation_type']) ? sanitize_text_field(wp_unslash($_POST['sincotechs_confirmation_type'])) : '';
        $confirmation_message = isset($_POST['sincotechs_confirmation_message']) ? wp_kses_post(wp_unslash($_POST['sincotechs_confirmation_message'])) : '';
        $confirmation_redirect = isset($_POST['sincotechs_confirmation_redirect']) ? esc_url_raw(wp_unslash($_POST['sincotechs_confirmation_redirect'])) : '';

        update_post_meta($post_id, '_sincotechs_confirmation_type', $confirmation_type);
        update_post_meta($post_id, '_sincotechs_confirmation_message', $confirmation_message);
        update_post_meta($post_id, '_sincotechs_confirmation_redirect', $confirmation_redirect);

        $send_autoresponder = isset($_POST['sincotechs_send_autoresponder']) ? '1' : '0';
        $autoresponder_email_field = isset($_POST['sincotechs_autoresponder_email_field']) ? sanitize_text_field(wp_unslash($_POST['sincotechs_autoresponder_email_field'])) : '';
        $autoresponder_subject = isset($_POST['sincotechs_autoresponder_subject']) ? sanitize_text_field(wp_unslash($_POST['sincotechs_autoresponder_subject'])) : '';
        $autoresponder_message = isset($_POST['sincotechs_autoresponder_message']) ? wp_kses_post(wp_unslash($_POST['sincotechs_autoresponder_message'])) : '';

        update_post_meta($post_id, '_sincotechs_send_autoresponder', $send_autoresponder);
        update_post_meta($post_id, '_sincotechs_autoresponder_email_field', $autoresponder_email_field);
        update_post_meta($post_id, '_sincotechs_autoresponder_subject', $autoresponder_subject);
        update_post_meta($post_id, '_sincotechs_autoresponder_message', $autoresponder_message);
    }

    /**
     * Admin assets (form builder UI)
     */
    public function enqueue_admin_assets($hook) {
        global $post;

        if (!$post || $post->post_type !== 'cwf_form') {
            return;
        }

        if (!self::is_license_valid()) {
            return;
        }

        wp_enqueue_style(
            'sincotechs-form-builder-css',
            plugin_dir_url(__FILE__) . 'admin/form-builder.css',
            [],
            '1.0.0'
        );

        wp_enqueue_script(
            'sincotechs-form-builder-js',
            plugin_dir_url(__FILE__) . 'admin/form-builder.js',
            ['jquery', 'jquery-ui-sortable'],
            '1.0.0',
            true
        );
    }

    /**
     * Frontend assets
     */
    public function enqueue_front_assets() {
        if (!self::is_license_valid()) {
            return;
        }

        wp_enqueue_style(
            'sincotechs-front-css',
            plugin_dir_url(__FILE__) . 'assets/front.css',
            [],
            '1.0.0'
        );

        wp_enqueue_script(
            'sincotechs-front-js',
            plugin_dir_url(__FILE__) . 'assets/front.js',
            ['jquery'],
            '1.0.0',
            true
        );
    }

    /**
     * Shortcode [custom_form id="123"]
     */
    public function render_form_shortcode($atts) {
        if (!self::is_license_valid()) {
            return '<p>Form temporarily unavailable (license invalid).</p>';
        }

        $atts = shortcode_atts([
            'id' => 0,
        ], $atts, 'custom_form');

        $form_id = intval($atts['id']);
        if (!$form_id) {
            return '<p>Form not found.</p>';
        }

        $fields_json = get_post_meta($form_id, '_sincotechs_form_fields', true);
        $fields = !empty($fields_json) ? json_decode($fields_json, true) : [];

        if (empty($fields) || !is_array($fields)) {
            return '<p>This form has no fields yet.</p>';
        }

        $confirmation_message = get_post_meta($form_id, '_sincotechs_confirmation_message', true);
        $success_param = isset($_GET['sincotechs_success']) ? sanitize_text_field(wp_unslash($_GET['sincotechs_success'])) : '';

        $nonce = wp_create_nonce('sincotechs_form_submit_' . $form_id);
        $action_url = esc_url(add_query_arg([]));

        ob_start();

        if ($success_param === '1' && !empty($confirmation_message)) {
            echo '<div class="sincotechs-confirmation-message">' . wp_kses_post(wpautop($confirmation_message)) . '</div>';
        }
        ?>
        <form class="sincotechs-form" method="post" action="<?php echo $action_url; ?>" enctype="multipart/form-data">
            <input type="hidden" name="sincotechs_form_id" value="<?php echo esc_attr($form_id); ?>">
            <input type="hidden" name="sincotechs_form_nonce" value="<?php echo esc_attr($nonce); ?>">

            <?php foreach ($fields as $field): ?>
                <?php
                $label    = isset($field['label']) ? $field['label'] : '';
                $name     = isset($field['name']) ? $field['name'] : '';
                $type     = isset($field['type']) ? $field['type'] : 'text';
                $required = !empty($field['required']);
                $options  = isset($field['options']) ? $field['options'] : [];
                $cond_field = isset($field['cond_field']) ? $field['cond_field'] : '';
                $cond_value = isset($field['cond_value']) ? $field['cond_value'] : '';

                if (!$name) {
                    continue;
                }

                $conditional_attr = '';
                if (!empty($cond_field) && !empty($cond_value)) {
                    $conditional_attr = ' data-cond-field="' . esc_attr($cond_field) . '" data-cond-value="' . esc_attr($cond_value) . '"';
                }
                ?>
                <div class="sincotechs-form-group"<?php echo $conditional_attr; ?>>
                    <label>
                        <?php echo esc_html($label); ?>
                        <?php if ($required): ?>
                            <span class="sincotechs-required">*</span>
                        <?php endif; ?>
                    </label>

                    <?php if ($type === 'textarea'): ?>
                        <textarea name="<?php echo esc_attr($name); ?>" <?php echo $required ? 'required' : ''; ?>></textarea>
                    <?php elseif ($type === 'email'): ?>
                        <input type="email" name="<?php echo esc_attr($name); ?>" <?php echo $required ? 'required' : ''; ?>>
                    <?php elseif ($type === 'select'): ?>
                        <select name="<?php echo esc_attr($name); ?>" <?php echo $required ? 'required' : ''; ?>>
                            <option value="">-- Please choose --</option>
                            <?php if (!empty($options) && is_array($options)): ?>
                                <?php foreach ($options as $opt): ?>
                                    <option value="<?php echo esc_attr($opt); ?>"><?php echo esc_html($opt); ?></option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                    <?php elseif ($type === 'file'): ?>
                        <input type="file" name="<?php echo esc_attr($name); ?>" <?php echo $required ? 'required' : ''; ?>>
                    <?php else: ?>
                        <input type="text" name="<?php echo esc_attr($name); ?>" <?php echo $required ? 'required' : ''; ?>>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>

            <button type="submit" class="sincotechs-submit">Submit</button>
        </form>
        <?php

        return ob_get_clean();
    }

    /**
     * Handle front-end submission
     */
    public function handle_form_submission() {
        if (!self::is_license_valid()) {
            return;
        }

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            return;
        }

        if (empty($_POST['sincotechs_form_id']) || empty($_POST['sincotechs_form_nonce'])) {
            return;
        }

        $form_id = intval($_POST['sincotechs_form_id']);
        $nonce   = sanitize_text_field(wp_unslash($_POST['sincotechs_form_nonce']));

        if (!wp_verify_nonce($nonce, 'sincotechs_form_submit_' . $form_id)) {
            return;
        }

        $fields_json = get_post_meta($form_id, '_sincotechs_form_fields', true);
        $fields = !empty($fields_json) ? json_decode($fields_json, true) : [];

        if (empty($fields) || !is_array($fields)) {
            return;
        }

        $data_for_email = [];
        $data_for_meta  = [];

        foreach ($fields as $field) {
            $name  = isset($field['name']) ? $field['name'] : '';
            $label = isset($field['label']) ? $field['label'] : $name;
            $type  = isset($field['type']) ? $field['type'] : 'text';

            if (!$name) {
                continue;
            }

            if ($type === 'file') {
                if (isset($_FILES[$name]) && !empty($_FILES[$name]['name'])) {
                    $file = $_FILES[$name];

                    require_once ABSPATH . 'wp-admin/includes/file.php';
                    $uploaded = wp_handle_upload($file, ['test_form' => false]);

                    if (!isset($uploaded['error']) && isset($uploaded['url'])) {
                        $file_url = $uploaded['url'];
                        $data_for_email[] = $label . ': ' . $file_url;
                        $data_for_meta[$name] = $file_url;
                    } else {
                        $data_for_email[] = $label . ': (upload failed)';
                        $data_for_meta[$name] = '';
                    }
                } else {
                    $data_for_email[] = $label . ': (no file)';
                    $data_for_meta[$name] = '';
                }
                continue;
            }

            $value = isset($_POST[$name]) ? wp_unslash($_POST[$name]) : '';
            if (is_string($value)) {
                $value = sanitize_text_field($value);
            }

            $data_for_email[] = $label . ': ' . $value;
            $data_for_meta[$name] = $value;
        }

        $entry_id = wp_insert_post([
            'post_type'   => 'cwf_entry',
            'post_status' => 'publish',
            'post_title'  => 'Entry for form #' . $form_id . ' - ' . current_time('mysql'),
        ]);

        if ($entry_id && !is_wp_error($entry_id)) {
            update_post_meta($entry_id, '_sincotechs_entry_data', $data_for_meta);
            update_post_meta($entry_id, '_sincotechs_form_id', $form_id);
        }

        // Admin email
        $admin_email = get_option('admin_email');
        $subject = 'New form entry (Form ID: ' . $form_id . ')';
        $message = "A new form entry has been submitted:\n\n" . implode("\n", $data_for_email);
        wp_mail($admin_email, $subject, $message);

        // Autoresponder
        $send_autoresponder        = get_post_meta($form_id, '_sincotechs_send_autoresponder', true);
        $autoresponder_email_field = get_post_meta($form_id, '_sincotechs_autoresponder_email_field', true);
        $autoresponder_subject     = get_post_meta($form_id, '_sincotechs_autoresponder_subject', true);
        $autoresponder_message     = get_post_meta($form_id, '_sincotechs_autoresponder_message', true);

        if ($send_autoresponder === '1' && !empty($autoresponder_email_field)) {
            $visitor_email = isset($data_for_meta[$autoresponder_email_field]) ? $data_for_meta[$autoresponder_email_field] : '';

            if (!empty($visitor_email) && is_email($visitor_email)) {
                $subject_to_send = !empty($autoresponder_subject) ? $autoresponder_subject : 'Thank you for your submission';
                $message_to_send = !empty($autoresponder_message) ? $autoresponder_message : 'We have received your form submission.';

                wp_mail($visitor_email, $subject_to_send, $message_to_send);
            }
        }

        $confirmation_type     = get_post_meta($form_id, '_sincotechs_confirmation_type', true);
        $confirmation_redirect = get_post_meta($form_id, '_sincotechs_confirmation_redirect', true);

        if ($confirmation_type === 'redirect' && !empty($confirmation_redirect)) {
            wp_safe_redirect($confirmation_redirect);
        } else {
            wp_safe_redirect(add_query_arg('sincotechs_success', '1', remove_query_arg(['sincotechs_success'])));
        }
        exit;
    }

    /**
     * Add Shortcode column
     */
    public function add_shortcode_column($columns) {
        $new = [];
        foreach ($columns as $key => $label) {
            $new[$key] = $label;
            if ($key === 'title') {
                $new['sincotechs_shortcode'] = __('Shortcode', 'sincotechs');
            }
        }
        return $new;
    }

    /**
     * Render Shortcode column with copy button
     */
    public function render_shortcode_column($column, $post_id) {
        if ($column !== 'sincotechs_shortcode') {
            return;
        }

        $shortcode = '[custom_form id="' . $post_id . '"]';
        ?>
        <code><?php echo esc_html($shortcode); ?></code>
        <button type="button"
                class="button button-small sincotechs-copy-shortcode"
                data-shortcode="<?php echo esc_attr($shortcode); ?>">
            <?php esc_html_e('Copy', 'sincotechs'); ?>
        </button>
        <span class="sincotechs-copy-done" style="display:none; margin-left:4px;">
            <?php esc_html_e('Copied!', 'sincotechs'); ?>
        </span>
        <?php
    }

    /**
     * JS for copy button in list table
     */
    public function enqueue_list_copy_script($hook) {
        if ($hook !== 'edit.php') {
            return;
        }

        $screen = get_current_screen();
        if (!$screen || $screen->post_type !== 'cwf_form') {
            return;
        }

        wp_enqueue_script('jquery');

        $inline_js = <<<'JS'
document.addEventListener('click', function(e) {
    var target = e.target;
    if (!target.classList.contains('sincotechs-copy-shortcode')) {
        return;
    }
    var shortcode = target.getAttribute('data-shortcode');
    if (!shortcode) return;

    function showCopied(msgEl) {
        if (!msgEl) return;
        msgEl.style.display = 'inline';
        setTimeout(function() {
            msgEl.style.display = 'none';
        }, 1500);
    }

    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(shortcode).then(function() {
            showCopied(target.nextElementSibling);
        }).catch(function() {
            window.prompt('Copy this shortcode:', shortcode);
        });
    } else {
        window.prompt('Copy this shortcode:', shortcode);
    }
});
JS;

        wp_add_inline_script('jquery', $inline_js);
    }
}

new Sincotechs_Custom_Forms();
