<?php
/**
 * Product Sync Audit Model
 *
 * @category   WordPress_Plugin
 * @package    Standard
 * @subpackage Models
 * @author     miniOrange <info@miniorange.com>
 * @license    MIT/Expat
 * @link       https://plugins.miniorange.com/woocommerce-api-product-sync-with-woocommerce-rest-apis
 */

namespace MOWCPS\Standard\Models;

use WP_Error;
use MOWCPS\Common\Utils\Model_Utils;
use MOWCPS\Common\Models\Product_Sync_Audit_Model as Common_Product_Sync_Audit_Model;

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

/**
 * Class Product_Sync_Audit_Model
 *
 * Handles product sync audit data storage and retrieval
 */
class Product_Sync_Audit_Model extends Common_Product_Sync_Audit_Model {
	/**
	 * Product sync audit table name
	 *
	 * @var string
	 */
	private static $table_name = Model_Utils::TABLE_PRODUCT_SYNC_AUDIT;

	/**
	 * Supplier table name
	 *
	 * @var string
	 */
	private static $suppliers_table = Model_Utils::TABLE_SUPPLIERS;

	/**
	 * Get product sync audit data with filtering and pagination
	 *
	 * @param string $mode Optional mode filter: 'manual', 'automatic', or '' for all.
	 * @return array|WP_Error Audit data or error
	 */
	public static function get_product_sync_audit( $mode = '' ) {
		$table_name      = Model_Utils::get_table_name( self::$table_name );
		$suppliers_table = Model_Utils::get_table_name( self::$suppliers_table );

		// Build the base query (standard plan - manual sync only).
		$query = "SELECT 
			s.name as supplier_name,
			s.uuid as supplier_uuid,
			psa.status,
			psa.status_message,
			psa.start_time,
			psa.end_time,
			psa.total_parsed,
			psa.parsed_success,
			psa.parsed_failed,
			psa.variation_success_parsed,
			'Manual' as sync_type,
			'N/A' as schedule_name,
			NULL as schedule_uuid
			FROM `{$table_name}` psa
			LEFT JOIN `{$suppliers_table}` s ON psa.supplier_id = s.id
			WHERE psa.connection_id IS NULL
			AND psa.schedule_id IS NULL
			ORDER BY psa.start_time DESC";

		return self::get_results( $query );
	}
}
