<?php

// Register Success Stories Post Type
function pelere_register_success_stories() {
    $labels = array(
        'name'               => 'Success Stories',
        'singular_name'      => 'Success Story',
        'menu_name'          => 'Success Stories',
        'name_admin_bar'     => 'Success Story',
        'add_new'            => 'Add New',
        'add_new_item'       => 'Add New Success Story',
        'new_item'           => 'New Story',
        'edit_item'          => 'Edit Story',
        'view_item'          => 'View Story',
        'all_items'          => 'All Stories',
        'search_items'       => 'Search Stories',
        'not_found'          => 'No stories found.',
        'not_found_in_trash' => 'No stories found in Trash.'
    );

    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array('slug' => 'success-stories'),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => 20,
        'menu_icon'          => 'dashicons-testimonial',
        'supports'           => array('title', 'editor', 'thumbnail'),
        'taxonomies'         => array('story_category')
    );

    register_post_type('success_stories', $args);

    // Register Story Categories
    register_taxonomy(
        'story_category',
        'success_stories',
        array(
            'label' => 'Categories',
            'rewrite' => array('slug' => 'story-category'),
            'hierarchical' => true,
        )
    );
}
add_action('init', 'pelere_register_success_stories');

// Add Custom Meta Fields
function pelere_add_story_meta_boxes() {
    add_meta_box(
        'pelere_story_details',
        'Client Details',
        'pelere_story_meta_box_callback',
        'success_stories',
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'pelere_add_story_meta_boxes');

function pelere_story_meta_box_callback($post) {
    wp_nonce_field('pelere_save_story_data', 'pelere_story_meta_nonce');

    $name = get_post_meta($post->ID, '_pelere_story_name', true);
    $email = get_post_meta($post->ID, '_pelere_story_email', true);
    $phone = get_post_meta($post->ID, '_pelere_story_phone', true);
    $location = get_post_meta($post->ID, '_pelere_story_location', true);

    echo '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">';
    
    echo '<p><label for="pelere_story_name" style="display: block; margin-bottom: 5px; font-weight: bold;">Full Name</label>';
    echo '<input type="text" id="pelere_story_name" name="pelere_story_name" value="' . esc_attr($name) . '" style="width: 100%;" /></p>';

    echo '<p><label for="pelere_story_email" style="display: block; margin-bottom: 5px; font-weight: bold;">Email</label>';
    echo '<input type="email" id="pelere_story_email" name="pelere_story_email" value="' . esc_attr($email) . '" style="width: 100%;" /></p>';

    echo '<p><label for="pelere_story_phone" style="display: block; margin-bottom: 5px; font-weight: bold;">Phone</label>';
    echo '<input type="tel" id="pelere_story_phone" name="pelere_story_phone" value="' . esc_attr($phone) . '" style="width: 100%;" /></p>';

    echo '<p><label for="pelere_story_location" style="display: block; margin-bottom: 5px; font-weight: bold;">Location</label>';
    echo '<input type="text" id="pelere_story_location" name="pelere_story_location" value="' . esc_attr($location) . '" style="width: 100%;" /></p>';

    echo '</div>';
}

function pelere_save_story_data($post_id) {
    if (!isset($_POST['pelere_story_meta_nonce']) || !wp_verify_nonce($_POST['pelere_story_meta_nonce'], 'pelere_save_story_data')) {
        return;
    }

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }

    if (!current_user_can('edit_post', $post_id)) {
        return;
    }

    $fields = array('name', 'email', 'phone', 'location');
    foreach ($fields as $field) {
        if (isset($_POST['pelere_story_' . $field])) {
            update_post_meta($post_id, '_pelere_story_' . $field, sanitize_text_field($_POST['pelere_story_' . $field]));
        }
    }
}
add_action('save_post', 'pelere_save_story_data');

// Success Stories Shortcode
function pelere_success_stories_shortcode($atts) {
    $atts = shortcode_atts(array(
        'category' => '',
        'limit'    => -1,
        'columns'  => 3
    ), $atts);

    ob_start();

    $args = array(
        'post_type'      => 'success_stories',
        'posts_per_page' => $atts['limit'],
        'tax_query'      => array()
    );

    if (!empty($atts['category'])) {
        $args['tax_query'][] = array(
            'taxonomy' => 'story_category',
            'field'    => 'slug',
            'terms'    => $atts['category']
        );
    }

    $stories = new WP_Query($args);

    if ($stories->have_posts()) : ?>
        
        <?php
            while ($stories->have_posts()) : $stories->the_post();
                $name = get_post_meta(get_the_ID(), '_pelere_story_name', true);
                $location = get_post_meta(get_the_ID(), '_pelere_story_location', true);
        ?>
            <div class="row  mb-3" data-aos="fade-up">
                <div class="col-lg-2 col-sm-3 align-self-center">
                    <?php if (has_post_thumbnail()) : ?>
                        <div class="story-image">
                            <?php the_post_thumbnail('large', array('style' => 'width: 100%; height: 100%; object-fit: cover;')); ?>
                        </div>
                    <?php endif; ?>
                </div>
                <div class="col-lg-10 col-sm-9">
                    <h3 class="story-title"><?php the_title(); ?></h3>
                    <div class="story-content"><?php the_content(); ?></div>
                    <div class="story-meta mb-3" style="margin-top: 15px; font-size: 0.8em; color: #666;">
                        <?php if ($name) : ?>
                            <p style="margin: 0;"><strong>Client:</strong> <?php echo esc_html($name); ?></p>
                        <?php endif; ?>
                        
                        <?php if ($location) : ?>
                            <p style="margin:0;"><strong>Location:</strong> <?php echo esc_html($location); ?></p>
                        <?php endif; ?>
                    </div>
                </div><hr/>
            </div>

            <?php
        endwhile;
        
    else :
        echo '<p>No success stories found.</p>';
    endif;

    wp_reset_postdata();
    return ob_get_clean();
}
add_shortcode('success_stories', 'pelere_success_stories_shortcode');

//Sliding Success Stories on Home page
function pelere_home_stories_shortcode($atts) {
    $atts = shortcode_atts(array(
        'category' => '',
        'limit'    => 6,
        'autoplay' => 'true',
        'interval' => 5000
    ), $atts);

    ob_start();

    $args = array(
        'post_type'      => 'success_stories',
        'posts_per_page' => $atts['limit'],
        'tax_query'      => array()
    );

    if (!empty($atts['category'])) {
        $args['tax_query'][] = array(
            'taxonomy' => 'story_category',
            'field'    => 'slug',
            'terms'    => $atts['category']
        );
    }

    $stories = new WP_Query($args);

    if ($stories->have_posts()) : ?>
        <div class="pelere-stories-carousel" 
             data-autoplay="<?php echo esc_attr($atts['autoplay']); ?>"
             data-interval="<?php echo esc_attr($atts['interval']); ?>">
            <div class="pelere-stories-track">
                <?php while ($stories->have_posts()) : $stories->the_post();
                    $name = get_post_meta(get_the_ID(), '_pelere_story_name', true);
                    $location = get_post_meta(get_the_ID(), '_pelere_story_location', true);
                ?>
                    <div class="home-story-card justify-content-evenly">
                        <h3><?php the_title(); ?></h3>
                        <div class="home-story-content"><?php the_excerpt(); ?></div>
                        <div class="d-flex bd-highlight">
                            <div class="bd-highlight p-1">
                                <?php if (has_post_thumbnail()) : ?>
                                    <div class="home-story-image">
                                        <?php the_post_thumbnail('thumbnail'); ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="bd-highlight p-1 home-story-meta">
                                <?php if ($name) : ?>
                                    <p style="margin:0;"><strong>Client:</strong> <?php echo esc_html($name); ?></p>
                                <?php endif; ?>
                                <?php if ($location) : ?>
                                    <p style="margin:0;"><strong>Location:</strong> <?php echo esc_html($location); ?></p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endwhile; ?>
            </div>
            <div class="pelere-stories-dots"></div>
        </div>
    <?php else : ?>
        <p>No success stories found.</p>
    <?php endif;

    wp_reset_postdata();
    return ob_get_clean();
}
add_shortcode('home_stories', 'pelere_home_stories_shortcode');
