<?php
namespace ShopyPress\Controllers;
if ( ! defined( 'ABSPATH' ) ) exit;

use ShopyPress\Jobs\SyncProducts;
use ShopyPress\Models\SyncState;
use ShopyPress\Utils\OptionUtils;

class ProductSyncCtrl {

    /**
     * Start product sync manually
     */
    public static function startSync(): void {
        // Verify nonce
        if (!check_ajax_referer('shopypress_app_settings_nonce', 'nonce', false)) {
            wp_send_json_error([
                'message' => esc_html__('Invalid security token', 'synckube-products-sync-for-shopify'),
            ], 403);
            return;
        }

        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error([
                'message' => esc_html__('Insufficient permissions', 'synckube-products-sync-for-shopify'),
            ], 403);
            return;
        }

        // Clear any existing state (fresh start)
        SyncState::delete();

        // Run sync job once
        $job = new SyncProducts();
        $job->run();

        // Get updated state
        $state = SyncState::load();

        wp_send_json_success([
            'message' => esc_html__('Sync started', 'synckube-products-sync-for-shopify'),
            'state' => $state ? $state->toArray() : null
        ]);
    }

    /**
     * Get current sync status
     */
    public static function getSyncStatus(): void {
        // Verify nonce
        if (!check_ajax_referer('shopypress_app_settings_nonce', 'nonce', false)) {
            wp_send_json_error([
                'message' => esc_html__('Invalid security token', 'synckube-products-sync-for-shopify'),
            ], 403);
            return;
        }

        $state = SyncState::load();

        wp_send_json_success([
            'state' => $state ? $state->toArray() : null,
        ]);
    }

    /**
     * Reset sync state
     */
    public static function resetSync(): void {
        // Verify nonce
        if (!check_ajax_referer('shopypress_app_settings_nonce', 'nonce', false)) {
            wp_send_json_error([
                'message' => esc_html__('Invalid security token', 'synckube-products-sync-for-shopify'),
            ], 403);
            return;
        }

        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error([
                'message' => esc_html__('Insufficient permissions', 'synckube-products-sync-for-shopify'),
            ], 403);
            return;
        }

        // Delete state
        SyncState::delete();

        // Clean up lock file if exists
        $lockFile = get_temp_dir() . 'shopypress_sync_products.lock';
        if (file_exists($lockFile)) {
            wp_delete_file($lockFile);
        }

        wp_send_json_success([
            'message' => esc_html__('Sync reset successfully', 'synckube-products-sync-for-shopify')
        ]);
    }
}
