<?php

namespace Convertforce\Core;

class Post
{
    public const POST_TYPE = 'convertforce-popup';
    public const META_KEY = '_convertforce_conversion';

    public static $is_saving = false;

    public static function register()
    {
        register_post_type(
            self::POST_TYPE,
            [
                'labels' => [
                    'name' => __('Campaigns', 'convertforce'),
                    'singular_name' => __('Campaign', 'convertforce'),
                    'menu_name' => __('Campaigns', 'convertforce'),
                    'add_new' => __('Add Campaign', 'convertforce'),
                    'add_new_item' => __('Add Campaign', 'convertforce'),
                ],
                'public' => false,
                'show_ui' => true,
                'show_in_menu' => 'convertforce',
                'supports' => ['title', 'editor', 'custom-fields'],
                'show_in_rest' => true,
                'hierarchical' => false,
                'delete_with_user' => false,
                'capability_type' => 'post',
                'template' => [
                    [
                        'convertforce/conversion',
                        [],
                        [['core/paragraph', ['placeholder' => 'Enter your content here']]]
                    ]
                ],
                'template_lock' => 'all',
            ]
        );


        add_filter('manage_edit-' . self::POST_TYPE . '_columns', [__CLASS__, 'add_columns']);
        add_action('manage_' . self::POST_TYPE . '_posts_custom_column', [__CLASS__, 'populate_columns'], 10, 2);
        add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_admin_assets']);


        add_action('wp_ajax_convertforce_toggle_post_status', [__CLASS__, 'toggle_post_status']);


        add_filter('manage_edit-' . self::POST_TYPE . '_sortable_columns', [__CLASS__, 'make_columns_sortable']);
        add_action('pre_get_posts', [__CLASS__, 'orderby_conversion_meta']);
    }

    public static function add_columns($columns)
    {
        $new_columns = [];

        foreach ($columns as $key => $value) {
            $new_columns[$key] = $value;
            if ($key === 'title') {
                $new_columns['status_toggle'] = __('Status', 'convertforce');
            }
        }

        $new_columns['views'] = __('Views', 'convertforce');
        $new_columns['trigger'] = __('Trigger', 'convertforce');
        $new_columns['display'] = __('Display', 'convertforce');
        $new_columns['author'] = __('Author', 'convertforce');
        $new_columns['campaign_id'] = __('Campaign ID', 'convertforce');


        if (isset($new_columns['date'])) {
            $date_column = ['date' => $new_columns['date']];
            unset($new_columns['date']);
            $new_columns = array_merge($new_columns, $date_column);
        }

        return $new_columns;
    }



    public static function populate_columns($column, $post_id)
    {
        $meta = get_post_meta($post_id, self::META_KEY, true);
        $status = get_post_status($post_id);
        $is_published = $status === 'publish';
        $checked = $is_published ? 'checked' : '';
        $status_label = $is_published ? 'Published' : 'Draft';
        $display_options = $meta['displayOptions'] ?? [];
        $display_conditions = $meta['displayConditions'] ?? [];

        $show_on = '';
        $hide_on = '';
        foreach ($display_conditions as $condition) {
            $entry = '';
            if ($condition['general'] === 'entire-site') {
                $entry = 'Entire Site';
            } else if ($condition['general'] === 'singular') {
                $entry = 'Singular: ' . $condition['singular'];
            } else if ($condition['general'] === 'archive') {
                $entry = 'Archive: ' . $condition['archive'];
            }
            if ($condition['condition'] === 'include') {
                $show_on .= "$entry <br>";
            } else {
                $hide_on .= "$entry <br>";
            }
        }


        switch ($column) {
            case 'status_toggle':
                echo '<label class="switch">
                    <input type="checkbox" class="toggle-status" data-post-id="' . esc_attr($post_id) . '" ' . esc_attr($checked) . '>
                    <span class="slider round"></span>
                  </label>';
                echo '<span class="status-label" style="margin-left: 10px;">' . esc_html($status_label) . '</span>';
                break;

            case 'views':
                echo isset($meta['views']) ? esc_html(number_format($meta['views'] ?? 0)) : 0;
                break;

            case 'trigger':
                $event = $display_options['event'] ?? 'load';
                $trigger_labels = [
                    'load' => __('Page Load', 'convertforce'),
                    'exit_intent' => __('Exit Intent', 'convertforce'),
                    'scroll' => __('Scroll Depth', 'convertforce'),
                    'time_delay' => __('Time on Page', 'convertforce'),
                    'inactivity' => __('User Inactivity', 'convertforce'),
                    'click' => __('Click', 'convertforce'),
                    'end_of_page' => __('End of Page', 'convertforce'),
                    'custom_link' => __('Custom Link', 'convertforce'),
                ];
                echo esc_html($trigger_labels[$event] ?? $event);
                break;

            case 'display':
                if ($show_on) {
                    echo 'Show on:<br>';
                    echo $show_on;
                }
                if ($hide_on) {
                    echo '<br>Hide on:<br>';
                    echo $hide_on;
                }
                break;

            case 'campaign_id':
                echo esc_html($post_id);
                break;
        }
    }


    public static function make_columns_sortable($columns)
    {
        $columns['views'] = 'views';
        return $columns;
    }

    public static function orderby_conversion_meta($query)
    {
        if (!is_admin() || !$query->is_main_query()) {
            return;
        }

        if ($query->get('orderby') === 'views') {
            $query->set('meta_key', self::META_KEY);
            $query->set('orderby', 'meta_value_num');
        }
    }



    public static function enqueue_admin_assets()
    {
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        if (!$screen || $screen->post_type !== self::POST_TYPE) {
            return;
        }

        $nonce = wp_create_nonce('toggle_post_status_nonce');

        add_filter('script_loader_tag', function ($tag, $handle) use ($nonce) {
            if ('convertforce-campaign-list' === $handle) {
                return str_replace(' src', ' data-nonce="' . esc_attr($nonce) . '" src', $tag);
            }
            return $tag;
        }, 10, 2);

        wp_enqueue_script(
            'convertforce-campaign-list',
            CONVERTFORCE_URL . '/build/campaign-list.js',
            [],
            CONVERTFORCE_VERSION,
            true
        );

        wp_enqueue_style(
            'convertforce-admin-list',
            CONVERTFORCE_URL . '/build/campaign-list-style.css',
            [],
            CONVERTFORCE_VERSION
        );
    }

    public static function toggle_post_status()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'toggle_post_status_nonce')) {
            wp_send_json_error(['message' => 'Invalid nonce']);
        }

        $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
        $new_status = isset($_POST['status']) ? sanitize_text_field(wp_unslash($_POST['status'])) : '';

        if (!$post_id || !in_array($new_status, ['publish', 'draft'])) {
            wp_send_json_error(['message' => 'Invalid data']);
        }

        wp_update_post([
            'ID' => $post_id,
            'post_status' => $new_status
        ]);

        wp_send_json_success(['message' => 'Post status updated']);
    }

    public static function save_post($post_id, $post)
    {
        self::$is_saving = !(
            $post->post_type !== self::POST_TYPE
            || (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
            || wp_is_post_autosave($post)
            || wp_is_post_revision($post_id)
            || 'trash' === $post->post_status
            || 'auto-draft' === $post->post_status
        );
    }

}
