<?php
// Custom Post Type :: DOWNLOADS (Enhanced Version)

// Register custom taxonomy for file categories
function custom_post_type_downloads() {
    $labels = array(
        'name'                => __('Downloads', 'kipya'),
        'add_new_item'        => __('New Download', 'kipya'),
        'add_new'             => __('New Download', 'kipya'),
        'edit_item'           => __('Edit Download', 'kipya'),
        'update_item'         => __('Update Download', 'kipya'),
        'all_items'           => __('All Downloads', 'kipya'),
        'search_items'        => __('Search', 'kipya'),
        'singular_name'       => __('Download'),
        'not_found'           => __('No downloads found.', 'kipya'),
        'not_found_in_trash'  => __('No downloads found in Trash.', 'kipya')
    );

    $supports = array(
        'title',
        'editor',
        'thumbnail',
        'excerpt'
    );

    $args = array(
        'labels'              => $labels,
        'description'         => 'For all Downloads and Publications',
        'supports'            => $supports,
        'hierarchical'        => false,
        'public'              => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'show_in_admin_bar'   => true,
        'menu_position'       => 7,
        'menu_icon'           => 'dashicons-download',
        'can_export'          => true,
        'has_archive'         => true,
        'exclude_from_search' => false,
        'capability_type'     => 'post',
    );
    register_post_type('downloads', $args);  
    register_file_taxonomy();
}
add_action('init', 'custom_post_type_downloads');

function register_file_taxonomy() {
    $args = array(
        'hierarchical'      => true,
        'labels'            => array(
            'name'              => _x('File Categories', 'taxonomy general name'),
            'singular_name'     => _x('File Category', 'taxonomy singular name'),
            'search_items'      => __('Search File Categories'),
            'all_items'         => __('All File Categories'),
            'parent_item'       => __('Parent File Category'),
            'parent_item_colon' => __('Parent File Category:'),
            'edit_item'         => __('Edit File Category'),
            'update_item'       => __('Update File Category'),
            'add_new_item'      => __('Add New File Category'),
            'new_item_name'     => __('New File Category Name'),
            'menu_name'         => __('File Categories'),
        ),
        'show_ui'           => true,
        'show_admin_column' => true,
        'query_var'         => true,
        'rewrite'           => array('slug' => 'file-category'),
    );
    register_taxonomy('file_category', array('downloads'), $args);
}

// Add custom meta boxes for Downloads
function add_custom_meta_boxes_downloads() {
    add_meta_box(
        'file_info_meta_box',
        'Publication Details',
        'render_file_info_meta_box',
        'downloads',
        'normal',
        'high'
    );
    
    add_meta_box(
        'file_stats_meta_box',
        'File Statistics',
        'render_file_stats_meta_box',
        'downloads',
        'side',
        'default'
    );
}
add_action('add_meta_boxes_downloads', 'add_custom_meta_boxes_downloads');

// Render main publication details meta box
function render_file_info_meta_box($post) {

    
    // Get existing values
    $authors = get_post_meta($post->ID, '_publication_authors', true);
    $publish_date = get_post_meta($post->ID, '_publication_date', true);
    $publisher = get_post_meta($post->ID, '_publication_publisher', true);
    $isbn = get_post_meta($post->ID, '_publication_isbn', true);
    $doi = get_post_meta($post->ID, '_publication_doi', true);
    $pages = get_post_meta($post->ID, '_publication_pages', true);
    $language = get_post_meta($post->ID, '_publication_language', true);
    $file_url = get_post_meta($post->ID, '_file_url', true);
    $external_file = get_post_meta($post->ID, '_external_file', true);
    $file_upload = get_post_meta($post->ID, '_file_upload', true);
    
    // Get the file size
    $file_size = '';
    if ($file_url) {
        $headers = get_headers($file_url, 1);
        $file_size = isset($headers['Content-Length']) ? size_format($headers['Content-Length']) : '';
    }

    // Include nonce field for security
    wp_nonce_field('custom_file_info_nonce', 'file_info_nonce');
    
     // Increment download count on file download
    increment_download_count($post->ID);

    // Output HTML for the fields
    ?>
    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
        <div>
            <p>
                <label for="publication_authors"><strong>Author(s):</strong></label><br>
                <input type="text" id="publication_authors" name="publication_authors" style="width: 100%;" 
                       value="<?= esc_attr($authors); ?>" placeholder="Separate multiple authors with commas">
            </p>
            
            <p>
                <label for="publication_date"><strong>Publication Date *:</strong></label><br>
                <input type="date" id="publication_date" name="publication_date" style="width: 100%;" 
                       value="<?= esc_attr($publish_date); ?>" required>
            </p>
            
            <p>
                <label for="publication_publisher"><strong>Publisher/Organization:</strong></label><br>
                <input type="text" id="publication_publisher" name="publication_publisher" style="width: 100%;" 
                       value="<?= esc_attr($publisher); ?>">
            </p>
            
            <p>
                <label for="publication_language"><strong>Language:</strong></label><br>
                <input type="text" id="publication_language" name="publication_language" style="width: 100%;" 
                       value="<?= esc_attr($language); ?>" placeholder="English, French, etc.">
            </p>
        </div>
        
        <div>
            <p>
                <label for="publication_isbn"><strong>ISBN/ISSN:</strong></label><br>
                <input type="text" id="publication_isbn" name="publication_isbn" style="width: 100%;" 
                       value="<?= esc_attr($isbn); ?>">
            </p>
            
            <p>
                <label for="publication_doi"><strong>DOI:</strong></label><br>
                <input type="text" id="publication_doi" name="publication_doi" style="width: 100%;" 
                       value="<?= esc_attr($doi); ?>">
            </p>
            
            <p>
                <label for="publication_pages"><strong>Number of Pages:</strong></label><br>
                <input type="number" id="publication_pages" name="publication_pages" style="width: 100%;" 
                       value="<?= esc_attr($pages); ?>">
            </p>
            
            <p>
                <label for="file_upload"><strong>File Upload:</strong></label><br>
                <input type="text" id="file_upload" name="file_upload" style="width: 80%;" 
                       value="<?= esc_attr($file_upload); ?>" />
                <button type="button" id="upload_button" class="button">Upload</button>
                <input type="hidden" id="file_url" name="file_url" value="<?= esc_attr($file_url); ?>" />
                <?php if ($file_url): ?>
                    <div style="margin-top: 5px;">
                        <a href="<?= esc_attr($file_url); ?>" target="_blank">View Current File</a>
                        <?= $file_size ? ' ('.esc_html($file_size).')' : '' ?>
                    </div>
                <?php endif; ?>
            </p>
            
            <p>
                <label for="external_file"><strong>KOHA URL:</strong></label><br>
                <input type="text" id="external_file" name="external_file" style="width: 100%;" 
                       value="<?= esc_attr($external_file); ?>" placeholder="Alternative to direct upload">
            </p>
        </div>
    </div>
    
    <script>
        jQuery(document).ready(function($){
            var fileFrame;

            $('#upload_button').on('click', function(event) {
                event.preventDefault();

                if (fileFrame) {
                    fileFrame.open();
                    return;
                }

                fileFrame = wp.media.frames.fileFrame = wp.media({
                    title: 'Choose File',
                    button: { text: 'Choose File' },
                    multiple: false
                });

                fileFrame.on('select', function() {
                    var attachment = fileFrame.state().get('selection').first().toJSON();
                    $('#file_upload').val(attachment.url);
                    $('#file_url').val(attachment.url);
                });

                fileFrame.open();
            });
        });
    </script>
    <?php
}

// Render file statistics meta box
function render_file_stats_meta_box($post) {
    $download_count = get_post_meta($post->ID, '_download_count', true);
    $download_count = empty($download_count) ? 0 : intval($download_count);
    $last_download = get_post_meta($post->ID, '_last_download_date', true);
    ?>
    <p>
        <strong>Download Count:</strong><br>
        <input type="text" value="<?= esc_attr($download_count); ?>" readonly style="width: 100%;">
    </p>
    <p>
        <strong>Last Downloaded:</strong><br>
        <input type="text" value="<?= $last_download ? esc_attr(date('F j, Y', strtotime($last_download))) : 'Never'; ?>" readonly style="width: 100%;">
    </p>
    <?php
}

// Save all custom fields
function save_custom_meta_boxes_downloads($post_id) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;
   
	// Save file URL
    if (isset($_POST['file_url'])) {
        update_post_meta($post_id, '_file_url', esc_url_raw($_POST['file_url']));
    }

    // Save external file URL
    if (isset($_POST['external_file'])) {
        update_post_meta($post_id, '_external_file', esc_url_raw($_POST['external_file']));
    }
    
    // Save download count
    if (isset($_POST['download_count'])) {
        update_post_meta($post_id, '_download_count', intval($_POST['download_count']));
    }
	
	
	// Define an array of field names
    $fields = array('publication_date', 'publication_authors','publication_isbn', 'publication_doi', 'publication_pages', 'publication_language', 'publication_publisher');
    foreach ($fields as $field) {
        // Check if the field key is set in $_POST
        if (isset($_POST[$field])) {
            // If set, update post meta
            if ($field === 'publication_date') {
                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('save_post_downloads', 'save_custom_meta_boxes_downloads');

// Increment download count and update last download date
function increment_download_count($post_id) {
    $download_count = get_post_meta($post_id, '_download_count', true);
    $download_count = empty($download_count) ? 1 : intval($download_count) + 1;
    update_post_meta($post_id, '_download_count', $download_count);
    update_post_meta($post_id, '_last_download_date', current_time('mysql'));
}

// Add custom columns to Downloads admin list
function add_custom_columns_to_downloads($columns) {
    $new_columns = array(
        'cb' => $columns['cb'],
        'photo' => __('Thumbnail'),
        'title' => __('Title'),
        'authors' => __('Author(s)'),
        'publish_date' => __('Published'),
        'file_size' => __('Size'),
        'download_count' => __('Downloads'),
        'file_categories' => __('Categories'),
        'date' => __('Added'),
    );
    return $new_columns;
}
add_filter('manage_downloads_posts_columns', 'add_custom_columns_to_downloads');

// Populate custom columns
function populate_custom_columns_in_downloads($column, $post_id) {
    switch ($column) {
        case 'photo':
            $photo_url = get_the_post_thumbnail_url($post_id, 'thumbnail');
            echo $photo_url ? '<img src="'.esc_url($photo_url).'" style="max-width:40px;height:40px;">' : '—';
            break;
            
        case 'authors':
            $authors = get_post_meta($post_id, '_publication_authors', true);
            echo $authors ? esc_html($authors) : '—';
            break;
            
        case 'publish_date':
            $date = get_post_meta($post_id, '_publication_date', true);
            echo $date ? esc_html(date('M j, Y', strtotime($date))) : '—';
            break;
            
        case 'file_size':
            $file_url = get_post_meta($post_id, '_file_url', true);
            if ($file_url) {
                $headers = get_headers($file_url, 1);
                echo isset($headers['Content-Length']) ? esc_html(size_format($headers['Content-Length'])) : '—';
            } else {
                echo '—';
            }
            break;
            
        case 'download_count':
            $count = get_post_meta($post_id, '_download_count', true);
            echo $count ? esc_html($count) : '0';
            break;
            
        case 'file_categories':
            $terms = get_the_terms($post_id, 'file_category');
            if ($terms && !is_wp_error($terms)) {
                $term_names = wp_list_pluck($terms, 'name');
                echo esc_html(implode(', ', $term_names));
            } else {
                echo '—';
            }
            break;
    }
}
add_action('manage_downloads_posts_custom_column', 'populate_custom_columns_in_downloads', 10, 2);

// Make custom columns sortable
function make_downloads_columns_sortable($columns) {
    $columns['publish_date'] = 'publish_date';
    $columns['download_count'] = 'download_count';
    return $columns;
}
add_filter('manage_edit-downloads_sortable_columns', 'make_downloads_columns_sortable');

// Handle custom column sorting
function handle_downloads_column_sorting($query) {
    if (!is_admin() || !$query->is_main_query()) return;
    
    $orderby = $query->get('orderby');
    
    if ('publish_date' === $orderby) {
        $query->set('meta_key', '_publication_date');
        $query->set('orderby', 'meta_value');
    } elseif ('download_count' === $orderby) {
        $query->set('meta_key', '_download_count');
        $query->set('orderby', 'meta_value_num');
    }
}
add_action('pre_get_posts', 'handle_downloads_column_sorting');


/** =================================================================
 *  SHORTCODE - PUBLICATIONS
 *===================================================================*/
function downloads_shortcode($atts) {
    // Define shortcode attributes
    $atts = shortcode_atts(
        array(
            'category' => '', // Default to empty string if not specified
            'number' => 10, // Default number of posts per page
            'order' => 'DESC', // Default Descending order
        ),
        $atts,
        'downloads'
    );

    // Custom query to retrieve Downloads
    $downloads_args = array(
        'post_type' => 'downloads',
        'posts_per_page' => $atts['number'],
        'orderby' => 'date',
        'order' => $atts['order'],
    );

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

    $downloads_query = new WP_Query($downloads_args);

    // Start output buffer
    ob_start();
    
    ?>

    <div class="row publications">
        <div class="col-md-12">
            <div class="table-responsive "><table id="downloads-table" class="table expandable-table w-100 dataTable no-footer" style="width: 100%">
                <thead>
                    <tr>
                        <th></th>
                        <th></th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // Loop through the downloads and output table rows
                    while ($downloads_query->have_posts()) : $downloads_query->the_post();
                    $post_id = get_the_ID();
						
                    $file_url       =  get_post_meta($post_id, '_file_url', true);
                    $file_size      =  get_post_meta($post_id, '_file_size', true);
                    $downloadCount = get_post_meta($post_id, '_download_count', true);
					$link		   = get_post_meta($post_id, '_external_file', true);				
					$publisherDate = get_post_meta($post_id, '_publication_date', true);
					$publisherName = get_post_meta($post_id, '_publication_publisher', true);
					$publisherAuthors = get_post_meta($post_id, '_publication_authors', true);
					$publisherIsban = get_post_meta($post_id, '_publication_isbn', true);
					$publisherDoi = get_post_meta($post_id, '_publication_doi', true);
					$publisherPages = get_post_meta($post_id, '_publication_pages', true);
					$publisherLanguage = get_post_meta($post_id, '_publication_language', true);
                    
                    // Get the file size
                    $file_size = '';
                    if ($file_url) {
                        $headers = get_headers($file_url, 1);
                        $file_size = isset($headers['Content-Length']) ? size_format($headers['Content-Length']) : '';
                    }
                        ?>
                        <tr>
                            <td width="25%">
                                <div class="pdf-thumbnail">
                					<?php // Display the post thumbnail
                						if (has_post_thumbnail()) {
                							the_post_thumbnail(); 
                						}else{
                							echo '<img src="'. get_template_directory_uri().'/assets/images/placeholder-image.jpg" alt="Afiego" class="img-fluid"/>';
                						}
                					?>
                				</div><!-- thumbnail !-->
                            </td>
                            <td width="58%" class="align-self-center">
                                <a href="<?= esc_url(get_permalink()); ?>"><h4 class="pub-title"><?php the_title(); ?></h4></a>
                                <div class="py-1"><small>Downloads: <?=     $downloadCount; ?> | Size: <?= $file_size; ?></small></div>
                                <h5 class="pub-summ">Overview</h5>
                                <div class="pub-desc"> <?php esc_html(the_content()); ?></div>
                                <div class="pub-link"><a href="<?= esc_url(get_permalink()); ?>">More about this publication </a></div> 
                            </td>
                            <td width="16%" class="align-self-center py-3">
                                <div class="pub-download"> 
									<?php if($file_url):?>
										<a href="<?= $file_url; ?>" target="_blank" onclick="updateDownloadCount(<?= $post_id; ?>)"> Download</button></a>
									<?php else:?>
										<a href="<?= $link; ?>" target="_blank"> Visit KOHA</button></a>
									<?php endif;?>
								</div>
                                    <script>
                                        function updateDownloadCount(post_id) {
                                            jQuery.ajax({
                                                type: 'POST',
                                                url: '<?php echo admin_url("admin-ajax.php"); ?>',
                                                data: {
                                                    action: 'update_download_count',
                                                    post_id: post_id
                                                },
                                                success: function(response) {
                                                    // Optionally handle success response
                                                    console.log('Download count updated successfully.');
                                                }
                                            });
                                        }
                                    </script>
                            </td><!-- download link  !-->
                        </tr>
                    <?php endwhile; ?>
                </tbody>
            </table></div>
        </div>
    </div>


   

    <?php
    // Clean output buffer and return content
    return ob_get_clean();
}
add_shortcode('publications', 'downloads_shortcode');


/** =================================================================
 *  SHORTCODE - PUBLICATIONS
 *===================================================================*/
function homeDownloads_shortcode($atts) {

    // Start output buffer
    ob_start();
    // Define shortcode attributes
    $atts = shortcode_atts(
        array(
            'category' => '', // Default to empty string if not specified
            'number' => 6, // Default number of posts per page
            'order' => 'DESC', // Default Descending order
        ),
        $atts,
        'downloads'
    );

    // Custom query to retrieve Downloads
    $downloads_args = array(
        'post_type' => 'downloads',
        'posts_per_page' => $atts['number'],
        'orderby' => 'date',
        'order' => $atts['order'],
    );

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

    $downloads_query = new WP_Query($downloads_args);?>
    
        <?php if ($downloads_query->have_posts()) : ?>
        <div class="row">
            <?php while ($downloads_query->have_posts()) : $downloads_query->the_post();
                $post_id = get_the_ID();
						
                    $file_url       =  get_post_meta($post_id, '_file_url', true);
                    $file_size      =  get_post_meta($post_id, '_file_size', true);
                    $downloadCount = get_post_meta($post_id, '_download_count', true);
					$link		   = get_post_meta($post_id, '_external_file', true);				
					$publisherDate = get_post_meta($post_id, '_publication_date', true);
					$publisherName = get_post_meta($post_id, '_publication_publisher', true);
					$publisherAuthors = get_post_meta($post_id, '_publication_authors', true);
					$publisherIsban = get_post_meta($post_id, '_publication_isbn', true);
					$publisherDoi = get_post_meta($post_id, '_publication_doi', true);
					$publisherPages = get_post_meta($post_id, '_publication_pages', true);
					$publisherLanguage = get_post_meta($post_id, '_publication_language', true);
                    
                    // Get the file size
                    $file_size = '';
                    if ($file_url) {
                        $headers = get_headers($file_url, 1);
                        $file_size = isset($headers['Content-Length']) ? size_format($headers['Content-Length']) : '';
                    }
                ?>
                <div class="col-lg-3 col-md-4 col-6 mb-3 kpy-home-downloads">
                    <div class="card card-body p-1 border-0" data-aos="fade-up">
                        <div class="pdf-thumbnail">
                			<?php // Display the post thumbnail
                				if (has_post_thumbnail()) {
                					the_post_thumbnail(); 
                				}else{
                					echo '<img src="'. get_template_directory_uri().'/assets/images/placeholder-image.jpg" alt="Afiego" class="img-fluid"/>';
                				}
                			?>
                		</div><!-- thumbnail !-->
                        <div class="py-1"><small style="font-size: 11px;"> 
                            <span class="badge bg-warning me-1"><?= $publisherDate ?></span>
                            <span class="badge bg-primary me-1"><?= $publisherAuthors ?></span>
                            <span class="badge bg-danger me-1"><?= $publisherIsban ?></span>
                        </small></div>
                        <a href="<?= esc_url(get_permalink()); ?>"><h4 class="pub-title"><?php the_title(); ?></h4></a>
                        <a href="<?= esc_url(get_permalink()); ?>" class="pub-link">More details </a>       
                        <script>
                            function updateDownloadCount(post_id) {
                                jQuery.ajax({
                                    type: 'POST',
                                    url: '<?php echo admin_url("admin-ajax.php"); ?>',
                                    data: {
                                        action: 'update_download_count',
                                        post_id: post_id
                                    },
                                    success: function(response) {
                                        // Optionally handle success response
                                            console.log('Download count updated successfully.');
                                        }
                                    });
                                }
                        </script>
                    </div><!-- card !-->
                </div><!-- col !-->
            <?php endwhile;
				wp_reset_postdata();
            else :
                echo 'No publications found.';
            endif;
            ?>
        </div><!-- Row !-->

    <?php
    // Clean output buffer and return content
    return ob_get_clean();
}
add_shortcode('home-publications', 'homeDownloads_shortcode');


/***=============================================================
 * SAVE Download Counts
*===============================================================*/
// Update download count via AJAX
add_action('wp_ajax_update_download_count', 'update_download_count_callback');
add_action('wp_ajax_nopriv_update_download_count', 'update_download_count_callback');
function update_download_count_callback() {
    $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
    if ($post_id > 0) {
        $download_count = get_post_meta($post_id, '_download_count', true);
        $download_count = empty($download_count) ? 1 : intval($download_count) + 1;
        update_post_meta($post_id, '_download_count', $download_count);
        echo 'success';
    } else {
        echo 'error';
    }
    wp_die();
}

