<?php
/**
 * Frontend class for displaying announcements on public pages
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class PC_Announcements_274_Frontend {
    
    /**
     * Constructor
     */
    public function __construct() {
        add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_scripts'));
        add_action('wp_head', array($this, 'display_announcements'), 1);
        add_shortcode('pc_announcements_274', array($this, 'get_announcements_for_shortcode'));
    }
    
    /**
     * Enqueue frontend scripts and styles
     */
    public function enqueue_frontend_scripts() {
        wp_enqueue_style('pc-announcements-274-public-style', PC_ANNOUNCEMENTS_274_PLUGIN_URL . 'public/css/public-style.css', array(), PC_ANNOUNCEMENTS_274_VERSION);
        wp_enqueue_script('pc-announcements-274-public-script', PC_ANNOUNCEMENTS_274_PLUGIN_URL . 'public/js/public-script.js', array('jquery'), PC_ANNOUNCEMENTS_274_VERSION, true);
    }
    
    /**
     * Get active announcements
     */
    private function get_active_announcements() {
        global $wpdb;
        $table_name = PC_Announcements_274_Install::get_table_name();
        
        if (empty($table_name)) {
            return array();
        }
        
        $current_time = current_time('mysql');
        
        $announcements = $wpdb->get_results($wpdb->prepare("
            SELECT * FROM $table_name 
            WHERE status = %s 
            AND (start_date IS NULL OR start_date <= %s)
            AND (end_date IS NULL OR end_date >= %s)
            ORDER BY created_at DESC
        ", 'active', $current_time, $current_time));
        
        if ($announcements === null) {
            return array();
        }
        
        return $announcements;
    }
    
    /**
     * Display announcements at the top of pages
     */
    public function display_announcements() {
        // Don't show on admin pages or in WordPress admin
        if (is_admin()) {
            return;
        }
        
        $announcements = $this->get_active_announcements();
        
        if (empty($announcements)) {
            return;
        }
        
        // Display only the most recent active announcement
        $announcement = $announcements[0];
        
        $this->render_announcement($announcement);
    }
    
    /**
     * Render single announcement
     */
    private function render_announcement($announcement) {
        $title = esc_html($announcement->title);
        $message = wpautop(wp_kses_post($announcement->message));
        $image_url = esc_url($announcement->image_url);
        $banner_color = esc_attr($announcement->banner_color);
        $link_url = esc_url($announcement->link_url);
        $close_text = __('Close', 'pc-announcements-274');
        
        $banner_style = '';
        if (!empty($banner_color) && $banner_color !== '#0d47a1') {
            $banner_style = 'background: ' . $banner_color . ';';
        }
        
        $has_link = !empty($link_url);
        $link_attrs = $has_link ? 'href="' . $link_url . '" target="_blank" rel="noopener noreferrer"' : '';
        $close_button = $has_link ? '' : '<button class="pc-announcements-274-close" aria-label="' . esc_attr($close_text) . '">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
        </button>';
        
        ?>
        <div class="pc-announcements-274-announcement" data-announcement-id="<?php echo $announcement->id; ?>" style="<?php echo $banner_style; ?>">
            <div class="pc-announcements-274-container">
                <div class="pc-announcements-274-content">
                    <?php if ($has_link): ?>
                        <a class="pc-announcements-274-link" <?php echo $link_attrs; ?>>
                    <?php endif; ?>
                    
                    <?php if (!empty($image_url)): ?>
                        <div class="pc-announcements-274-image">
                            <img src="<?php echo $image_url; ?>" alt="<?php echo esc_attr($title); ?>" loading="lazy">
                        </div>
                    <?php endif; ?>
                    
                    <div class="pc-announcements-274-text">
                        <?php if (!empty($title)): ?>
                            <h3 class="pc-announcements-274-title"><?php echo $title; ?></h3>
                        <?php endif; ?>
                        <?php if (!empty(trim($message))): ?>
                            <div class="pc-announcements-274-message">
                                <?php echo $message; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <?php if ($has_link): ?>
                        </a>
                    <?php endif; ?>
                </div>
                
                <?php echo $close_button; ?>
            </div>
        </div>
        <?php
    }
    
    /**
     * Get announcements for shortcode
     */
    public function get_announcements_for_shortcode($atts) {
        $atts = shortcode_atts(array(
            'count' => 1,
            'show_image' => true,
            'show_close' => true,
            'class' => ''
        ), $atts, 'pc_announcements_274');
        
        $announcements = $this->get_active_announcements();
        
        if (empty($announcements)) {
            return '';
        }
        
        $output = '';
        $count = min(intval($atts['count']), count($announcements));
        $show_image = filter_var($atts['show_image'], FILTER_VALIDATE_BOOLEAN);
        $show_close = filter_var($atts['show_close'], FILTER_VALIDATE_BOOLEAN);
        $custom_class = sanitize_html_class($atts['class']);
        
        for ($i = 0; $i < $count; $i++) {
            $announcement = $announcements[$i];
            $output .= $this->render_announcement_html($announcement, $show_image, $show_close, $custom_class);
        }
        
        return $output;
    }
    
    /**
     * Render announcement as HTML string
     */
    private function render_announcement_html($announcement, $show_image = true, $show_close = true, $custom_class = '') {
        $title = esc_html($announcement->title);
        $message = wpautop(wp_kses_post($announcement->message));
        $image_url = esc_url($announcement->image_url);
        $banner_color = esc_attr($announcement->banner_color);
        $link_url = esc_url($announcement->link_url);
        $close_text = __('Close', 'pc-announcements-274');
        $class_names = array('pc-announcements-274-announcement');
        
        if (!empty($custom_class)) {
            $class_names[] = $custom_class;
        }
        
        $banner_style = '';
        if (!empty($banner_color) && $banner_color !== '#0d47a1') {
            $banner_style = 'style="background: ' . $banner_color . ';"';
        }
        
        $has_link = !empty($link_url);
        $link_attrs = $has_link ? 'href="' . $link_url . '" target="_blank" rel="noopener noreferrer"' : '';
        
        $html = '<div class="' . implode(' ', $class_names) . '" data-announcement-id="' . $announcement->id . '" ' . $banner_style . '>';
        $html .= '<div class="pc-announcements-274-container">';
        $html .= '<div class="pc-announcements-274-content">';
        
        if ($has_link) {
            $html .= '<a class="pc-announcements-274-link" ' . $link_attrs . '>';
        }
        
        if ($show_image && !empty($image_url)) {
            $html .= '<div class="pc-announcements-274-image">';
            $html .= '<img src="' . $image_url . '" alt="' . esc_attr($title) . '" loading="lazy">';
            $html .= '</div>';
        }
        
        $html .= '<div class="pc-announcements-274-text">';
        
        if (!empty($title)) {
            $html .= '<h3 class="pc-announcements-274-title">' . $title . '</h3>';
        }
        
        if (!empty(trim($message))) {
            $html .= '<div class="pc-announcements-274-message">' . $message . '</div>';
        }
        
        $html .= '</div>';
        
        if ($has_link) {
            $html .= '</a>';
        }
        
        $html .= '</div>';
        
        if ($show_close && !$has_link) {
            $html .= '<button class="pc-announcements-274-close" aria-label="' . esc_attr($close_text) . '">';
            $html .= '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">';
            $html .= '<path d="M18 6L6 18M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>';
            $html .= '</svg>';
            $html .= '</button>';
        }
        
        $html .= '</div>';
        $html .= '</div>';
        
        return $html;
    }
}