<?php
/*-----------------------------------------------------------------------------------*/
/*  EXTHEM.ES
/*  PREMIUM WORDRESS THEMES
/*
/*  STOP DON'T TRY EDIT
/*  IF YOU DON'T KNOW PHP 
/*
/*-----------------------------------------------------------------------------------*/
 

// Add the meta box
add_action( 'add_meta_boxes', 'custom_file_repeater_meta_box' );
function custom_file_repeater_meta_box() {
    add_meta_box(
        'file_repeater_meta_box',
        'Download Link Box',
        'display_file_repeater_meta_box',
        ['post'], // Change to your post types
        'normal',
        'high'
    );
}

// Display the meta box with repeater
function display_file_repeater_meta_box( $post ) {
    wp_nonce_field( 'file_repeater_nonce', 'file_repeater_nonce_field' );
    $repeater_data = get_post_meta( $post->ID, '_file_repeater_data', true ) ?: [];
	

    // Enqueue WordPress media uploader scripts
    wp_enqueue_media();

    echo '<div id="file-repeater-container" class="admin-inside-box clearfix"><div class="aps-wrap">';
	?>
	
		<ul class="aps-data-tabs"> 
	
		<li class="active" data-tab="#apes-tb-download">Download Link</li>  
		 
		</ul>
		
		<div id="apes-tb-download" class="aps-tab-content active">
		<div class="aps-group-inputs"> 
		
		<ul id="sort_table" class="ui-sortable"> 
	<?php
    foreach ( $repeater_data as $index => $row ) {
        $file_id = ! empty( $row['file_id'] ) ? $row['file_id'] : '';
        $file_url = $file_id ? wp_get_attachment_url( $file_id ) : '';
        $title = ! empty( $row['title'] ) ? esc_attr( $row['title'] ) : '';
        ?>

	 
	
        <div class="repeater-row" style="border: 1px solid #ddd; padding: 10px; margin-bottom: 10px;">
            <p>
                <label>Title:</label><br>
                <input type="text" name="file_repeater[<?php echo $index; ?>][title]" value="<?php echo $title; ?>" placeholder="e.g., User Manual" style="width: 50%;" />
            </p>
            <p>
                <label>File:</label><br>
                <input type="hidden" name="file_repeater[<?php echo $index; ?>][file_id]" class="file-id" value="<?php echo esc_attr( $file_id ); ?>">
                <input type="text" class="file-url" value="<?php echo esc_url( $file_url ); ?>" readonly style="width: 50%;">
                <button type="button" class="upload-file-button button">Upload File</button>
                <button type="button" class="remove-file-button button" <?php echo $file_id ? '' : 'style="display:none;"'; ?>>Remove File</button>
            </p>
            <button type="button" class="remove-row-button button">Remove Row</button>
        </div>
        <?php
    }
	?>
        </ul>
        </div>
        </div>
	<?php
    echo '</div></div>';
    echo '<button type="button" id="add-repeater-row" class="button">Add Document</button>';

    // JavaScript for repeater and file upload
    ?>
    <script>
    jQuery(document).ready(function($) {
        // Add new repeater row
        $('#add-repeater-row').click(function() {
            var index = $('.repeater-row').length;
            var row = `
                <div class="repeater-row" style="border: 1px solid #ddd; padding: 10px; margin-bottom: 10px;">
                    <p>
                        <label>Title:</label><br>
                        <input type="text" name="file_repeater[${index}][title]" placeholder="e.g., User Manual" style="width: 50%;">
                    </p>
                    <p>
                        <label>File:</label><br>
                        <input type="hidden" name="file_repeater[${index}][file_id]" class="file-id">
                        <input type="text" class="file-url" readonly style="width: 50%;">
                        <button type="button" class="upload-file-button button">Upload File</button>
                        <button type="button" class="remove-file-button button" style="display:none;">Remove File</button>
                    </p>
                    <button type="button" class="remove-row-button button">Remove Row</button>
                </div>`;
            $('#file-repeater-container').append(row);
        });

        // Remove repeater row
        $(document).on('click', '.remove-row-button', function() {
            $(this).closest('.repeater-row').remove();
        });

        // File upload handler
        $(document).on('click', '.upload-file-button', function(e) {
            e.preventDefault();
            var $button = $(this);
            var $row = $button.closest('.repeater-row');
            var $file_id_input = $row.find('.file-id');
            var $file_url_input = $row.find('.file-url');

            var uploader = wp.media({
                title: 'Select File',
                button: { text: 'Select File' },
                multiple: false,
				/* 
                library: { type: ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip'] } // Restrict file types
				 */
            }).on('select', function() {
                var attachment = uploader.state().get('selection').first().toJSON();
                $file_id_input.val(attachment.id);
                $file_url_input.val(attachment.url);
                $button.siblings('.remove-file-button').show();
            }).open();
        });

        // Remove file
        $(document).on('click', '.remove-file-button', function() {
            var $row = $(this).closest('.repeater-row');
            $row.find('.file-id').val('');
            $row.find('.file-url').val('');
            $(this).hide();
        });
    });
    </script>
    <?php
}

// Save the repeater data
add_action( 'save_post', 'save_file_repeater_meta_box' );
function save_file_repeater_meta_box( $post_id ) {
    // Security checks
    if ( ! isset( $_POST['file_repeater_nonce_field'] ) || ! wp_verify_nonce( $_POST['file_repeater_nonce_field'], 'file_repeater_nonce' ) ) {
        return;
    }
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }
    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        return;
    }

    // Sanitize and save repeater data
    $repeater_data = isset( $_POST['file_repeater'] ) ? (array) $_POST['file_repeater'] : [];
    $sanitized_data = [];
    foreach ( $repeater_data as $index => $row ) {
        $sanitized_data[ $index ] = [
            'title'   => isset( $row['title'] ) ? sanitize_text_field( $row['title'] ) : '',
            'file_id' => isset( $row['file_id'] ) ? absint( $row['file_id'] ) : ''
        ];
    }
    update_post_meta( $post_id, '_file_repeater_data', $sanitized_data );
}
