<?php
/**
 * Helper functions for BW Gallery
 */

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

class BW_Gallery_Helper {
    
    /**
     * Sanitize and validate gallery data
     */
    public static function validate_gallery_data($data) {
        $errors = array();
        
        // Validate gallery name
        if (empty($data['name'])) {
            $errors['name'] = __('Gallery name is required.', 'bw-gallery');
        } elseif (strlen($data['name']) > 255) {
            $errors['name'] = __('Gallery name must be less than 255 characters.', 'bw-gallery');
        }
        
        // Validate columns
        if (isset($data['columns'])) {
            $columns = intval($data['columns']);
            if ($columns < 1 || $columns > 10) {
                $errors['columns'] = __('Columns must be between 1 and 10.', 'bw-gallery');
            }
        }
        
        // Validate gap
        if (isset($data['gap'])) {
            $gap = intval($data['gap']);
            if ($gap < 0 || $gap > 100) {
                $errors['gap'] = __('Gap must be between 0 and 100 pixels.', 'bw-gallery');
            }
        }
        
        return $errors;
    }
    
    /**
     * Get cached gallery data
     */
    public static function get_cached_gallery($gallery_id) {
        $cache_key = 'bwg_gallery_' . $gallery_id;
        $cached = wp_cache_get($cache_key, 'bw_gallery');
        
        if (false === $cached) {
            $db = new BW_Gallery_DB();
            $gallery = $db->get_gallery($gallery_id);
            
            if ($gallery) {
                wp_cache_set($cache_key, $gallery, 'bw_gallery', 3600);
            }
            
            return $gallery;
        }
        
        return $cached;
    }
    
    /**
     * Clear gallery cache
     */
    public static function clear_gallery_cache($gallery_id) {
        wp_cache_delete('bwg_gallery_' . $gallery_id, 'bw_gallery');
        wp_cache_delete('bwg_gallery_images_' . $gallery_id, 'bw_gallery');
    }
    
    /**
     * Get optimized image URL
     */
    public static function get_optimized_image_url($attachment_id, $size = 'medium') {
        $image_data = wp_get_attachment_image_src($attachment_id, $size);
        
        if (!$image_data) {
            return false;
        }
        
        // Apply filters for CDN or external storage
        $url = apply_filters('bwg_image_url', $image_data[0], $attachment_id, $size);
        
        return $url;
    }
    
    /**
     * Log debug information
     */
    public static function log($message, $level = 'info') {
        if (!defined('WP_DEBUG') || !WP_DEBUG) {
            return;
        }
        
        $upload_dir = wp_upload_dir();
        $log_dir = $upload_dir['basedir'] . '/bw-gallery-logs';
        
        if (!file_exists($log_dir)) {
            wp_mkdir_p($log_dir);
        }
        
        $log_file = $log_dir . '/debug.log';
        $timestamp = current_time('mysql');
        $formatted = sprintf("[%s] [%s] %s\n", $timestamp, strtoupper($level), $message);
        
        error_log($formatted, 3, $log_file);
    }
    
    /**
     * Rate limiting check
     */
    public static function check_rate_limit($action, $limit = 10, $window = 60) {
        $user_id = get_current_user_id();
        $key = 'bwg_rate_limit_' . $action . '_' . $user_id;
        $attempts = get_transient($key);
        
        if (false === $attempts) {
            $attempts = 0;
        }
        
        if ($attempts >= $limit) {
            self::log("Rate limit exceeded for action: $action, user: $user_id", 'warning');
            return false;
        }
        
        set_transient($key, $attempts + 1, $window);
        return true;
    }
    
    /**
     * Generate unique gallery slug
     */
    public static function generate_gallery_slug($name) {
        $slug = sanitize_title($name);
        $original_slug = $slug;
        $counter = 1;
        
        global $wpdb;
        $table = $wpdb->prefix . 'bwg_galleries';
        
        while ($wpdb->get_var($wpdb->prepare("SELECT id FROM $table WHERE name = %s", $slug))) {
            $slug = $original_slug . '-' . $counter;
            $counter++;
        }
        
        return $slug;
    }
    
    /**
     * Get gallery shortcode HTML for copy
     */
    public static function get_shortcode_html($gallery_id) {
        $shortcode = '[bw_gallery id="' . intval($gallery_id) . '"]';
        
        return sprintf(
            '<code class="bwg-shortcode">%s</code> <button class="button button-small bwg-copy-shortcode" data-shortcode="%s">%s</button>',
            esc_html($shortcode),
            esc_attr($shortcode),
            esc_html__('Copy', 'bw-gallery')
        );
    }
    
    /**
     * Bulk optimize gallery images
     */
    public static function optimize_gallery_images($gallery_id) {
        $db = new BW_Gallery_DB();
        $images = $db->get_gallery_images($gallery_id);
        
        foreach ($images as $image) {
            $attachment_id = $image['image_id'];
            
            // Generate missing image sizes
            if (wp_attachment_is_image($attachment_id)) {
                $fullsizepath = get_attached_file($attachment_id);
                
                if (file_exists($fullsizepath)) {
                    wp_generate_attachment_metadata($attachment_id, $fullsizepath);
                }
            }
        }
        
        self::log("Optimized images for gallery ID: $gallery_id");
    }
    
    /**
     * Export gallery data
     */
    public static function export_gallery($gallery_id) {
        $db = new BW_Gallery_DB();
        $gallery = $db->get_gallery($gallery_id);
        $images = $db->get_gallery_images($gallery_id);
        
        if (!$gallery) {
            return false;
        }
        
        $export_data = array(
            'gallery' => $gallery,
            'images' => $images,
            'version' => BWG_VERSION,
            'export_date' => current_time('mysql')
        );
        
        return json_encode($export_data, JSON_PRETTY_PRINT);
    }
    
    /**
     * Import gallery data
     */
    public static function import_gallery($json_data) {
        $data = json_decode($json_data, true);
        
        if (!$data || !isset($data['gallery']) || !isset($data['images'])) {
            return new WP_Error('invalid_data', __('Invalid import data.', 'bw-gallery'));
        }
        
        $db = new BW_Gallery_DB();
        
        // Create new gallery
        $gallery_id = $db->insert_gallery($data['gallery']);
        
        if (!$gallery_id) {
            return new WP_Error('insert_failed', __('Failed to create gallery.', 'bw-gallery'));
        }
        
        // Import images
        foreach ($data['images'] as $image) {
            $db->add_gallery_image(
                $gallery_id,
                $image['image_id'],
                $image['tab_name'],
                $image['caption'],
                $image['sort_order']
            );
        }
        
        return $gallery_id;
    }
}