<?php

namespace Meliconnect\Meliconnect\Core;

use Meliconnect\Meliconnect\Core\Helpers\Helper;
use Meliconnect\Meliconnect\Core\Helpers\SyncHashHelper;
use Meliconnect\Meliconnect\Core\Services\SyncContextResolver;

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

class SyncDashboard
{


    /**
     * RENDER
     */
    public static function render()
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        include plugin_dir_path(__FILE__) . '/Views/syncdashboard.php';
    }
    /**
     * AJAX: GET ITEMS
     */
    public static function ajaxCleanLogs()
    {
        self::checkSecurity();

        global $wpdb;

        $table = $wpdb->prefix . 'meliconnect_sync_logs';

        $count = $wpdb->get_var("SELECT COUNT(*) FROM {$table}");

        $wpdb->query("TRUNCATE TABLE {$table}");

        wp_send_json_success([
            'deleted' => (int)$count
        ]);
    }

    public static function ajaxGetSyncLogs()
    {
        self::checkSecurity();

        global $wpdb;

        $logs_table = $wpdb->prefix . 'meliconnect_sync_logs';
        $snap_table = $wpdb->prefix . 'meliconnect_settings_snapshots';

        $page  = max(1, intval($_GET['page'] ?? 1));
        $limit = 20;
        $offset = ($page - 1) * $limit;

        $where = "WHERE 1=1";

        if (!empty($_GET['action_filter'])) {
            $where .= $wpdb->prepare(" AND l.action LIKE %s", '%' . $_GET['action_filter'] . '%');
        }

        if (!empty($_GET['status'])) {
            $where .= $wpdb->prepare(" AND l.status = %s", $_GET['status']);
        }

        if (!empty($_GET['listing'])) {
            $where .= $wpdb->prepare(" AND l.meli_item_id LIKE %s", '%' . $_GET['listing'] . '%');
        }

        $total = $wpdb->get_var("SELECT COUNT(*) FROM {$logs_table} l {$where}");

        $rows = $wpdb->get_results("
            SELECT l.*, s.settings
            FROM {$logs_table} l
            LEFT JOIN {$snap_table} s ON s.id = l.settings_snapshot_id
            {$where}
            ORDER BY l.created_at DESC
            LIMIT {$limit} OFFSET {$offset}
        ");

        foreach ($rows as $row) {

            // 🛒 WooCommerce product
            if (!empty($row->woo_product_id)) {
                $row->woo_title = get_the_title($row->woo_product_id);
                $row->woo_edit_link = get_edit_post_link($row->woo_product_id);
                $row->meli_permalink = get_post_meta($row->woo_product_id, 'meliconnect_meli_permalink', true);
            } else {
                $row->woo_title = '';
                $row->woo_edit_link = '';
            }
        }


        wp_send_json([
            'items' => $rows,
            'total' => (int)$total,
            'pages' => ceil($total / $limit),
            'current' => $page
        ]);
    }
    /**
     * AJAX: GET ITEMS
     */
    public static function ajaxGetItems()
    {
        self::checkSecurity();

        global $wpdb;

        $table = $wpdb->prefix . 'meliconnect_sync_state';

        $needs_sync = isset($_GET['needs_sync']) ? (int) $_GET['needs_sync'] : null;

        $page  = max(1, intval($_GET['page'] ?? 1));
        $limit = 20;
        $offset = ($page - 1) * $limit;

        $where = "WHERE 1=1";

        // filtros
        if (!empty($_GET['status'])) {
            $where .= $wpdb->prepare(" AND sync_status = %s", $_GET['status']);
        }

        if (!empty($_GET['type'])) {
            $where .= $wpdb->prepare(" AND sync_type = %s", $_GET['type']);
        }

        if (!empty($_GET['seller'])) {
            $where .= $wpdb->prepare(" AND meli_seller_id LIKE %s", '%' . $_GET['seller'] . '%');
        }

        if (!empty($_GET['listing'])) {
            $where .= $wpdb->prepare(" AND meli_item_id LIKE %s", '%' . $_GET['listing'] . '%');
        }

        if ($needs_sync !== null) {
            $where .= $wpdb->prepare(" AND needs_sync = %d", $_GET['needs_sync']);
        }

        // total
        $total = $wpdb->get_var("SELECT COUNT(*) FROM {$table} {$where}");

        // data
        $items = $wpdb->get_results("
            SELECT *
            FROM {$table}
            {$where}
            ORDER BY updated_at DESC
            LIMIT {$limit} OFFSET {$offset}
        ");

        foreach ($items as $item) {
            if (!empty($item->woo_product_id)) {
                $item->edit_link = get_edit_post_link($item->woo_product_id);
                $item->title = get_the_title($item->woo_product_id); // opcional
                $item->meli_permalink = get_post_meta($item->woo_product_id, 'meliconnect_meli_permalink', true);
            } else {
                $item->edit_link = '';
                $item->title = '';
                $item->meli_permalink = '';
            }
        }

        wp_send_json([
            'items' => $items,
            'total' => (int)$total,
            'pages' => ceil($total / $limit),
            'current' => $page
        ]);
    }

    /**
     * AJAX: UPDATE ITEM
     */
    public static function ajaxUpdateItem()
    {
        self::checkSecurity();

        global $wpdb;

        $table = $wpdb->prefix . 'meliconnect_sync_state';

        $id     = (int) ($_POST['id'] ?? 0);
        $action = sanitize_text_field($_POST['action_type'] ?? '');

        if (!$id) {
            wp_send_json_error('Invalid ID');
        }

        if ($action === 'retry') {

            $wpdb->update($table, [
                'sync_status' => 'pending',
                'needs_sync'  => 1,
                'retry_count' => 0,
                'locked_at'   => null
            ], ['id' => $id]);
        } elseif ($action === 'unlock') {

            $wpdb->update($table, [
                'locked_at'   => null,
                'sync_status' => 'pending'
            ], ['id' => $id]);
        }

        wp_send_json_success();
    }

    public static function ajaxSeedSyncTable($request)
    {
        $limit  = isset($_POST['limit']) ? (int) $_POST['limit'] : 50;
        $offset = isset($_POST['offset']) ? (int) $_POST['offset'] : 0;

        self::checkSecurity();

        $result = self::seedMissingItems($limit, $offset);

        wp_send_json_success($result);
    }

    /**
     * SEEDER 
     */
    public static function seedMissingItems($limit = 50, $offset = 0)
    {
        global $wpdb;

        $table = $wpdb->prefix . 'meliconnect_sync_state';
        $transient_key = 'meliconnect_seed_total';
        $log_channel = 'meliconnect-sync-seeder';



        Helper::logData(
            "Seeder start | offset={$offset} limit={$limit}",
            $log_channel
        );

        // ===============================
        // TOTAL
        // ===============================
        $total = get_transient($transient_key);

        if ($total === false) {

            $total = (int) $wpdb->get_var("
            SELECT COUNT(p.ID)
            FROM {$wpdb->posts} p
            INNER JOIN {$wpdb->postmeta} pm
                ON p.ID = pm.post_id
            WHERE p.post_type IN ('product','product_variation')
            AND p.post_status = 'publish'
            AND pm.meta_key = 'meliconnect_meli_listing_id'
        ");

            set_transient(
                $transient_key,
                $total,
                10 * MINUTE_IN_SECONDS
            );
        }

        // ===============================
        // CLEANUP
        // ===============================
        if ($offset === 0) {

            $deleted = $wpdb->query("
            DELETE s
            FROM {$table} s
            LEFT JOIN {$wpdb->posts} p
                ON p.ID = s.woo_product_id
            WHERE p.ID IS NULL
        ");

            Helper::logData(
                "Cleanup removed {$deleted} orphan records",
                $log_channel
            );
        }

        // ===============================
        // POSTS
        // ===============================
        $posts = get_posts([
            'post_type'      => ['product', 'product_variation'],
            'posts_per_page' => $limit,
            'offset'         => $offset,
            'post_status'    => ['publish'],
            'meta_query'     => [
                [
                    'key'     => 'meliconnect_meli_listing_id',
                    'compare' => 'EXISTS'
                ]
            ]
        ]);

        if (empty($posts)) {

            delete_transient($transient_key);

            return [
                'processed'       => 0,
                'processed_total' => min($offset, $total),
                'total'           => $total,
                'progress'        => 100,
                'has_more'        => false
            ];
        }

        // ===============================
        // LOOP
        // ===============================
        foreach ($posts as $post) {

            $product_id = $post->ID;

            $woo = wc_get_product($product_id);

            if (!$woo) {

                Helper::logData(
                    "Skip {$product_id} - invalid Woo product",
                    $log_channel
                );

                continue;
            }

            // ===============================
            // VARIATION
            // ===============================
            $woo_product_id = $product_id;
            $woo_variation_id = null;

            if ($post->post_type === 'product_variation') {

                if (
                    !$post->post_parent ||
                    !wc_get_product($post->post_parent)
                ) {

                    Helper::logData(
                        "Skip variation {$product_id} - orphan",
                        $log_channel
                    );

                    continue;
                }

                $woo_product_id = $post->post_parent;
                $woo_variation_id = $product_id;
            }

            // ===============================
            // META
            // ===============================
            $meli_id = get_post_meta(
                $product_id,
                'meliconnect_meli_listing_id',
                true
            );

            $seller_id = get_post_meta(
                $product_id,
                'meliconnect_meli_seller_id',
                true
            );

            if (empty($meli_id) || empty($seller_id)) {

                Helper::logData(
                    "Skip {$product_id} - missing meli meta",
                    $log_channel
                );

                continue;
            }

            // ===============================
            // EXISTING ROW
            // ===============================
            $row = $wpdb->get_row($wpdb->prepare(
                "
                SELECT *
                FROM {$table}
                WHERE woo_product_id = %d
                AND (
                    woo_variation_id = %d
                    OR (%d = 0 AND woo_variation_id IS NULL)
                )
                LIMIT 1
                ",
                $woo_product_id,
                (int) $woo_variation_id,
                (int) $woo_variation_id
            ));

            // ===============================
            // BUILD CONTEXT
            // ===============================

            $context = SyncContextResolver::buildSeedContext($woo_product_id, $meli_id, $seller_id);

            if (!$context) {

                Helper::logData(
                    "Skip {$meli_id} - context failed",
                    $log_channel
                );

                continue;
            }

            $meli = $context['meli'];
            $meli_hash = SyncHashHelper::buildHashFromMeli($meli, 'full');

            // ===============================
            // REMOVE DEAD ITEMS
            // ===============================
            if (in_array($meli['status'], ['closed', 'deleted'])) {

                if ($row) {

                    Helper::logData(
                        "Deleting {$meli_id} - dead status {$meli['status']}",
                        $log_channel
                    );

                    $wpdb->delete($table, ['id' => $row->id]);
                }

                continue;
            }

            // ===============================
            // INSERT
            // ===============================
            if (!$row) {

                Helper::logData(
                    "Insert new sync state {$meli_id}",
                    $log_channel
                );

                $wpdb->insert($table, [
                    'woo_product_id'     => $woo_product_id,
                    'woo_variation_id'   => $woo_variation_id,

                    'meli_item_id'       => $meli_id,
                    'meli_seller_id'     => $seller_id,

                    'last_hash'          => $meli_hash,

                    'last_synced_price'  => $meli['price'],
                    'last_synced_stock'  => $meli['available_quantity'],
                    'last_synced_status' => $meli['status'],

                    'sync_status'        => 'synced',
                    'needs_sync'         => 0,

                    'created_at'         => current_time('mysql'),
                    'updated_at'         => current_time('mysql'),
                ]);

                continue;
            }

            // ===============================
            // HASH DIFF
            // ===============================
            if ($row->last_hash !== $meli_hash) {

                Helper::logData(
                    "Diff detected {$meli_id} → enqueue sync",
                    $log_channel
                );

                $wpdb->update($table, [
                    'needs_sync'  => 1,
                    'sync_status' => 'pending',
                    'updated_at'  => current_time('mysql')
                ], ['id' => $row->id]);

                continue;
            }

            // ===============================
            // UPDATE META
            // ===============================
            $wpdb->update($table, [
                'meli_seller_id' => $seller_id,
                'updated_at'     => current_time('mysql')
            ], ['id' => $row->id]);
        }

        // ===============================
        // PROGRESS
        // ===============================
        $processed_now   = count($posts);

        $processed_total = min(
            $offset + $processed_now,
            $total
        );

        $progress = $total > 0
            ? round(($processed_total / $total) * 100, 2)
            : 100;

        $has_more = ($offset + $processed_now) < $total;

        if (!$has_more) {

            delete_transient($transient_key);

            Helper::logData(
                "Seeder finished",
                $log_channel
            );
        }

        return [
            'processed'       => $processed_now,
            'processed_total' => $processed_total,
            'total'           => $total,
            'progress'        => $progress,
            'has_more'        => $has_more
        ];
    }

    /**
     * SECURITY
     */
    private static function checkSecurity()
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized');
        }

        check_ajax_referer('meliconnect_sync_nonce', 'nonce');
    }
}
