<?php
/**
 * Media Upload Bridge for Tabular3
 * 
 * This file serves as a bridge between the WordPress media uploader and the DataTables Editor
 */

// Load WordPress
require_once('../../../wp-load.php');

// Check if user can upload files
if (!current_user_can('upload_files')) {
    wp_die('You do not have permission to upload files.');
}

// Check nonce
// $nonce = isset($_GET['nonce']) ? $_GET['nonce'] : '';
// if (!wp_verify_nonce($nonce, 'tabular3_nonce')) {
//    wp_die('Security check failed');
// }

// Get post ID if specified
$post_id = isset($_GET['post_id']) ? intval($_GET['post_id']) : 0;

// Include necessary media functions
require_once(ABSPATH . 'wp-admin/includes/image.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Select Media</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
            margin: 0;
            padding: 0;
        }
        .media-container {
            padding: 20px;
        }
        .media-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .media-items {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 15px;
        }
        .media-item {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: center;
            cursor: pointer;
        }
        .media-item img {
            max-width: 100%;
            height: auto;
            max-height: 100px;
        }
        .media-item.selected {
            border: 3px solid #2271b1;
            background-color: #f0f6fc;
        }
        .media-actions {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 15px;
            background: #fff;
            border-top: 1px solid #ddd;
            text-align: right;
        }
        .button {
            background: #2271b1;
            border: none;
            color: white;
            padding: 8px 16px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 14px;
            margin: 4px 2px;
            cursor: pointer;
            border-radius: 2px;
        }
        .button-secondary {
            background: #f6f7f7;
            border: 1px solid #2271b1;
            color: #2271b1;
        }
        .upload-ui {
            margin-bottom: 20px;
            padding: 20px;
            border: 2px dashed #ddd;
            text-align: center;
        }
        #file-input {
            display: none;
        }
        .progress-bar {
            height: 10px;
            background-color: #e0e0e0;
            margin-top: 10px;
            display: none;
        }
        .progress {
            height: 100%;
            width: 0;
            background-color: #2271b1;
            transition: width 0.3s;
        }
    </style>
    
    <?php
    // Include WordPress scripts
    wp_enqueue_media();
    wp_print_scripts(array('jquery'));
    ?>
</head>
<body>
    <div class="media-container">
        <div class="media-header">
            <h2>Select Media</h2>
            <div>
                <button class="button button-secondary" id="upload-button">Upload Files</button>
                <input type="file" id="file-input" multiple>
            </div>
        </div>
        
        <div class="upload-ui">
            <p>Drag files here or click "Upload Files" to upload</p>
            <div class="progress-bar">
                <div class="progress"></div>
            </div>
        </div>
        
        <div class="media-items" id="media-items">
            <?php
            // Display existing media
            $args = array(
                'post_type' => 'attachment',
                'post_mime_type' => 'image',
                'post_status' => 'inherit',
                'posts_per_page' => -1,
                'orderby' => 'date',
                'order' => 'DESC',
            );
            
            $query_images = new WP_Query($args);
            
            foreach ($query_images->posts as $image) {
                $thumb_url = wp_get_attachment_thumb_url($image->ID);
                $full_url = wp_get_attachment_url($image->ID);
                ?>
                <div class="media-item" data-id="<?php echo esc_attr($image->ID); ?>" data-url="<?php echo esc_url($full_url); ?>">
                    <img src="<?php echo esc_url($thumb_url); ?>" alt="<?php echo esc_attr($image->post_title); ?>">
                    <div><?php echo esc_html($image->post_title); ?></div>
                </div>
                <?php
            }
            ?>
        </div>
    </div>
    
    <div class="media-actions">
        <button class="button button-secondary" id="cancel-button">Cancel</button>
        <button class="button" id="select-button">Select</button>
    </div>
    
    <script>
        jQuery(document).ready(function($) {
            let selectedItems = [];
            
            // Handle item selection
            $(document).on('click', '.media-item', function() {
                const id = $(this).data('id');
                const url = $(this).data('url');
                
                if ($(this).hasClass('selected')) {
                    // Deselect
                    $(this).removeClass('selected');
                    selectedItems = selectedItems.filter(item => item.id !== id);
                } else {
                    // Select
                    $(this).addClass('selected');
                    selectedItems.push({
                        id: id,
                        url: url
                    });
                }
            });
            
            // Upload button click
            $('#upload-button').click(function() {
                $('#file-input').click();
            });
            
            // File input change
            $('#file-input').change(function(e) {
                if (e.target.files.length > 0) {
                    uploadFiles(e.target.files);
                }
            });
            
            // Drag and drop
            const dropZone = $('.upload-ui')[0];
            
            dropZone.addEventListener('dragover', function(e) {
                e.preventDefault();
                $(this).css('background-color', '#f0f6fc');
            });
            
            dropZone.addEventListener('dragleave', function(e) {
                e.preventDefault();
                $(this).css('background-color', '');
            });
            
            dropZone.addEventListener('drop', function(e) {
                e.preventDefault();
                $(this).css('background-color', '');
                
                if (e.dataTransfer.files.length > 0) {
                    uploadFiles(e.dataTransfer.files);
                }
            });
            
            // Upload files function
            function uploadFiles(files) {
                const progressBar = $('.progress-bar');
                const progress = $('.progress');
                
                progressBar.show();
                
                let filesProcessed = 0;
                const totalFiles = files.length;
                
                for (let i = 0; i < files.length; i++) {
                    const formData = new FormData();
                    formData.append('action', 'tabular3_handle_media_upload');
                    formData.append('nonce', '<?php echo wp_create_nonce('tabular3_nonce'); ?>');
                    formData.append('file', files[i]);
                    
                    $.ajax({
                        url: '<?php echo admin_url('admin-ajax.php'); ?>',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(response) {
                            filesProcessed++;
                            
                            // Update progress
                            const percentComplete = (filesProcessed / totalFiles) * 100;
                            progress.css('width', percentComplete + '%');
                            
                            if (response.success) {
                                // Add the uploaded image to the grid
                                const newItem = $(`
                                    <div class="media-item" data-id="${response.data.id}" data-url="${response.data.url}">
                                        <img src="${response.data.url}" alt="">
                                        <div>${files[i].name}</div>
                                    </div>
                                `);
                                
                                $('#media-items').prepend(newItem);
                            }
                            
                            if (filesProcessed === totalFiles) {
                                // Reset the progress bar
                                setTimeout(function() {
                                    progressBar.hide();
                                    progress.css('width', '0%');
                                }, 1000);
                            }
                        },
                        error: function() {
                            filesProcessed++;
                            alert('Error uploading file: ' + files[i].name);
                            
                            // Update progress even on error
                            const percentComplete = (filesProcessed / totalFiles) * 100;
                            progress.css('width', percentComplete + '%');
                            
                            if (filesProcessed === totalFiles) {
                                setTimeout(function() {
                                    progressBar.hide();
                                    progress.css('width', '0%');
                                }, 1000);
                            }
                        }
                    });
                }
            }
            
            // Select button click
            $('#select-button').click(function() {
                // Prepare data for parent window
                const ids = selectedItems.map(item => item.id);
                const urls = selectedItems.map(item => item.url);
                
                // Send data to parent window
                window.parent.postMessage({
                    attachmentIds: ids,
                    attachmentUrls: urls
                }, '*');
            });
            
            // Cancel button click
            $('#cancel-button').click(function() {
                window.parent.postMessage({
                    cancelled: true
                }, '*');
            });
        });
    </script>
</body>
</html>
