<?php
/**
 * Services Grid Shortcode - Updated Version with AOS
 */
if ( ! function_exists( 'kpy_services_grid_shortcode' ) ) {

    function kpy_services_grid_shortcode( $atts ) {

        $atts = shortcode_atts( [
            'category'      => 'service',
            'media_url'     => '',
            'media_type'    => '',
            'title'         => 'Our Services',
            'subtitle'      => 'We work with enterprises, organizations, and businesses from various industries.',
            'posts_per_page'=> 6,
        ], $atts, 'kpy_services_grid' );

        // DEBUG: Check if media_url is being passed
        $debug_info = '';
        if ( empty( $atts['media_url'] ) ) {
            $debug_info = '<!-- DEBUG: media_url is EMPTY. Please add media_url="your-image-url.jpg" to the shortcode -->';
        } else {
            $debug_info = '<!-- DEBUG: media_url = ' . esc_url( $atts['media_url'] ) . ' -->';
        }

        // Auto-detect media type
        $media_type = $atts['media_type'];
        if ( empty( $media_type ) && ! empty( $atts['media_url'] ) ) {
            $url_parts = parse_url( $atts['media_url'] );
            $path = $url_parts['path'] ?? '';
            $extension = strtolower( pathinfo( $path, PATHINFO_EXTENSION ) );
            
            $video_extensions = ['mp4', 'webm', 'ogg', 'mov', 'm4v'];
            $image_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'];
            
            if ( in_array( $extension, $video_extensions ) ) {
                $media_type = 'video';
            } elseif ( in_array( $extension, $image_extensions ) ) {
                $media_type = 'image';
            } else {
                $media_type = 'image'; // Default to image
            }
        }

        $query = new WP_Query( [
            'post_type'      => 'page',
            'posts_per_page' => intval( $atts['posts_per_page'] ),
            'orderby'        => 'date',
            'order'          => 'DESC',
            'tax_query'      => [
                [
                    'taxonomy' => 'page_category',
                    'field'    => 'slug',
                    'terms'    => array( sanitize_title( $atts['category'] ) ),
                ],
            ],
        ] );

        $pages = $query->posts;

        // Service icons mapping
        $service_icons = [
            'web hosting' => 'fas fa-server',
            'digital security' => 'fas fa-shield-alt',
            'app and software development' => 'fas fa-code',
            'seo and maintenance' => 'fas fa-chart-line',
            'domain' => 'fas fa-globe',
            'domains' => 'fas fa-globe',
            'web solution' => 'fas fa-laptop-code',
            'web solutions' => 'fas fa-laptop-code',
        ];

        $uid = 'kpy-sg-' . uniqid();
        wp_enqueue_style( 'font-awesome-6', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css', array(), '6.4.2' );

        ob_start();
        echo $debug_info;
        ?>
        <div class="kpy-sg-wrapper" id="<?php echo esc_attr( $uid ); ?>">

            <!-- Section Header -->
            <div class="kpy-sg-header" 
                 data-aos="fade-up" 
                 data-aos-duration="800" 
                 data-aos-offset="100">
                <div class="kpy-sg-title-container">
                    <div class="kpy-sg-title-bg" aria-hidden="true" 
                         data-aos="fade-right" 
                         data-aos-duration="600" 
                         data-aos-delay="100">
                        What We Do
                    </div>
                    <h2 class="kpy-sg-title">
                        <span class="kpy-sg-title-red" data-aos="zoom-in" data-aos-duration="600" data-aos-delay="200">Our</span>
                        <span class="kpy-sg-title-white" data-aos="zoom-in" data-aos-duration="600" data-aos-delay="300">Services</span>
                    </h2>
                </div>
            </div>

            <!-- Grid -->
            <div class="kpy-sg-grid">

                <!-- Hero Card with Media -->
                <div class="kpy-sg-card kpy-sg-card--hero" 
                     data-aos="fade-right" 
                     data-aos-duration="1000" 
                     data-aos-offset="150"
                     data-aos-easing="ease-out-cubic">
                    <?php if ( ! empty( $atts['media_url'] ) ) : ?>
                        <?php if ( $media_type === 'video' ) : ?>
                            <video
                                class="kpy-sg-media kpy-sg-video"
                                src="<?php echo esc_url( $atts['media_url'] ); ?>"
                                autoplay
                                loop
                                muted
                                playsinline
                                preload="auto"
                                data-aos="fade-in"
                                data-aos-duration="1200"
                            ></video>
                        <?php else : ?>
                            <img 
                                class="kpy-sg-media kpy-sg-image"
                                src="<?php echo esc_url( $atts['media_url'] ); ?>"
                                alt="Hero background"
                                loading="lazy"
                                data-aos="zoom-in"
                                data-aos-duration="1000"
                                data-aos-delay="100"
                            />
                        <?php endif; ?>
                    <?php else : ?>
                        <div class="kpy-sg-media kpy-sg-media--placeholder" data-aos="fade-in" data-aos-duration="800">
                            <?php if ( current_user_can( 'manage_options' ) ) : ?>
                                <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; color: white; background: rgba(0,0,0,0.7); padding: 20px; border-radius: 10px;">
                                    <p style="margin: 0; font-size: 14px;">⚠️ ADMIN NOTICE: Please add media_url parameter to the shortcode</p>
                                    <p style="margin: 5px 0 0; font-size: 12px;">Example: [kpy_services_grid media_url="https://your-site.com/image.jpg"]</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Overlay Content - Left Aligned -->
                    <div class="kpy-sg-hero-overlay">
                        <div class="kpy-sg-hero-content kpy-sg-hero-content--left"
                             data-aos="fade-up"
                             data-aos-duration="800"
                             data-aos-delay="300"
                             data-aos-offset="50">
                            <div class="kpy-sg-hero-icon" data-aos="zoom-in" data-aos-duration="500" data-aos-delay="400">
                                <i class="fas fa-cogs"></i>
                            </div>
                            <h3 class="kpy-sg-hero-title" data-aos="fade-up" data-aos-duration="600" data-aos-delay="500">Innovative Solutions</h3>
                            <p class="kpy-sg-hero-description" data-aos="fade-up" data-aos-duration="700" data-aos-delay="600">Transforming ideas into reality with cutting-edge technology, expert craftsmanship, and a passion for innovation. We build digital solutions that are powerful, intuitive, and designed to help your business succeed.</p>
                        </div>
                    </div>
                </div>

                <!-- Service Cards -->
                <?php if ( $pages ) : ?>
                    <?php foreach ( $pages as $index => $page ) : ?>
                        <?php
                        // Clean excerpt
                        if ( ! empty( $page->post_excerpt ) ) {
                            $excerpt = strip_shortcodes( $page->post_excerpt );
                            $excerpt = wp_strip_all_tags( $excerpt );
                        } else {
                            $excerpt = wp_trim_words( strip_shortcodes( $page->post_content ), 20, '...' );
                            $excerpt = wp_strip_all_tags( $excerpt );
                        }
                        
                        $link = get_permalink( $page->ID );
                        $name = strtolower( get_the_title( $page ) );
                        
                        // Determine icon
                        $icon_class = 'fas fa-cube';
                        foreach ( $service_icons as $service_name => $icon ) {
                            if ( strpos( $name, $service_name ) !== false ) {
                                $icon_class = $icon;
                                break;
                            }
                        }
                        
                        // Calculate animation delay based on index
                        $delay = 0.1 + ($index * 0.05);
                        ?>
                        <a href="<?php echo esc_url( $link ); ?>" 
                           class="kpy-sg-card kpy-sg-card--service"
                           data-aos="fade-up"
                           data-aos-duration="600"
                           data-aos-delay="<?php echo $delay * 1000; ?>"
                           data-aos-offset="50">
                            <div class="kpy-sg-card__glass-bg"></div>
                            <div class="kpy-sg-card__inner">
                                <div class="kpy-sg-icon-container" data-aos="zoom-in" data-aos-duration="400" data-aos-delay="<?php echo ($delay * 1000) + 100; ?>">
                                    <i class="<?php echo $icon_class; ?> kpy-sg-fa-icon"></i>
                                </div>
                                <span class="kpy-sg-card__name" data-aos="fade-up" data-aos-duration="400" data-aos-delay="<?php echo ($delay * 1000) + 200; ?>"><?php echo esc_html( get_the_title( $page ) ); ?></span>
                            </div>
                            
                            <!-- Excerpt Overlay (appears on hover) -->
                            <?php if ( ! empty( $excerpt ) ) : ?>
                                <div class="kpy-sg-card__excerpt-overlay">
                                    <div class="kpy-sg-card__excerpt-content">
                                        <?php echo esc_html( $excerpt ); ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                            
                            <!-- Red hover overlay -->
                            <div class="kpy-sg-card__red-overlay"></div>
                            <div class="kpy-sg-card__edge-highlight"></div>
                        </a>
                    <?php endforeach; ?>
                <?php else : ?>
                    <p class="kpy-sg-empty" data-aos="fade-up">No services found for category <em><?php echo esc_html( $atts['category'] ); ?></em>.</p>
                <?php endif; ?>

            </div>
        </div>

        <?php
        return ob_get_clean();
    }

    add_shortcode( 'kpy_services_grid', 'kpy_services_grid_shortcode' );
}

function services_cards_shortcode($atts = []) {
    // Shortcode attributes with defaults
    $atts = shortcode_atts([
        'posts_per_page' => 2,
        'cta_title' => 'We Will Help Your Business Growing',
        'cta_subtitle' => 'OUR SERVICES',
        'show_cta' => 'yes',
        'columns' => '3'
    ], $atts);
    
    ob_start();
    
    $args = array(
        'post_type'      => 'page',
        'posts_per_page' => intval($atts['posts_per_page']),
        'orderby'        => 'rand',
        'tax_query'      => [
            [
                'taxonomy' => 'page_category',
                'field'    => 'slug',
                'terms'    => 'service',
            ],
        ],
    );
    
    $query = new WP_Query($args);
    
    if ($query->have_posts()) :
        
        // Column class based on shortcode attribute
        $column_class = 'services-grid--cols-' . $atts['columns'];
        ?>
        
        <div class="services-grid <?php echo esc_attr($column_class); ?>" 
             data-aos="fade-up" 
             data-aos-duration="800" 
             data-aos-offset="100">
            
            <?php if ($atts['show_cta'] === 'yes') : ?>
            <!-- CTA CARD -->
            <div class="service-card cta-card" 
                 data-aos="fade-right" 
                 data-aos-duration="800" 
                 data-aos-offset="100"
                 data-aos-delay="100">
                <span class="small-title" data-aos="fade-up" data-aos-duration="500" data-aos-delay="200"><?php echo esc_html($atts['cta_subtitle']); ?></span>
                <h2 data-aos="fade-up" data-aos-duration="600" data-aos-delay="300"><?php echo esc_html($atts['cta_title']); ?></h2>
                <div class="cta-decoration" data-aos="zoom-in" data-aos-duration="500" data-aos-delay="400">
                    <span></span>
                    <span></span>
                    <span></span>
                </div>
            </div>
            <?php endif; ?>
            
            <?php 
            $delay_index = 1;
            while ($query->have_posts()) : $query->the_post();
                
                // Enhanced icon mapping with more keywords
                $title = get_the_title();
                $icon = $atts['default_icon'] ?? 'fa-solid fa-star';
                
                $icon_map = [
                    'identity' => 'fa-solid fa-pen-nib',
                    'graphic' => 'fa-solid fa-palette',
                    'logo' => 'fa-solid fa-trademark',
                    'marketing' => 'fa-solid fa-bullhorn',
                    'seo' => 'fa-solid fa-chart-line',
                    'social' => 'fa-solid fa-hashtag',
                    'cloud' => 'fa-solid fa-cloud',
                    'maintenance' => 'fa-brands fa-google-drive',
                    'workspace' => 'fa-brands fa-google',
                    'gemini' => 'fa-regular fa-message',
                    'education' => 'fa-solid fa-graduation-cap',
                    'ads' => 'fa-solid fa-ad',
                    'branding' => 'fa-solid fa-brush',
                    'web' => 'fa-solid fa-code',
                    'development' => 'fa-solid fa-laptop-code',
                    'ai' => 'fa-solid fa-microchip',
                    'security' => 'fa-solid fa-shield-haltered',
                    'support' => 'fa-solid fa-headset',
                    'analytics' => 'fa-solid fa-chart-simple'
                ];
                
                foreach ($icon_map as $keyword => $icon_class) {
                    if (stripos($title, $keyword) !== false) {
                        $icon = $icon_class;
                        break;
                    }
                }
                
                // Get custom excerpt or generate one
                $excerpt = get_the_excerpt();
                if (empty($excerpt)) {
                    $excerpt = wp_trim_words(get_the_content(), 10, '...');
                } else {
                    $excerpt = wp_trim_words($excerpt, 10, '...');
                }
                
                // Calculate animation delay
                $animation_delay = 0.15 + ($delay_index * 0.08);
                ?>
                
                <div class="service-card" 
                     data-aos="fade-up" 
                     data-aos-duration="700" 
                     data-aos-delay="<?php echo $animation_delay * 1000; ?>"
                     data-aos-offset="50"
                     style="animation-delay: <?php echo 0.05 + ($delay_index * 0.05); ?>s">
                    <div class="service-icon" data-aos="zoom-in" data-aos-duration="500" data-aos-delay="<?php echo ($animation_delay * 1000) + 100; ?>">
                        <i class="<?php echo esc_attr($icon); ?>" aria-hidden="true"></i>
                    </div>
                    
                    <h3 data-aos="fade-up" data-aos-duration="500" data-aos-delay="<?php echo ($animation_delay * 1000) + 200; ?>"><?php the_title(); ?></h3>
                    
                    <p data-aos="fade-up" data-aos-duration="600" data-aos-delay="<?php echo ($animation_delay * 1000) + 300; ?>"><?php echo esc_html($excerpt); ?></p>
                    
                    <a href="<?php the_permalink(); ?>" 
                       class="service-link"
                       data-aos="fade-up" 
                       data-aos-duration="400" 
                       data-aos-delay="<?php echo ($animation_delay * 1000) + 400; ?>">
                        Read More <i class="fa-solid fa-arrow-right" aria-hidden="true"></i>
                    </a>
                </div>
                
            <?php 
            $delay_index++;
            endwhile; 
            ?>
            
        </div>
        
        <?php
        wp_reset_postdata();
    else :
        echo '<p class="services-error" data-aos="fade-up">No services found. Please add pages with "service" category.</p>';
    endif;
    
    return ob_get_clean();
}
add_shortcode('services_cards', 'services_cards_shortcode');

// Optional: Register a second shortcode with different defaults
function featured_services_shortcode($atts = []) {
    $atts['cta_title'] = 'Transform Your Business Today';
    $atts['cta_subtitle'] = 'FEATURED SERVICES';
    $atts['posts_per_page'] = 3;
    $atts['columns'] = '4';
    
    return services_cards_shortcode($atts);
}
add_shortcode('featured_services', 'featured_services_shortcode');