<?php

namespace Meliconnect\Meliconnect\Core\Models;

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

	private static $table_name;

	// Este método se llama automáticamente cuando se accede por primera vez a la clase
	public static function init() {
		global $wpdb;
		self::$table_name = $wpdb->prefix . 'meliconnect_process_items';
	}

	public static function getPendingBatch( string $type, int $limit ) {
		global $wpdb;

		$process = Process::getCurrentProcessData( $type, array( 'pending', 'processing' ) );

		if ( ! $process ) {
			return array();
		}

		return self::getProcessItems(
			$process->process_id,
			$limit,
			'pending'
		);
	}

    public static function countPending($process_id)
    {
        global $wpdb;

        self::init();

        $table = self::$table_name;

        return (int) $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) 
                FROM {$table} 
                WHERE process_id = %s 
                AND process_status = 'pending'",
                $process_id
            )
        );
    }

	public static function markAsProcessing( array $ids ) {
		global $wpdb;

		if ( empty( $ids ) ) {
			return;
		}

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

		$wpdb->query(
			$wpdb->prepare(
				"UPDATE {$wpdb->prefix}meliconnect_process_items
                SET process_status = 'processing', updated_at = NOW()
                WHERE id IN ($placeholders)",
				$ids
			)
		);
	}

	public static function markAsProcessed( $item_id, $process_id ) {
		return self::updateProcessedItemStatus(
			$item_id,
			'processed',
			$process_id
		);
	}

	public static function markAsFailed( $item_id, $process_id, $error ) {
        //Updates count of failed items in process table
		self::updateProcessedItemStatus(
			$item_id,
			'failed',
			$process_id
		);
		
        global $wpdb;

		$wpdb->update(
			"{$wpdb->prefix}meliconnect_process_items",
			array(
				'process_status' => 'failed',
				'process_error'  => substr( $error, 0, 255 ),
				'updated_at'     => current_time( 'mysql' ),
			),
			array(
				'id'         => $item_id,
				'process_id' => $process_id,
			)
		);
	}

	public static function updateProcessedItemStatus( $item_process_id, $status, $process_id) {
		global $wpdb;

		self::init();

		$table_name = self::$table_name;

        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$result_item = $wpdb->query( $wpdb->prepare( "UPDATE {$table_name} SET process_status = %s WHERE id = %s", $status, $item_process_id ) );

		if ( $result_item !== false ) {

			if ( $status == 'failed' ) {
				$process = Process::updateProcessProgress( $process_id, false );
			} else {
				$process = Process::updateProcessProgress( $process_id, true );
			}

			return $process;
		}

		return false;
	}


	public static function createProcessItems( $process_id, $items ) {
		global $wpdb;

		self::init();

		$table_name = self::$table_name;

		// Asegúrate de que $items sea un array no vacío y de arrays asociativos
		if ( ! empty( $items ) && is_array( $items ) ) {
			foreach ( $items as $item ) {
				if ( is_array( $item ) ) {
					$wpdb->insert(
						$table_name,
						array(
							'process_id'      => $process_id,
							'meli_user_id'    => $item['meli_user_id'] ?? null,
							'meli_listing_id' => $item['meli_listing_id'] ?? null,
							'woo_product_id'  => $item['woo_product_id'] ?? null,
							'template_id'     => $item['template_id'] ?? null,
							'process_status'  => 'pending',
						)
					);
				}
			}
		}
	}

	public static function getProcessItems( $process_id, $limit = 100, $item_status = 'pending' ) {
		global $wpdb;

		self::init();

		$table_name = self::$table_name;

        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$items = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table_name} WHERE process_id = %s AND process_status = %s LIMIT %d", $process_id, $item_status, $limit ) );

		return $items;
	}

	public static function deleteItems( $process_id ) {
		global $wpdb;

		self::init();

		$table_name = self::$table_name;

        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$result = $wpdb->query( $wpdb->prepare( "DELETE FROM {$table_name} WHERE process_id = %s", $process_id ) );

		return $result;
	}
}
