<?php
/**
 * WooCommerce Featured Attributes
 *
 * Add this code to your theme's functions.php file or as a custom plugin
 */

// Add Featured Attributes meta box to product edit screen
function add_featured_attributes_meta_box() {
    add_meta_box(
        'featured_attributes_meta_box',
        __('Featured Attributes',TEXT_DOMAIN),
        'featured_attributes_meta_box_callback',
        'product',
        'side'
    );
}
add_action('add_meta_boxes', 'add_featured_attributes_meta_box');

// Meta box callback function
function featured_attributes_meta_box_callback($post) {
    wp_nonce_field('featured_attributes_meta_box', 'featured_attributes_meta_box_nonce');

    // Get current featured attributes
    $featured_attributes = get_post_meta($post->ID, '_featured_attributes', true);
    if (!is_array($featured_attributes)) {
        $featured_attributes = array();
    }

    // Get all product attributes
    $product = wc_get_product($post->ID);
    $attributes = $product->get_attributes();

    if (empty($attributes)) {
        echo '<p>'.__('No attributes found for this product.',TEXT_DOMAIN).'</p>';
        return;
    }

    echo '<p>'.__('Select attributes to feature at the top of the product page:',TEXT_DOMAIN).'</p>';
    echo '<div style="max-height: 200px; overflow-y: auto;">';

    foreach ($attributes as $attribute_name => $attribute) {
        $attribute_label = urldecode(wc_attribute_label($attribute_name));
        $checked = in_array($attribute_name, $featured_attributes) ? 'checked' : '';

        echo '<label style="display: block; margin-bottom: 5px;">';
        echo '<input type="checkbox" name="featured_attributes[]" value="' . esc_attr($attribute_name) . '" ' . $checked . '> ';
        echo esc_html($attribute_label);
        echo '</label>';
    }

    echo '</div>';
}

// Save meta box data
function save_featured_attributes_meta_box_data($post_id) {
    // Check if our nonce is set
    if (!isset($_POST['featured_attributes_meta_box_nonce'])) {
        return;
    }

    // Verify that the nonce is valid
    if (!wp_verify_nonce($_POST['featured_attributes_meta_box_nonce'], 'featured_attributes_meta_box')) {
        return;
    }

    // If this is an autosave, we don't want to do anything
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }

    // Check the user's permissions
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }

    // Update the featured attributes meta
    $featured_attributes = isset($_POST['featured_attributes']) ? $_POST['featured_attributes'] : array();
    update_post_meta($post_id, '_featured_attributes', $featured_attributes);
}
add_action('save_post_product', 'save_featured_attributes_meta_box_data');
















// Add enctype to the form to support file uploads
add_action('woocommerce_edit_account_form_start', 'add_enctype_to_form');
function add_enctype_to_form() {
    echo '<script>
        document.addEventListener("DOMContentLoaded", function() {
            var form = document.querySelector("form.woocommerce-EditAccountForm");
            if (form) {
                form.setAttribute("enctype", "multipart/form-data");
            }
        });
    </script>';
}

// Add avatar upload field to WooCommerce account edit form
add_action('woocommerce_edit_account_form_start', 'add_avatar_upload_field');
function add_avatar_upload_field() {
    $user_id = get_current_user_id();
    $avatar_url = get_user_meta($user_id, 'custom_avatar', true);
    ?>
    <div class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
        <label for="avatar_upload"><?php _e('Profile Avatar', TEXT_DOMAIN); ?></label>
        <div class="avatar-upload-container">
            <?php if ($avatar_url): ?>
                <div class="current-avatar">
                    <img src="<?php echo esc_url($avatar_url); ?>" alt="Current Avatar" class="avatar-preview">
                    <button type="button" class="remove-avatar" data-user-id="<?php echo $user_id; ?>">
                        <span class="icon-x1"></span>
                    </button>
                </div>
            <?php endif; ?>

            <div class="avatar-preview-container" style="display: none;">
                <img class="new-avatar-preview" alt="Avatar Preview">
            </div>

            <div class="custom-file-upload <?php echo $avatar_url ? 'has-avatar' : ''; ?>">
                <input type="file" id="avatar_upload" name="avatar_upload" accept="image/*" class="avatar-file-input">
                <label for="avatar_upload" class="file-upload-label">
                    <span class="upload-icon"><i class="icon-camera"></i></span>
                    <span class="upload-text">
                        <?php if ($avatar_url) {
                            _e('Change Avatar', TEXT_DOMAIN);
                        } else {
                            _e('Choose Avatar', TEXT_DOMAIN);
                        }?>
                </label>
            </div>


        </div>
        <small class="form-text"><?php _e('Upload a profile picture (JPG, PNG, GIF). Max size: 2MB', TEXT_DOMAIN); ?></small>
    </div>
    <script>
        jQuery(document).ready(function($) {
            // Preview avatar before upload
            $('#avatar_upload').on('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        $('.new-avatar-preview').attr('src', e.target.result);
                        $('.avatar-preview-container').show();
                    };
                    reader.readAsDataURL(file);
                }
            });

            // Remove avatar
            $('.remove-avatar').on('click', function() {
                const userId = $(this).data('user-id');

                if (confirm("<?php _e('Are you sure you want to remove your avatar?',TEXT_DOMAIN);?>")) {
                    $.ajax({
                        url: '<?php echo admin_url('admin-ajax.php'); ?>',
                        type: 'POST',
                        data: {
                            action: 'remove_user_avatar',
                            user_id: userId,
                            nonce: '<?php echo wp_create_nonce('remove_avatar_nonce'); ?>'
                        },
                        success: function(response) {
                            if (response.success) {
                                $('.current-avatar').fadeOut();
                                $('.custom-file-upload').removeClass('has-avatar');
                                $('.upload-text').text("<?php _e('Choose Avatar',TEXT_DOMAIN);?>");
                            }
                        }
                    });
                }
            });
        });
    </script>
    <?php
}

// Handle avatar upload when form is saved
add_action('woocommerce_save_account_details', 'save_avatar_upload');
function save_avatar_upload($user_id) {
    // Debug: Log what we're receiving
    error_log('Avatar upload debug - FILES: ' . print_r($_FILES, true));
    error_log('Avatar upload debug - POST: ' . print_r($_POST, true));

    // Check if file was uploaded
    if (!isset($_FILES['avatar_upload'])) {
        error_log('Avatar upload debug: avatar_upload not in $_FILES');
        return;
    }

    $file = $_FILES['avatar_upload'];

    // Check for upload errors
    if ($file['error'] !== UPLOAD_ERR_OK) {
        if ($file['error'] === UPLOAD_ERR_NO_FILE) {
            // No file uploaded, just return silently
            return;
        }

        $error_messages = array(
            UPLOAD_ERR_INI_SIZE => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
            UPLOAD_ERR_FORM_SIZE => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
            UPLOAD_ERR_PARTIAL => 'The uploaded file was only partially uploaded',
            UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder',
            UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
            UPLOAD_ERR_EXTENSION => 'A PHP extension stopped the file upload'
        );

        $error_message = isset($error_messages[$file['error']]) ? $error_messages[$file['error']] : 'Unknown upload error';
        error_log('Avatar upload error: ' . $error_message);
        wc_add_notice(__('Upload error: ' . $error_message, TEXT_DOMAIN), 'error');
        return;
    }

    // Check if file is empty
    if ($file['size'] === 0) {
        error_log('Avatar upload debug: File size is 0');
        return;
    }

    // Validate file type
    $file_info = wp_check_filetype($file['name']);
    $allowed_types = array('jpg', 'jpeg', 'png', 'gif');

    if (!in_array(strtolower($file_info['ext']), $allowed_types)) {
        wc_add_notice(__('Please upload a valid image file (JPG, PNG, or GIF).', TEXT_DOMAIN), 'error');
        error_log('Avatar upload error: Invalid file type - ' . $file_info['ext']);
        return;
    }

    // Validate file size (2MB max)
    if ($file['size'] > 2 * 1024 * 1024) {
        wc_add_notice(__('File size must be less than 2MB.', TEXT_DOMAIN), 'error');
        error_log('Avatar upload error: File too large - ' . $file['size'] . ' bytes');
        return;
    }

    // Include WordPress file handling functions
    if (!function_exists('wp_handle_upload')) {
        require_once(ABSPATH . 'wp-admin/includes/file.php');
    }

    // Handle file upload
    $upload_overrides = array(
        'test_form' => false,
        'unique_filename_callback' => function($dir, $name, $ext) use ($user_id) {
            return 'avatar_user_' . $user_id . '_' . time() . $ext;
        }
    );

    $movefile = wp_handle_upload($file, $upload_overrides);

    error_log('Avatar upload debug - movefile result: ' . print_r($movefile, true));

    if ($movefile && !isset($movefile['error'])) {
        // Remove old avatar if exists
        $old_avatar = get_user_meta($user_id, 'custom_avatar', true);
        if ($old_avatar) {
            $upload_dir = wp_upload_dir();
            $old_file_path = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $old_avatar);
            if (file_exists($old_file_path)) {
                wp_delete_file($old_file_path);
                error_log('Avatar upload debug: Deleted old file - ' . $old_file_path);
            }
        }

        // Save new avatar URL
        update_user_meta($user_id, 'custom_avatar', $movefile['url']);
        wc_add_notice(__('Avatar uploaded successfully!', TEXT_DOMAIN), 'success');
        error_log('Avatar upload success: ' . $movefile['url']);
    } else {
        $error_msg = isset($movefile['error']) ? $movefile['error'] : 'Unknown error during file upload';
        wc_add_notice(__('There was an error uploading your avatar: ' . $error_msg, TEXT_DOMAIN), 'error');
        error_log('Avatar upload error: ' . $error_msg);
    }
}

// AJAX handler for removing avatar
add_action('wp_ajax_remove_user_avatar', 'handle_remove_user_avatar');
function handle_remove_user_avatar() {
    if (!wp_verify_nonce($_POST['nonce'], 'remove_avatar_nonce')) {
        wp_die('Security check failed');
    }

    $user_id = intval($_POST['user_id']);

    if ($user_id !== get_current_user_id()) {
        wp_die('Unauthorized');
    }

    $avatar_url = get_user_meta($user_id, 'custom_avatar', true);
    if ($avatar_url) {
        // Delete the file
        $file_path = str_replace(wp_upload_dir()['baseurl'], wp_upload_dir()['basedir'], $avatar_url);
        if (file_exists($file_path)) {
            wp_delete_file($file_path);
        }

        // Remove from user meta
        delete_user_meta($user_id, 'custom_avatar');
    }

    wp_send_json_success();
}

// Function to get user's custom avatar
function get_user_custom_avatar($user_id, $size = 100) {
    $avatar_url = get_user_meta($user_id, 'custom_avatar', true);

    if ($avatar_url) {
        return '<img src="' . esc_url($avatar_url) . '" alt="User Avatar" width="' . $size . '" height="' . $size . '" class="custom-user-avatar" style="border-radius: 50%; object-fit: cover;">';
    }

    // Fallback to WordPress default avatar
    return get_avatar($user_id, $size);
}

// Optional: Replace WordPress avatars with custom avatars site-wide
add_filter('get_avatar', 'use_custom_avatar', 10, 5);
function use_custom_avatar($avatar, $id_or_email, $size, $default, $alt) {
    $user_id = null;

    if (is_numeric($id_or_email)) {
        $user_id = $id_or_email;
    } elseif (is_string($id_or_email) && is_email($id_or_email)) {
        $user = get_user_by('email', $id_or_email);
        if ($user) {
            $user_id = $user->ID;
        }
    } elseif (is_object($id_or_email) && isset($id_or_email->user_id)) {
        $user_id = $id_or_email->user_id;
    }

    if ($user_id) {
        $custom_avatar = get_user_meta($user_id, 'custom_avatar', true);
        if ($custom_avatar) {
            return '<img src="' . esc_url($custom_avatar) . '" alt="' . esc_attr($alt) . '" width="' . $size . '" height="' . $size . '" class="custom-user-avatar" style="border-radius: 50%; object-fit: cover;">';
        }
    }

    return $avatar;
}