<?php
if (!defined('ABSPATH')) {
    exit;
}

class Bulk_Sync_Manager {
    
    private $s3_sync;
    private $batch_size;
    
    public function __construct($s3_sync) {
        $this->s3_sync = $s3_sync;
        $this->batch_size = apply_filters('cloud_uploads_batch_size', 5);
        
        $this->setup_hooks();
    }
    
    private function setup_hooks() {
        add_action('admin_init', array($this, 'handle_bulk_actions'));
    }
    
    public function get_unsynced_attachments($limit = null, $offset = 0) {
        global $wpdb;
        
        $query = "SELECT ID FROM {$wpdb->posts} 
                 WHERE post_type = 'attachment' 
                 AND post_status = 'inherit'
                 AND ID NOT IN (
                     SELECT post_id FROM {$wpdb->postmeta} 
                     WHERE meta_key = '_s3_synced' 
                     AND meta_value = '1'
                 )";
        
        if ($limit) {
            $query .= $wpdb->prepare(" LIMIT %d OFFSET %d", $limit, $offset);
        }
        
        return $wpdb->get_col($query);
    }
    
    public function get_sync_stats() {
        global $wpdb;
        
        $total = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = 'attachment' AND post_status = 'inherit'");
        $synced = $wpdb->get_var("SELECT COUNT(DISTINCT post_id) FROM {$wpdb->postmeta} WHERE meta_key = '_s3_synced' AND meta_value = '1'");
        
        return array(
            'total' => (int) $total,
            'synced' => (int) $synced,
            'unsynced' => (int) ($total - $synced),
            'percentage' => $total > 0 ? round(($synced / $total) * 100) : 0
        );
    }
    
    public function process_batch($batch_number = 0, $batch_size = 5) {
        $offset = $batch_number * $batch_size;
        $attachments = $this->get_unsynced_attachments($batch_size, $offset);
        
        $results = array(
            'processed' => 0,
            'succeeded' => 0,
            'failed' => 0,
            'errors' => array(),
            'batch' => $batch_number,
            'completed' => false
        );
        
        foreach ($attachments as $attachment_id) {
            $results['processed']++;
            
            try {
                $success = $this->s3_sync->sync_attachment($attachment_id);
                
                if ($success) {
                    $results['succeeded']++;
                } else {
                    $results['failed']++;
                    $results['errors'][] = "Failed to sync attachment ID: $attachment_id";
                }
            } catch (Exception $e) {
                $results['failed']++;
                $results['errors'][] = "Error syncing attachment ID: $attachment_id - " . $e->getMessage();
            }
        }
        
        // Check if this was the last batch
        $remaining = $this->get_unsynced_attachments(1, $offset + $batch_size);
        $results['completed'] = empty($remaining);
        
        // Update overall stats
        $stats = $this->get_sync_stats();
        $results['stats'] = $stats;
        
        return $results;
    }
    
    public function handle_bulk_actions() {
        if (isset($_GET['action']) && $_GET['action'] === 'sync_all_to_s3') {
            check_admin_referer('sync_all_to_s3');
            
            // Redirect to settings page with bulk sync interface
            wp_redirect(admin_url('upload.php?page=cloud-uploads&bulk_sync=1'));
            exit;
        }
    }
    
    public function prepare_bulk_sync() {
        // This method can be used to prepare for bulk sync
        // For example, logging start time, resetting previous progress, etc.
        update_option('cloud_uploads_bulk_started', current_time('mysql'));
        delete_option('cloud_uploads_bulk_completed');
    }
}