<?php
/**
 * LegacyAdminHelpers
 *
 * Trimmed-down helper set used by the Tools page in the free plugin.
 * Only includes the cleanup, slug-regeneration, and duplicate-scan helpers —
 * the wider Pro variant covers profile-screen extras and product-list filters.
 */

namespace Pixeldev\SquareWooSync\Admin\Helpers;

defined('ABSPATH') || exit;

class LegacyAdminHelpers
{
    /**
     * Delete every user's square_customer_id meta.
     */
    public function remove_customer_meta(): void
    {
        foreach (get_users(['fields' => 'ID']) as $user_id) {
            update_user_meta((int) $user_id, 'square_customer_id', '');
        }
    }

    /**
     * Delete square_* product meta keys.
     */
    public function remove_product_meta(): void
    {
        global $wpdb;

        $keys  = ['square_product_id', 'square_variation_id', 'square_locations'];
        $in    = "'" . implode("','", array_map('esc_sql', $keys)) . "'";
        $table = $wpdb->postmeta;

        // phpcs:ignore WordPress.DB.PreparedSQL
        $wpdb->query(
            "DELETE pm FROM $table pm
             JOIN {$wpdb->posts} p ON p.ID = pm.post_id
             WHERE p.post_type = 'product'
               AND pm.meta_key IN ($in)"
        );
    }

    /**
     * Find every Square product id that's linked to more than one Woo product
     * (or variation). Variations and parent products that share the same id
     * are reported separately so the UI can display them clearly.
     *
     * @return array<int, array{square_id:string, products:array<int, array{id:int,title:string,type:string,parent:int}>}>
     */
    public function scan_duplicate_square_links(): array
    {
        global $wpdb;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL
        $rows = $wpdb->get_results(
            "SELECT
                pm.meta_value AS square_id,
                GROUP_CONCAT(p.ID ORDER BY p.ID) AS post_ids,
                GROUP_CONCAT(p.post_title ORDER BY p.ID SEPARATOR '||') AS post_titles,
                GROUP_CONCAT(p.post_type ORDER BY p.ID) AS post_types,
                GROUP_CONCAT(p.post_parent ORDER BY p.ID) AS post_parents,
                COUNT(*) AS dup_count
            FROM {$wpdb->postmeta} pm
            INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
            WHERE pm.meta_key = 'square_product_id'
              AND pm.meta_value != ''
              AND p.post_status != 'trash'
              AND p.post_type = 'product'
            GROUP BY pm.meta_value
            HAVING dup_count > 1
            ORDER BY dup_count DESC, square_id ASC
            LIMIT 100"
        );

        if (empty($rows)) {
            return [];
        }

        $groups = [];

        foreach ($rows as $row) {
            $ids      = explode(',', $row->post_ids);
            $titles   = explode('||', $row->post_titles);
            $types    = explode(',', $row->post_types);
            $parents  = explode(',', $row->post_parents);
            $products = [];

            foreach ($ids as $i => $id) {
                $products[] = [
                    'id'     => (int) $id,
                    'title'  => $titles[$i] ?? '',
                    'type'   => $types[$i] ?? '',
                    'parent' => (int) ($parents[$i] ?? 0),
                ];
            }

            $groups[] = [
                'square_id' => $row->square_id,
                'products'  => $products,
            ];
        }

        return $groups;
    }

    /**
     * Regenerate slugs for products that still have default slugs like
     * "product" or "product-123".
     */
    public function regenerate_product_slugs(): int
    {
        $args = [
            'post_type'      => 'product',
            'post_status'    => ['publish', 'draft', 'pending', 'private', 'future'],
            'posts_per_page' => -1,
            'fields'         => 'ids',
            'no_found_rows'  => true,
        ];

        $ids     = get_posts($args);
        $updated = 0;

        foreach ($ids as $post_id) {
            $post = get_post((int) $post_id);
            if (!$post) {
                continue;
            }

            $slug = (string) $post->post_name;
            if ($slug === '' || $slug === 'product' || preg_match('/^product(?:-\\d+)+$/', $slug)) {
                $title = get_the_title((int) $post_id);
                $title = is_string($title) ? trim($title) : '';
                if ($title === '') {
                    continue;
                }

                $desired = sanitize_title($title);
                $unique  = wp_unique_post_slug($desired, (int) $post_id, $post->post_status, $post->post_type, (int) $post->post_parent);
                $result  = wp_update_post([
                    'ID'        => (int) $post_id,
                    'post_name' => $unique,
                ], true);

                if (!is_wp_error($result)) {
                    $updated++;
                }
            }
        }

        return $updated;
    }
}
