<?php

namespace Meliconnect\Meliconnect\Modules\Exporter\Models;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

use Error;
use Meliconnect\Meliconnect\Core\Helpers\Helper;

class ProductToExport {

	private static $table_name;

	public static function init() {
		global $wpdb;

		self::$table_name = $wpdb->prefix . 'meliconnect_products_to_export';
	}

    public static function truncate_table() {
        global $wpdb;
        self::init();

		$table_name = self::$table_name;

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



	public static function count_products_to_export() {
		global $wpdb;

		self::init();

		$table_name = self::$table_name;

        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		return $wpdb->get_var( "SELECT COUNT(*) FROM $table_name" );
	}

    public static function update_vinculated_listing_id( $woo_product_id, $listing_id ) {
        global $wpdb;

        self::init();

        $table_name = self::$table_name;

        return $wpdb->update(
            $table_name,
            array(
                'vinculated_listing_id' => $listing_id,
                'updated_at' => current_time('mysql')
            ),
            array(
                'woo_product_id' => $woo_product_id
            ),
            array('%s', '%s'),
            array('%d')
        );
    }

    public static function mark_as_finished_with_listing_data( $woo_product_id, $listing_id, $permalink, $seller_id ) {

        global $wpdb;

        self::init();

        $table_name = self::$table_name;

        $data = array(
            'export_status' => 'finished',
            'export_error'  => null,
            'updated_at'    => current_time('mysql')
        );

        // SOLO actualiza si hay datos válidos
        if ( ! empty($listing_id) ) {
            $data['vinculated_listing_id'] = $listing_id;
        }

        if ( ! empty($permalink) ) {
            $data['meli_permalink'] = $permalink;
        }

        if ( ! empty($seller_id) ) {
            $data['meli_seller_id'] = (int) $seller_id;
        }

        return $wpdb->update(
            $table_name,
            $data,
            array('woo_product_id' => $woo_product_id),
            null,
            array('%d')
        );
    }

	public static function fill_products_table($products) {

        if (empty($products)) return;

        global $wpdb;

        self::init();

        $table = self::$table_name;

        $placeholders = [];
        $values = [];

        foreach ($products as $p) {

            $placeholders[] = "(%d,%s,%s,%s,%s,%s,%d,%s,%s,%s,%s,%s,%s,%s,%s)";

            array_push(
                $values,
                $p['product_id'],
                $p['product_name'],
                $p['sku'],
                $p['gtin'],
                $p['product_type'],
                $p['status'],
                $p['vinculated_template_id'] ?: null,
                $p['vinculated_listing_id'],
                null,
                null,
                $p['meli_permalink'],
                $p['meli_seller_id'],
                'pending',
                null,
                current_time('mysql')
            );
        }

        $sql = "
        INSERT INTO $table (
            woo_product_id,
            woo_product_name,
            woo_sku,
            woo_gtin,
            woo_product_type,
            woo_status,
            vinculated_template_id,
            vinculated_listing_id,
            listing_match_by,
            template_match_by,
            meli_permalink,
            meli_seller_id,
            export_status,
            export_error,
            updated_at
        ) VALUES " . implode(',', $placeholders) . "

        ON DUPLICATE KEY UPDATE
            woo_product_name = VALUES(woo_product_name),
            woo_sku = VALUES(woo_sku),
            woo_gtin = VALUES(woo_gtin),
            woo_product_type = VALUES(woo_product_type),
            woo_status = VALUES(woo_status),
            updated_at = VALUES(updated_at)
        ";

        $wpdb->query($wpdb->prepare($sql, $values));
    }





	public static function get_products_to_export( $products_ids ) {
		global $wpdb;
		self::init();

		$table_name = self::$table_name;
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
		if ( ! empty( $products_ids ) && is_array( $products_ids ) ) {
			$placeholders = implode( ',', array_fill( 0, count( $products_ids ), '%s' ) );

			return $wpdb->get_results(
				$wpdb->prepare(
					"SELECT * FROM {$table_name} WHERE woo_product_id IN ($placeholders)",
					...$products_ids
				)
			);

		}

		$result = $wpdb->get_results( "SELECT * FROM {$table_name}" );
        // phpcs:enable

		return $result;
	}



	public static function update_product_to_export_status( $woo_products_ids, $export_status, $export_error = null ) {
		global $wpdb;
		self::init();

		$table_name = self::$table_name;

		if ( empty( $export_status ) ) {
			return false;
		}

		$fields_to_update = 'export_status = %s';
		$params           = array( $export_status );

		if ( $export_error !== null ) {
			$serialized_errors = maybe_serialize( $export_error );
			$fields_to_update .= ', export_error = %s';
			$params[]          = $serialized_errors;
		}

	// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
		if ( $woo_products_ids === 'all' ) {
			return $wpdb->query(
				$wpdb->prepare(
					"UPDATE {$table_name} SET {$fields_to_update}",
					$params
				)
			);
		} else {
			if ( ! is_array( $woo_products_ids ) ) {
				$woo_products_ids = array( $woo_products_ids );
			}

			$placeholders = implode( ',', array_fill( 0, count( $woo_products_ids ), '%d' ) );

			return $wpdb->query(
				$wpdb->prepare(
					"UPDATE {$table_name} SET {$fields_to_update} WHERE woo_product_id IN ($placeholders)",
					...array_merge( $params, $woo_products_ids )
				)
			);
		}
	// phpcs:enable
	}

	public static function unlink_woo_product( $woo_product_id ) {
		if ( empty( $woo_product_id ) ) {
			return false;
		}

		global $wpdb;

		self::init();

		$table_name = self::$table_name; // Asegúrate de que esta propiedad tenga un valor válido

		// Ejecutamos la consulta
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$result = $wpdb->query(
			$wpdb->prepare(
				"UPDATE {$table_name} SET vinculated_listing_id = 0 WHERE woo_product_id = %d",
				$woo_product_id
			)
		);
        // phpcs:enable

		// Verificamos si hubo algún error
		if ( $result === false ) {

			Helper::logData( 'Error unlinking product from user listing: ' . $wpdb->last_error );

			/*
			$last_query = $wpdb->last_query;
			Helper::logData('Última consulta SQL ejecutada: ' . $last_query); */
			return false;
		}

		// Si no hubo error, devolvemos el número de filas afectadas
		return $result;
	}
}
