<?php
/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 * 
 * Copyright (c) 2025 CastConductor.com. All Rights Reserved.
 * 
 * This file is part of Cast Conductor ("Software"). The Software and its source
 * code constitute proprietary, confidential, and trade secret information of
 * CastConductor.com ("Company"). Any access or use is governed strictly by the
 * Cast Conductor Proprietary License v5 ("License"). By installing, copying,
 * accessing, compiling, or otherwise using the Software you agree to be bound by
 * all terms of the License. If you do not agree, you must cease use immediately.
 * 
 * Key Terms (Summary – see full License for binding terms):
 *  1. No Redistribution: You may not publish, distribute, sublicense, rent,
 *     lease, transfer, sell, or otherwise make the Software (or any derivative)
 *     available to any third party without prior written consent of Company.
 *  2. No Modification: Modification, reverse engineering, decompilation, or
 *     disassembly is prohibited except to the limited extent expressly permitted
 *     by applicable law that cannot be contractually waived.
 *  3. Confidentiality: Treat all source code and related artifacts as Company
 *     Confidential Information. Maintain at least the same degree of care as for
 *     your own confidential materials, and not less than reasonable care.
 *  4. No Patent License: No express or implied patent rights are granted. Future
 *     patents (if any) are fully reserved.
 *  5. No Trademark License: Company names, marks, and logos may not be used
 *     without prior written permission.
 *  6. Limited Internal Use: Use is limited solely to internal evaluation and
 *     operation of licensed Cast Conductor deployments. Commercial hosting or
 *     resale as a service requires a separate written agreement.
 *  7. Telemetry & License Validation: The Software may periodically transmit a
 *     hashed installation identifier, domain (or site ID), plugin/app version,
 *     and a truncated (non-reversible) fragment of the license key solely to
 *     validate activation status and enforce licensing. This minimal "phone home"
 *     check contains no personal or content data. If optional telemetry is later
 *     introduced it will be limited to aggregate operational metrics (no PII),
 *     fully documented, and optionally disableable per published instructions.
 *  8. Third-Party Components: The Software may include open source components
 *     covered by their own licenses. See THIRD-PARTY-NOTICES.md. Those licenses
 *     govern their respective components; this License governs all remaining code.
 *  9. Export Compliance: You are responsible for compliance with all applicable
 *     export control and sanctions laws.
 * 10. Warranty Disclaimer: THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF
 *     ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO MERCHANTABILITY,
 *     FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.
 * 11. Limitation of Liability: IN NO EVENT WILL COMPANY OR AUTHORS BE LIABLE FOR
 *     ANY INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE
 *     DAMAGES, OR LOST PROFITS, EVEN IF ADVISED OF THE POSSIBILITY.
 * 12. Acceptance: Use of the Software constitutes acceptance of the License.
 * 13. Enforcement: Unauthorized reproduction or distribution may result in civil
 *     and criminal penalties and will be prosecuted to the maximum extent allowed
 *     by law.
 * 
 * Authoritative EULA: EULA-v5.1.md (repository root – private) and https://castconductor.com/eula
 * Precedence: If this summary conflicts with the EULA, the EULA governs.
 * Revision: Current EULA revision v5.1 (subject to update; check EULA for current enterprise thresholds).
 * 
 * Full License text available from: licensing@castconductor.com
 * Security reports: security@castconductor.com
 * Commercial inquiries: licensing@castconductor.com
 * 
 * END OF HEADER
 */

/**
 * Track Info Content Block
 * 
 * Handles track information display with enhanced album artwork discovery
 * Integrates with iTunes, MusicBrainz, and Deezer APIs for comprehensive artwork lookup
 */

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

class CastConductor_Track_Info_Block {
    
    /**
     * Content block type identifier
     */
    public $type = 'track_info';
    
    /**
     * Content block display name
     */
    public $display_name = 'Track Info';
    
    /**
     * Content block description
     */
    public $description = 'Display current track information with enhanced album artwork discovery';
    
    /**
     * Cache duration for artwork URLs (24 hours)
     */
    private $cache_duration = 86400;
    
    /**
     * Album artwork API configuration
     */
    private $artwork_config = [
        'enabled' => true,
        'use_itunes' => true,
        'use_musicbrainz' => true,
        'use_deezer' => true,
        'cache_size' => 500,
        'timeout' => 10,
        'fallback_enabled' => true
    ];
    
    /**
     * Constructor
     */
    public function __construct() {
        add_action('wp_ajax_search_album_artwork', [$this, 'ajax_search_album_artwork']);
        add_action('wp_ajax_nopriv_search_album_artwork', [$this, 'ajax_search_album_artwork']);
        add_action('wp_ajax_clear_artwork_cache', [$this, 'ajax_clear_artwork_cache']);
    }
    
    /**
     * Get content block configuration
     */
    public function get_config() {
        return [
            'type' => $this->type,
            'display_name' => $this->display_name,
            'description' => $this->description,
            'category' => 'media',
            'icon' => 'dashicons-format-audio',
            'supports' => [
                'positioning' => true,
                'styling' => true,
                'animation' => true,
                'responsive' => true
            ],
            'fields' => $this->get_field_schema(),
            'preview' => [
                'artist' => 'Pink Floyd',
                'title' => 'Comfortably Numb',
                'album' => 'The Wall',
                'artwork_url' => '',
                'show_artwork' => true,
                'show_progress' => true
            ]
        ];
    }
    
    /**
     * Get content block field schema
     */
    private function get_field_schema() {
        return [
            'display_settings' => [
                'type' => 'group',
                'label' => 'Display Settings',
                'fields' => [
                    'show_artwork' => [
                        'type' => 'checkbox',
                        'label' => 'Show Album Artwork',
                        'default' => true,
                        'description' => 'Enable enhanced album artwork discovery'
                    ],
                    'artwork_size' => [
                        'type' => 'select',
                        'label' => 'Artwork Size',
                        'default' => 'medium',
                        'options' => [
                            'small' => 'Small (100x100)',
                            'medium' => 'Medium (300x300)',
                            'large' => 'Large (600x600)',
                            'xlarge' => 'Extra Large (1200x1200)'
                        ]
                    ],
                    'show_progress' => [
                        'type' => 'checkbox',
                        'label' => 'Show Progress Bar',
                        'default' => false
                    ],
                    'layout' => [
                        'type' => 'select',
                        'label' => 'Layout Style',
                        'default' => 'horizontal',
                        'options' => [
                            'horizontal' => 'Horizontal (artwork left)',
                            'vertical' => 'Vertical (artwork top)',
                            'artwork_only' => 'Artwork Only',
                            'text_only' => 'Text Only'
                        ]
                    ]
                ]
            ],
            'artwork_settings' => [
                'type' => 'group',
                'label' => 'Artwork Discovery',
                'fields' => [
                    'enable_auto_discovery' => [
                        'type' => 'checkbox',
                        'label' => 'Auto-Discover Artwork',
                        'default' => true,
                        'description' => 'Automatically search for album artwork using multiple APIs'
                    ],
                    'fallback_to_branding' => [
                        'type' => 'checkbox',
                        'label' => 'Use WordPress Branding as Fallback',
                        'default' => true
                    ],
                    'cache_artwork' => [
                        'type' => 'checkbox',
                        'label' => 'Cache Artwork URLs',
                        'default' => true,
                        'description' => 'Cache successful artwork URLs for 24 hours'
                    ]
                ]
            ],
            'styling' => [
                'type' => 'group',
                'label' => 'Visual Styling',
                'fields' => [
                    'background_color' => [
                        'type' => 'color',
                        'label' => 'Background Color',
                        'default' => 'rgba(0,0,0,0.8)'
                    ],
                    'text_color' => [
                        'type' => 'color',
                        'label' => 'Text Color',
                        'default' => '#ffffff'
                    ],
                    'border_radius' => [
                        'type' => 'number',
                        'label' => 'Border Radius (px)',
                        'default' => 8,
                        'min' => 0,
                        'max' => 50
                    ],
                    'shadow_enabled' => [
                        'type' => 'checkbox',
                        'label' => 'Enable Drop Shadow',
                        'default' => true
                    ]
                ]
            ]
        ];
    }
    
    /**
     * Render content block
     */
    public function render($data = [], $context = 'frontend') {
        $config = wp_parse_args($data, $this->get_config()['preview']);
        
        // Get current track info from active stream
        $track_info = $this->get_current_track_info();
        if ($track_info) {
            $config = array_merge($config, $track_info);
        }
        
        // Search for album artwork if enabled
        if (!empty($config['show_artwork']) && !empty($config['enable_auto_discovery'])) {
            $artwork_url = $this->search_album_artwork(
                $config['artist'] ?? '',
                $config['album'] ?? $config['title'] ?? '',
                $config['title'] ?? ''
            );
            if ($artwork_url) {
                $config['artwork_url'] = $artwork_url;
            }
        }
        
        ob_start();
        ?>
        <div class="castconductor-preview-block" 
             data-layout="<?php echo esc_attr($config['layout'] ?? 'horizontal'); ?>"
             data-size="<?php echo esc_attr($config['artwork_size'] ?? 'medium'); ?>">
            
            <?php if (!empty($config['show_artwork']) && !empty($config['artwork_url'])): ?>
                <div class="artwork-container">
                    <img src="<?php echo esc_url($config['artwork_url']); ?>" 
                         alt="<?php echo esc_attr($config['album'] ?? $config['title'] ?? 'Album artwork'); ?>"
                         loading="lazy" />
                </div>
            <?php endif; ?>
            
            <div class="text-content">
                <?php if (!empty($config['title'])): ?>
                    <div class="title"><?php echo esc_html($config['title']); ?></div>
                <?php endif; ?>
                
                <?php if (!empty($config['artist'])): ?>
                    <div class="artist"><?php echo esc_html($config['artist']); ?></div>
                <?php endif; ?>
                
                <?php if (!empty($config['album']) && $config['album'] !== $config['title']): ?>
                    <div class="album"><?php echo esc_html($config['album']); ?></div>
                <?php endif; ?>
                
                <?php if (!empty($config['show_progress'])): ?>
                    <div class="track-progress">
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: 0%"></div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }
    
    /**
     * Search for album artwork using multiple APIs
     */
    public function search_album_artwork($artist, $album, $title = '') {
        if (empty($artist) && empty($album) && empty($title)) {
            return '';
        }
        
        // Create cache key
        $cache_key = 'cc_artwork_' . md5(strtolower($artist . '|' . $album . '|' . $title));
        
        // Check cache first
        if ($this->artwork_config['cache_size'] > 0) {
            $cached = get_transient($cache_key);
            if ($cached !== false) {
                return $cached === 'not_found' ? '' : $cached;
            }
        }
        
        $artwork_url = '';
        
        // Strategy 1: iTunes Search API
        if ($this->artwork_config['use_itunes'] && empty($artwork_url)) {
            $artwork_url = $this->search_itunes_artwork($artist, $album, $title);
        }
        
        // Strategy 2: MusicBrainz + Cover Art Archive
        if ($this->artwork_config['use_musicbrainz'] && empty($artwork_url)) {
            $artwork_url = $this->search_musicbrainz_artwork($artist, $album, $title);
        }
        
        // Strategy 3: Deezer API
        if ($this->artwork_config['use_deezer'] && empty($artwork_url)) {
            $artwork_url = $this->search_deezer_artwork($artist, $album, $title);
        }
        
        // Cache result (including negative results)
        if ($this->artwork_config['cache_size'] > 0) {
            $cache_value = empty($artwork_url) ? 'not_found' : $artwork_url;
            set_transient($cache_key, $cache_value, $this->cache_duration);
        }
        
        return $artwork_url;
    }
    
    /**
     * Search iTunes API for artwork
     */
    private function search_itunes_artwork($artist, $album, $title) {
        $search_terms = [];
        if (!empty($artist)) $search_terms[] = $artist;
        if (!empty($album)) $search_terms[] = $album;
        if (!empty($title) && $title !== $album) $search_terms[] = $title;
        
        if (empty($search_terms)) return '';
        
        $query = urlencode(implode(' ', $search_terms));
        $url = "https://itunes.apple.com/search?term={$query}&entity=album&limit=5&media=music";
        
        $response = wp_remote_get($url, [
            'timeout' => $this->artwork_config['timeout'],
            'user-agent' => 'CastConductor/' . CASTCONDUCTOR_VERSION
        ]);
        
        if (is_wp_error($response)) {
            return '';
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (!empty($data['results'])) {
            foreach ($data['results'] as $result) {
                if (!empty($result['artworkUrl100'])) {
                    // Upscale to higher resolution
                    $artwork_url = str_replace('100x100bb', '600x600bb', $result['artworkUrl100']);
                    return $artwork_url;
                }
            }
        }
        
        return '';
    }
    
    /**
     * Search MusicBrainz API for artwork
     */
    private function search_musicbrainz_artwork($artist, $album, $title) {
        if (empty($artist)) return '';
        
        $query_parts = [];
        $query_parts[] = 'artist:' . urlencode($artist);
        
        if (!empty($album)) {
            $query_parts[] = 'release:' . urlencode($album);
        } elseif (!empty($title)) {
            $query_parts[] = 'release:' . urlencode($title);
        }
        
        $query = implode(' AND ', $query_parts);
        $url = "https://musicbrainz.org/ws/2/release?query={$query}&fmt=json&limit=5";
        
        $response = wp_remote_get($url, [
            'timeout' => $this->artwork_config['timeout'],
            'user-agent' => 'CastConductor/' . CASTCONDUCTOR_VERSION . ' (contact@castconductor.com)'
        ]);
        
        if (is_wp_error($response)) {
            return '';
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (!empty($data['releases'])) {
            foreach ($data['releases'] as $release) {
                if (!empty($release['id'])) {
                    $artwork_url = $this->get_coverart_archive_image($release['id']);
                    if (!empty($artwork_url)) {
                        return $artwork_url;
                    }
                }
            }
        }
        
        return '';
    }
    
    /**
     * Get artwork from Cover Art Archive
     */
    private function get_coverart_archive_image($release_id) {
        $url = "https://coverartarchive.org/release/{$release_id}/front";
        
        $response = wp_remote_head($url, [
            'timeout' => $this->artwork_config['timeout'],
            'redirection' => 0
        ]);
        
        if (!is_wp_error($response)) {
            $code = wp_remote_retrieve_response_code($response);
            if ($code === 302 || $code === 307) {
                $location = wp_remote_retrieve_header($response, 'location');
                if (!empty($location)) {
                    return $location;
                }
            }
        }
        
        return '';
    }
    
    /**
     * Search Deezer API for artwork
     */
    private function search_deezer_artwork($artist, $album, $title) {
        $search_terms = [];
        if (!empty($artist)) $search_terms[] = $artist;
        if (!empty($album)) $search_terms[] = $album;
        if (!empty($title) && $title !== $album) $search_terms[] = $title;
        
        if (empty($search_terms)) return '';
        
        $query = urlencode(implode(' ', $search_terms));
        $url = "https://api.deezer.com/search/album?q={$query}&limit=5";
        
        $response = wp_remote_get($url, [
            'timeout' => $this->artwork_config['timeout'],
            'user-agent' => 'CastConductor/' . CASTCONDUCTOR_VERSION
        ]);
        
        if (is_wp_error($response)) {
            return '';
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (!empty($data['data'])) {
            foreach ($data['data'] as $album_data) {
                if (!empty($album_data['cover_xl'])) {
                    return $album_data['cover_xl'];
                } elseif (!empty($album_data['cover_big'])) {
                    return $album_data['cover_big'];
                }
            }
        }
        
        return '';
    }
    
    /**
     * Get current track info from streaming source
     */
    private function get_current_track_info() {
        // This would integrate with the streaming source API
        // For now, return empty - will be populated by live data integration
        return null;
    }
    
    /**
     * AJAX handler for album artwork search
     */
    public function ajax_search_album_artwork() {
        check_ajax_referer('castconductor_admin', 'nonce');
        
        $artist = sanitize_text_field($_POST['artist'] ?? '');
        $album = sanitize_text_field($_POST['album'] ?? '');
        $title = sanitize_text_field($_POST['title'] ?? '');
        
        $artwork_url = $this->search_album_artwork($artist, $album, $title);
        
        wp_send_json_success([
            'artwork_url' => $artwork_url,
            'cache_key' => md5(strtolower($artist . '|' . $album . '|' . $title))
        ]);
    }
    
    /**
     * AJAX handler for clearing artwork cache
     */
    public function ajax_clear_artwork_cache() {
        check_ajax_referer('castconductor_admin', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        global $wpdb;
        $wpdb->query(
            "DELETE FROM {$wpdb->options} 
             WHERE option_name LIKE '_transient_cc_artwork_%' 
             OR option_name LIKE '_transient_timeout_cc_artwork_%'"
        );
        
        wp_send_json_success(['message' => 'Artwork cache cleared successfully']);
    }
    
    /**
     * Get block specific CSS
     */
    public function get_css($config = []) {
        $css = '
.castconductor-preview-block {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 16px;
    background: rgba(0,0,0,0.8);
    border-radius: 8px;
    color: white;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}

.castconductor-preview-block[data-layout="vertical"] {
    flex-direction: column;
    text-align: center;
}

.castconductor-preview-block[data-layout="artwork_only"] .text-content {
    display: none;
}

.castconductor-preview-block[data-layout="text_only"] .artwork-container {
    display: none;
}

/* Artwork sizing based on data-size attribute */
.castconductor-preview-block[data-size="small"] .artwork-container { 
    width: 100px; 
    height: 100px; 
    flex-shrink: 0;
}

.castconductor-preview-block[data-size="medium"] .artwork-container { 
    width: 200px; 
    height: 200px; 
    flex-shrink: 0;
}

.castconductor-preview-block[data-size="large"] .artwork-container { 
    width: 300px; 
    height: 300px; 
    flex-shrink: 0;
}

.castconductor-preview-block[data-size="xlarge"] .artwork-container { 
    width: 400px; 
    height: 400px; 
    flex-shrink: 0;
}

.artwork-container {
    overflow: hidden;
    border-radius: 4px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.3);
}

.artwork-container img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
}

.text-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.title {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 4px;
}

.artist {
    font-size: 16px;
    opacity: 0.9;
    margin-bottom: 2px;
}

.album {
    font-size: 14px;
    opacity: 0.7;
}

.track-progress {
    margin-top: 12px;
}

.progress-bar {
    width: 100%;
    height: 4px;
    background: rgba(255,255,255,0.2);
    border-radius: 2px;
    overflow: hidden;
}

.progress-fill {
    height: 100%;
    background: linear-gradient(90deg, #1db954, #1ed760);
    transition: width 0.3s ease;
}

@media (max-width: 768px) {
    .castconductor-preview-block {
        flex-direction: column;
        text-align: center;
        gap: 12px;
        padding: 12px;
    }
    
    .artwork-container {
        max-width: 150px;
    }
}
';
        
        return $css;
    }
}
