<?php
if (!defined('ABSPATH')) {
    exit;
}
// includes/sync.php

function wordchat_render_sync_page() {
    if (!current_user_can('manage_options')) {
        wp_die(__('You do not have sufficient permissions to access this page.', 'wordchat-pro'));
    }

    $site_id = get_option('wordchat_site_id');
    $api_key = get_option('wordchat_api_key');

    if (!$site_id || !$api_key) {
        echo "<div class='notice notice-error'><p>" . esc_html__('Please register Word.Chat before syncing content.', 'wordchat-pro') . "</p></div>";
        return;
    }

    // Get all public post types
    $post_types = get_post_types(['public' => true], 'objects');
    unset($post_types['attachment']);
    $post_type_slugs = array_keys($post_types);

    $posts = get_posts([
        'post_type' => $post_type_slugs,
        'post_status' => 'publish',
        'numberposts' => -1,
        'orderby' => 'type',
        'order' => 'ASC',
    ]);

    // Get all categories for the filter
    $all_categories = get_categories(['hide_empty' => true]);

    $synced_ids = [];
    foreach ($posts as $post) {
        if (get_post_meta($post->ID, 'wordchat_synced', true)) {
            $synced_ids[] = $post->ID;
        }
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Verify nonce
        if (!isset($_POST['wordchat_sync_nonce']) || !wp_verify_nonce($_POST['wordchat_sync_nonce'], 'wordchat_sync_action')) {
            wp_die(__('Security check failed. Please try again.', 'wordchat-pro'));
        }

        $selected_ids = isset($_POST['wordchat_sync']) ? array_map('absint', $_POST['wordchat_sync']) : [];
        $unsynced_ids = array_diff($synced_ids, $selected_ids);

        // Sync selected
        foreach ($selected_ids as $post_id) {
            $post = get_post($post_id);
            if (!$post) continue;

            $url = get_permalink($post);
            $categories = get_the_category($post_id);
            $category = $categories && !empty($categories) ? $categories[0]->name : null;

            $payload = [
                'site_id' => $site_id,
                'api_key' => $api_key,
                'domain' => get_site_url(),
                'chunks' => [[
                    'text' => strip_tags($post->post_title . ". " . $post->post_content),
                    'url' => $url,
                    'category' => $category
                ]]
            ];

            $response = wp_remote_post(WORDCHAT_API_URL . '/ingest', [
                'headers' => ['Content-Type' => 'application/json'],
                'body' => json_encode($payload)
            ]);

            if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
                update_post_meta($post_id, 'wordchat_synced', true);
                update_post_meta($post_id, 'wordchat_synced_at', current_time('mysql'));
            }
        }

        // Unsync deselected
        foreach ($unsynced_ids as $post_id) {
            $post = get_post($post_id);
            if (!$post) continue;

            $url = get_permalink($post);

            $payload = [
                'site_id' => $site_id,
                'api_key' => $api_key,
                'url' => $url
            ];

            $response = wp_remote_post(WORDCHAT_API_URL . '/unsync', [
                'headers' => ['Content-Type' => 'application/json'],
                'body' => json_encode($payload)
            ]);

            if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
                delete_post_meta($post_id, 'wordchat_synced');
                delete_post_meta($post_id, 'wordchat_synced_at');
            }
        }

        // Refresh synced_ids after save
        $synced_ids = [];
        foreach ($posts as $post) {
            if (get_post_meta($post->ID, 'wordchat_synced', true)) {
                $synced_ids[] = $post->ID;
            }
        }

        echo "<div class='notice notice-success is-dismissible'><p>" . esc_html__('Sync updated successfully.', 'wordchat-pro') . "</p></div>";
    }
    ?>
    <div class="wrap">
        <h1><?php echo esc_html__('Sync WordPress Content to Word.Chat', 'wordchat-pro'); ?></h1>
        <p style="margin-bottom: 16px; color: #6B7280;">
            <?php echo esc_html__('Select the content you want your AI chatbot to learn from. Pro plan: unlimited content.', 'wordchat-pro'); ?>
        </p>

        <form method="post">
            <?php wp_nonce_field('wordchat_sync_action', 'wordchat_sync_nonce'); ?>

            <div style="margin-bottom: 16px; display: flex; align-items: center; gap: 12px; flex-wrap: wrap;">
                <button type="button" class="button" onclick="wordchatSyncSelectAll()"><?php echo esc_html__('Select All', 'wordchat-pro'); ?></button>
                <button type="button" class="button" onclick="wordchatSyncDeselectAll()"><?php echo esc_html__('Deselect All', 'wordchat-pro'); ?></button>

                <select id="wordchat-filter-type" onchange="wordchatSyncFilter()" style="min-width: 140px;">
                    <option value="all"><?php echo esc_html__('All Types', 'wordchat-pro'); ?></option>
                    <?php foreach ($post_types as $pt_slug => $pt_obj): ?>
                        <option value="<?php echo esc_attr($pt_slug); ?>"><?php echo esc_html($pt_obj->labels->name); ?></option>
                    <?php endforeach; ?>
                </select>

                <select id="wordchat-filter-category" onchange="wordchatSyncFilter()" style="min-width: 160px;">
                    <option value="all"><?php echo esc_html__('All Categories', 'wordchat-pro'); ?></option>
                    <?php foreach ($all_categories as $cat): ?>
                        <option value="<?php echo esc_attr($cat->slug); ?>"><?php echo esc_html($cat->name); ?> (<?php echo absint($cat->count); ?>)</option>
                    <?php endforeach; ?>
                </select>

                <span style="color: #6B7280; font-size: 13px;">
                    <span id="wordchat-sync-selected">0</span> <?php echo esc_html__('items selected', 'wordchat-pro'); ?>
                    <span id="wordchat-sync-filter-info" style="display: none; margin-left: 8px; color: #9CA3AF;">
                        — <?php echo esc_html__('showing', 'wordchat-pro'); ?> <span id="wordchat-sync-visible">0</span> <?php echo esc_html__('of', 'wordchat-pro'); ?> <?php echo count($posts); ?>
                    </span>
                </span>
            </div>

            <table class="widefat striped" id="wordchat-sync-table">
                <thead><tr>
                    <th style="width: 30px;"></th>
                    <th><?php echo esc_html__('Title', 'wordchat-pro'); ?></th>
                    <th><?php echo esc_html__('Type', 'wordchat-pro'); ?></th>
                    <th><?php echo esc_html__('Category', 'wordchat-pro'); ?></th>
                    <th><?php echo esc_html__('Published', 'wordchat-pro'); ?></th>
                    <th><?php echo esc_html__('Modified', 'wordchat-pro'); ?></th>
                    <th><?php echo esc_html__('Status', 'wordchat-pro'); ?></th>
                    <th><?php echo esc_html__('Last Synced', 'wordchat-pro'); ?></th>
                </tr></thead>
                <tbody>
                <?php foreach ($posts as $post):
                    $is_synced = get_post_meta($post->ID, 'wordchat_synced', true);
                    $synced_at = get_post_meta($post->ID, 'wordchat_synced_at', true);
                    $published = get_the_date('Y-m-d H:i', $post);
                    $modified = get_the_modified_date('Y-m-d H:i', $post);
                    $needs_resync = $synced_at && strtotime($modified) > strtotime($synced_at);

                    $post_cats = get_the_category($post->ID);
                    $cat_slugs = [];
                    $cat_names = [];
                    if ($post_cats && !empty($post_cats)) {
                        foreach ($post_cats as $pc) {
                            $cat_slugs[] = $pc->slug;
                            $cat_names[] = $pc->name;
                        }
                    }

                    if ($is_synced) {
                        $status = $needs_resync
                            ? '<span style="color: #D97706;">&#x26A0;&#xFE0F; ' . esc_html__('Needs Resync', 'wordchat-pro') . '</span>'
                            : '<span style="color: #059669;">&#x2705; ' . esc_html__('Synced', 'wordchat-pro') . '</span>';
                    } else {
                        $status = '<span style="color: #6B7280;">&#x2B1C; ' . esc_html__('Not Synced', 'wordchat-pro') . '</span>';
                    }
                ?>
                    <tr class="wordchat-sync-row"
                        data-post-type="<?php echo esc_attr($post->post_type); ?>"
                        data-categories="<?php echo esc_attr(implode(',', $cat_slugs)); ?>">
                        <td><input type="checkbox" class="wordchat-sync-cb" name="wordchat_sync[]"
                                   value="<?php echo esc_attr($post->ID); ?>"<?php echo $is_synced ? ' checked' : ''; ?>
                                   onchange="wordchatSyncUpdateCount()"></td>
                        <td><strong><?php echo esc_html($post->post_title); ?></strong></td>
                        <td><span style="text-transform: capitalize; color: #6B7280;"><?php echo esc_html($post->post_type); ?></span></td>
                        <td style="color: #6B7280; font-size: 13px;"><?php echo !empty($cat_names) ? esc_html(implode(', ', $cat_names)) : '—'; ?></td>
                        <td style="color: #6B7280; font-size: 13px;"><?php echo esc_html($published); ?></td>
                        <td style="color: #6B7280; font-size: 13px;"><?php echo esc_html($modified); ?></td>
                        <td><?php echo $status; ?></td>
                        <td style="color: #6B7280; font-size: 13px;"><?php echo $synced_at ? esc_html($synced_at) : '—'; ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>

            <p style="margin-top: 16px;">
                <input type="submit" class="button button-primary" value="<?php echo esc_attr__('Sync Selected', 'wordchat-pro'); ?>">
                <span style="margin-left: 12px; color: #6B7280; font-size: 13px;">
                    <?php printf(
                        esc_html__('Currently %d of %d items synced', 'wordchat-pro'),
                        count($synced_ids),
                        count($posts)
                    ); ?>
                </span>
            </p>
        </form>
    </div>

    <script>
    function wordchatSyncFilter() {
        var typeFilter = document.getElementById('wordchat-filter-type').value;
        var catFilter = document.getElementById('wordchat-filter-category').value;
        var rows = document.querySelectorAll('.wordchat-sync-row');
        var visibleCount = 0;

        rows.forEach(function(row) {
            var rowType = row.getAttribute('data-post-type');
            var rowCats = row.getAttribute('data-categories') || '';
            var show = true;

            if (typeFilter !== 'all' && rowType !== typeFilter) {
                show = false;
            }
            if (catFilter !== 'all') {
                var catList = rowCats.split(',').filter(Boolean);
                if (catList.indexOf(catFilter) === -1) {
                    show = false;
                }
            }

            row.style.display = show ? '' : 'none';
            if (show) visibleCount++;
        });

        var filterInfo = document.getElementById('wordchat-sync-filter-info');
        var visibleEl = document.getElementById('wordchat-sync-visible');
        if (typeFilter === 'all' && catFilter === 'all') {
            filterInfo.style.display = 'none';
        } else {
            filterInfo.style.display = 'inline';
            visibleEl.textContent = visibleCount;
        }

        wordchatSyncUpdateCount();
    }

    function wordchatSyncSelectAll() {
        document.querySelectorAll('.wordchat-sync-row').forEach(function(row) {
            if (row.style.display !== 'none') {
                row.querySelector('.wordchat-sync-cb').checked = true;
            }
        });
        wordchatSyncUpdateCount();
    }

    function wordchatSyncDeselectAll() {
        document.querySelectorAll('.wordchat-sync-row').forEach(function(row) {
            if (row.style.display !== 'none') {
                row.querySelector('.wordchat-sync-cb').checked = false;
            }
        });
        wordchatSyncUpdateCount();
    }

    function wordchatSyncUpdateCount() {
        var count = document.querySelectorAll('.wordchat-sync-cb:checked').length;
        document.getElementById('wordchat-sync-selected').textContent = count;
    }

    // Initialize count on load
    document.addEventListener('DOMContentLoaded', function() {
        wordchatSyncUpdateCount();
    });
    </script>
    <?php
}

// Add to admin menu
function wordchat_add_sync_page() {
    add_submenu_page(
        'wordchat-pro',
        __('Content Sync', 'wordchat-pro'),
        __('Content Sync', 'wordchat-pro'),
        'manage_options',
        'wordchat-sync',
        'wordchat_render_sync_page'
    );
}
add_action('admin_menu', 'wordchat_add_sync_page');
