<?php
/**
 * Plugin Name: VH Flickr Mosaic
 * Plugin URI: https://github.com/vesnushka/vh-flickr-mosaic
 * Description: Beautiful photo mosaic widget with fade animations, powered by VH Posting System
 * Version: 1.0.0
 * Author: VH Posting System
 * License: GPL v2 or later
 * Text Domain: vh-flickr-mosaic
 */

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

class VH_Flickr_Mosaic {

    private static $instance = null;
    private $options;

    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        $this->options = get_option('vh_flickr_mosaic_options', [
            'api_url' => '',
            'position' => 'footer',
            'rows' => 2,
            'photo_size' => 150,
            'animation_speed' => 5,
            'enabled' => true,
        ]);

        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_init', [$this, 'settings_init']);
        add_action('wp_enqueue_scripts', [$this, 'enqueue_scripts']);
        add_action('wp_footer', [$this, 'render_mosaic']);
        add_shortcode('flickr_mosaic', [$this, 'shortcode_mosaic']);
    }

    public function add_admin_menu() {
        add_options_page(
            'VH Flickr Mosaic',
            'VH Flickr Mosaic',
            'manage_options',
            'vh-flickr-mosaic',
            [$this, 'options_page']
        );
    }

    public function settings_init() {
        register_setting('vh_flickr_mosaic', 'vh_flickr_mosaic_options');

        add_settings_section(
            'vh_flickr_mosaic_section',
            __('Настройки мозаики', 'vh-flickr-mosaic'),
            null,
            'vh-flickr-mosaic'
        );

        add_settings_field(
            'api_url',
            __('API URL', 'vh-flickr-mosaic'),
            [$this, 'api_url_render'],
            'vh-flickr-mosaic',
            'vh_flickr_mosaic_section'
        );

        add_settings_field(
            'enabled',
            __('Включить', 'vh-flickr-mosaic'),
            [$this, 'enabled_render'],
            'vh-flickr-mosaic',
            'vh_flickr_mosaic_section'
        );

        add_settings_field(
            'position',
            __('Позиция', 'vh-flickr-mosaic'),
            [$this, 'position_render'],
            'vh-flickr-mosaic',
            'vh_flickr_mosaic_section'
        );

        add_settings_field(
            'rows',
            __('Количество рядов', 'vh-flickr-mosaic'),
            [$this, 'rows_render'],
            'vh-flickr-mosaic',
            'vh_flickr_mosaic_section'
        );

        add_settings_field(
            'photo_size',
            __('Размер фото (px)', 'vh-flickr-mosaic'),
            [$this, 'photo_size_render'],
            'vh-flickr-mosaic',
            'vh_flickr_mosaic_section'
        );

        add_settings_field(
            'animation_speed',
            __('Скорость анимации (сек)', 'vh-flickr-mosaic'),
            [$this, 'animation_speed_render'],
            'vh-flickr-mosaic',
            'vh_flickr_mosaic_section'
        );
    }

    public function api_url_render() {
        ?>
        <input type='url' name='vh_flickr_mosaic_options[api_url]'
               value='<?php echo esc_attr($this->options['api_url'] ?? ''); ?>'
               class='regular-text' placeholder='https://your-site.com/vh/widget_api.php?action=get_photos'>
        <p class="description"><?php _e('URL API из VH Posting System (вкладка Виджет)', 'vh-flickr-mosaic'); ?></p>
        <?php
    }

    public function enabled_render() {
        ?>
        <label>
            <input type='checkbox' name='vh_flickr_mosaic_options[enabled]'
                   <?php checked($this->options['enabled'] ?? true); ?> value='1'>
            <?php _e('Показывать мозаику', 'vh-flickr-mosaic'); ?>
        </label>
        <?php
    }

    public function position_render() {
        ?>
        <select name='vh_flickr_mosaic_options[position]'>
            <option value='footer' <?php selected($this->options['position'] ?? 'footer', 'footer'); ?>>
                <?php _e('В футере', 'vh-flickr-mosaic'); ?>
            </option>
            <option value='shortcode' <?php selected($this->options['position'] ?? 'footer', 'shortcode'); ?>>
                <?php _e('Только шорткод [flickr_mosaic]', 'vh-flickr-mosaic'); ?>
            </option>
        </select>
        <?php
    }

    public function rows_render() {
        ?>
        <input type='number' name='vh_flickr_mosaic_options[rows]'
               value='<?php echo esc_attr($this->options['rows'] ?? 2); ?>'
               min='1' max='5' style='width: 60px;'>
        <?php
    }

    public function photo_size_render() {
        ?>
        <input type='number' name='vh_flickr_mosaic_options[photo_size]'
               value='<?php echo esc_attr($this->options['photo_size'] ?? 150); ?>'
               min='80' max='300' style='width: 80px;'>
        <?php
    }

    public function animation_speed_render() {
        ?>
        <input type='number' name='vh_flickr_mosaic_options[animation_speed]'
               value='<?php echo esc_attr($this->options['animation_speed'] ?? 5); ?>'
               min='2' max='15' step='0.5' style='width: 80px;'>
        <p class="description"><?php _e('Время между сменой фото', 'vh-flickr-mosaic'); ?></p>
        <?php
    }

    public function options_page() {
        ?>
        <div class="wrap">
            <h1><?php _e('VH Flickr Mosaic', 'vh-flickr-mosaic'); ?></h1>
            <form action='options.php' method='post'>
                <?php
                settings_fields('vh_flickr_mosaic');
                do_settings_sections('vh-flickr-mosaic');
                submit_button();
                ?>
            </form>

            <hr>
            <h2><?php _e('Использование', 'vh-flickr-mosaic'); ?></h2>
            <p><?php _e('Используйте шорткод для вставки мозаики в любое место:', 'vh-flickr-mosaic'); ?></p>
            <code>[flickr_mosaic]</code>
            <p><?php _e('С параметрами:', 'vh-flickr-mosaic'); ?></p>
            <code>[flickr_mosaic rows="3" size="120" speed="4"]</code>

            <hr>
            <h2><?php _e('Предпросмотр', 'vh-flickr-mosaic'); ?></h2>
            <div id="vh-mosaic-preview">
                <button type="button" class="button" onclick="vhMosaicPreview()">
                    <?php _e('Загрузить предпросмотр', 'vh-flickr-mosaic'); ?>
                </button>
            </div>

            <script>
            function vhMosaicPreview() {
                const apiUrl = document.querySelector('input[name="vh_flickr_mosaic_options[api_url]"]').value;
                if (!apiUrl) {
                    alert('Укажите API URL');
                    return;
                }

                const preview = document.getElementById('vh-mosaic-preview');
                preview.innerHTML = '<p>Загрузка...</p>';

                fetch(apiUrl)
                    .then(r => r.json())
                    .then(data => {
                        if (data.success && data.photos) {
                            let html = '<div style="display:flex;flex-wrap:wrap;gap:8px;max-width:600px;">';
                            data.photos.slice(0, 12).forEach(photo => {
                                html += `<img src="${photo.thumb}" style="width:80px;height:80px;object-fit:cover;border-radius:4px;">`;
                            });
                            html += '</div>';
                            html += `<p>Загружено ${data.photos.length} фото</p>`;
                            preview.innerHTML = html;
                        } else {
                            preview.innerHTML = '<p style="color:red;">Ошибка: ' + (data.error || 'Неизвестная ошибка') + '</p>';
                        }
                    })
                    .catch(err => {
                        preview.innerHTML = '<p style="color:red;">Ошибка подключения: ' + err.message + '</p>';
                    });
            }
            </script>
        </div>
        <?php
    }

    public function enqueue_scripts() {
        if (empty($this->options['enabled']) || empty($this->options['api_url'])) {
            return;
        }

        wp_enqueue_style(
            'vh-flickr-mosaic',
            plugin_dir_url(__FILE__) . 'assets/css/mosaic.css',
            [],
            '1.0.0'
        );

        wp_enqueue_script(
            'vh-flickr-mosaic',
            plugin_dir_url(__FILE__) . 'assets/js/mosaic.js',
            [],
            '1.0.0',
            true
        );

        wp_localize_script('vh-flickr-mosaic', 'vhMosaicConfig', [
            'apiUrl' => $this->options['api_url'],
            'rows' => intval($this->options['rows'] ?? 2),
            'photoSize' => intval($this->options['photo_size'] ?? 150),
            'animationSpeed' => floatval($this->options['animation_speed'] ?? 5),
        ]);
    }

    public function render_mosaic() {
        if (empty($this->options['enabled']) || empty($this->options['api_url'])) {
            return;
        }

        if (($this->options['position'] ?? 'footer') !== 'footer') {
            return;
        }

        echo $this->get_mosaic_html();
    }

    public function shortcode_mosaic($atts) {
        if (empty($this->options['api_url'])) {
            return '<!-- VH Flickr Mosaic: API URL not configured -->';
        }

        $atts = shortcode_atts([
            'rows' => $this->options['rows'] ?? 2,
            'size' => $this->options['photo_size'] ?? 150,
            'speed' => $this->options['animation_speed'] ?? 5,
        ], $atts);

        return $this->get_mosaic_html($atts);
    }

    private function get_mosaic_html($atts = []) {
        $rows = intval($atts['rows'] ?? $this->options['rows'] ?? 2);
        $size = intval($atts['size'] ?? $this->options['photo_size'] ?? 150);
        $speed = floatval($atts['speed'] ?? $this->options['animation_speed'] ?? 5);

        return sprintf(
            '<div class="vh-flickr-mosaic" data-rows="%d" data-size="%d" data-speed="%s">
                <div class="vh-mosaic-container"></div>
            </div>',
            $rows,
            $size,
            $speed
        );
    }
}

// Initialize
VH_Flickr_Mosaic::get_instance();
