<?php //Custom Post :: Sponsors

function custom_post_type_sponsor(){
    $labels = array(
        'name'                => __('Sponsors', 'kipya' ),
        'add_new_item'        => __( 'Add New Sponsor', 'kipya' ),
        'add_new'             => __( 'Add New Sponsor', 'kipya' ),
        'edit_item'           => __( 'Edit Sponsor', 'kipya' ),
        'update_item'         => __( 'Update Sponsor', 'kipya' ),
        'all_items'           => __( 'Sponsors', 'kipya' ),
        'search_items'        => __( 'Search ', 'kipya' ),
        'singular_name'       => __('Sponsor'),
    );
    $supports = array(
        'title',        // Post title
        'excerpt',      // Allows short description
        'editor',      // Allows full description
        'thumbnail',    // Allows feature images

    );
    $args = array(
        'labels'              => $labels,
        'description'         => 'For all Sponsors', 
        'supports'            => $supports,
        'hierarchical'        => false, 
        'public'              => true,  // Makes the post type public
        'show_ui'             => true,  // Displays an interface for this post type
        'show_in_menu'        => true,  // Displays in the Admin Menu (the left panel)
        'show_in_admin_bar'   => true,  // Displays in the black admin bar
        'menu_position'       => 10,     // The position number in the left menu
        'menu_icon'           => 'dashicons-filter',  
        'can_export'          => true,  // Allows content export using Tools -> Export
        'has_archive'         => true,  // Enables post type archive (by month, date, or year)
        'exclude_from_search' => false, 
        'capability_type'     => 'post', // Allows read, edit, delete like “Post”
    );
    register_post_type('sponsor', $args);

    // Register meta boxes individually
    add_action('add_meta_boxes_sponsor', 'add_custom_meta_boxes_sponsors');

    //Adding Category
    $taxonomy_labels = array(
        'name'              => _x('Sponsor Categories', 'taxonomy general name'),
        'singular_name'     => _x('Sponsor Category', 'taxonomy singular name'),
        'search_items'      => __('Search Sponsor Categories'),
        'all_items'         => __('All Sponsor Categories'),
        'edit_item'         => __('Edit Sponsor Category'),
        'update_item'       => __('Update Sponsor Category'),
        'add_new_item'      => __('Add New Sponsor Category'),
        'new_item_name'     => __('New Sponsor Category Name'),
        'menu_name'         => __('Sponsor Categories'),
    );
    $taxonomy_args = array(
        'hierarchical'      => true, 
        'labels'            => $taxonomy_labels,
        'show_ui'           => true,
        'show_in_rest'      => true, 
        'query_var'         => true,
        'rewrite'           => array('slug' => 'sponsor-category'),
    );
    register_taxonomy('sponsor_category', 'sponsor', $taxonomy_args);
}
add_action('init', 'custom_post_type_sponsor');

//Add Custom Meta Boxes on sponsor
function add_custom_meta_boxes_sponsors() {
    add_meta_box('sponsors_details', 'Sponsor Details', 'render_custom_meta_box_sponsors', 'sponsor', 'normal', 'high');
}

// Render custom meta boxes
function render_custom_meta_box_sponsors($post) {
    // Get existing values
	$post_id    = $post->ID;
    $project   = get_post_meta($post->ID, '_project', true);
    $website    = get_post_meta($post->ID, '_website', true);

    // Output fields
    ?>
    <div class="row">
        <div class="col-md-12 mb-3">
            <label for="project"><b>Project Name (Optional)</b></label><br/>
            <input type="text" id="project" name="project" style="width: 100%;" value="<?= esc_attr($project); ?>">
        </div>
        <div class="col-md-12 mb-3">
            <label for="link" class="form-label"><b>Sponsor Website</b></label><br/>
            <input type="text" id="link" name="website" style="width: 100%" value="<?= esc_attr($website); ?>" placeholder="https://www.example.com">
        </div>
    </div>
    <?php
}

// Save custom meta box data
function save_custom_meta_box_sponsors($post_id) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;

    // Save custom fields
    // Define an array of field names
    $fields = array('project',  'website');
    foreach ($fields as $field) {
        // Check if the field key is set in $_POST
        if (isset($_POST[$field])) {
            // If set, update post meta
            if ($field === 'project') {
                update_post_meta($post_id, '_' . $field, wp_kses_post($_POST[$field]));
            } else {
                update_post_meta($post_id, '_' . $field, sanitize_text_field($_POST[$field]));
            }
        } else {
            // If not set, handle accordingly (you can leave it empty or provide a default value)
            update_post_meta($post_id, '_' . $field, ''); // Setting it to an empty string in this case
        }
    }
}

add_action('add_meta_boxes', 'add_custom_meta_boxes_sponsors');
add_action('save_post', 'save_custom_meta_box_sponsors');




/** =============================================================
 * ADMIN DASHBOARD
 *==============================================================*/
// Add custom columns to the sponsor post type - DASHBOARD
function add_custom_columns_to_sponsor($columns) {
    $new_columns = array(
        'cb' => $columns['cb'],
        'photo' => __('Photo'),
        'title' => __('Name'),
        'project' => __('Project'),
        'sponsor_category' => __('Category'),
    );    
    return $new_columns;
}
add_filter('manage_sponsor_posts_columns', 'add_custom_columns_to_sponsor');


// Populate custom columns with data
function populate_custom_sponsor_columns($column, $post_id) {
    switch ($column) {
        case 'photo':
            // Display the featured image
            $photo_url = get_the_post_thumbnail_url($post_id, 'thumbnail'); // You can adjust the image size ('thumbnail', 'medium', 'large', 'full')
            if ($photo_url) {
                echo '<img src="' . esc_url($photo_url) . '" alt="Photo" style="max-height: 50px; width: auto;" />';
            } else {
                echo 'No photo available';
            }
            break;        

        case 'title':
            // Display the start date
            $title = get_post_meta($post_id, 'title', true);
            echo esc_html($title);
            break;

        case 'project':
            // Display the end date
            $position = get_post_meta($post_id, '_project', true);
            echo esc_html($position);
            break;

        case 'sponsor_category':
            // Display the sponsor category
            $terms = wp_get_post_terms($post_id, 'sponsor_category'); 
            if (!empty($terms) && !is_wp_error($terms)) {
                $categories = array();
                foreach ($terms as $term) {
                    $categories[] = $term->name;
                }
                echo esc_html(implode(', ', $categories));
            } else {
                echo 'No category';
            }
            break;
    }
}
add_action('manage_sponsor_posts_custom_column', 'populate_custom_sponsor_columns', 10, 2);


/** =================================================================
 *  SHORTCODE - sponsor
 *===================================================================*/
function sponsor_shortcode($atts) {
    // Define shortcode attributes, if needed
    $atts = shortcode_atts(
        array(
            'category' => '', // Default to empty string if not specified
            'number' => 8, // Default number of posts per page
            'order' => 'ASC', //Default Descending order
            
        ),
        $atts,
        'sponsor'
    );

    // Custom query to retrieve sponsors
    $sponsors_args = array(
        'post_type' => 'sponsor',
        'posts_per_page' => $atts['number'], // Number of posts per page
        'orderby' => 'date', // Order by date
        'order' => $atts['order'], // order
    );

    // Check if category attribute is provided and not empty
    if (!empty($atts['category'])) {
        $sponsors_args['tax_query'] = array(
            array(
                'taxonomy' => 'sponsor_category',
                'field' => 'slug',
                'terms' => $atts['category'],
            ),
        );
    }

    $sponsors_query = new WP_Query($sponsors_args);

    ob_start();
    // Check if there are upcoming events
    if ($sponsors_query->have_posts()) :?>
<div class="row nngof-sponsors g-0">
  <?php
    while ($sponsors_query->have_posts()) : $sponsors_query->the_post();
        $post_id = get_the_ID();

        $project = get_post_meta(get_the_ID(), '_project', true);
        $website = get_post_meta(get_the_ID(), '_website', true);
        ?>
        <div class="col-xl-3 col-lg-3 col-sm-4 text-center">
            <a href="<?php echo esc_url($website); ?>" target="_blank" class="card-link"> <!-- Anchor tag with website link -->
                <div class="card mx-3 my-4 border-0" data-aos="fade-up">
                    <div class="post-thumbnail">
                        <?php 
                        // Display the post thumbnail
                        if (has_post_thumbnail()) {
                            the_post_thumbnail('small'); 
                        } else {
                            echo '<img src="'. get_template_directory_uri() .'/assets/images/photo-placeholder.jpg" alt="HADS" class="img-fluid"/>';
                        }
                        ?>
                    </div>
                </div><!-- card !-->
            </a> <!-- End anchor tag -->
        </div><!-- col !-->
  <?php
    endwhile;
    wp_reset_postdata();
  else :
    echo 'No sponsors found.';
  ?>
</div><!-- accordion !-->
        <?php
    endif;

    return ob_get_clean();
}

add_shortcode('sponsor', 'sponsor_shortcode');