<?php
/**
 * File Helper Functions
 *
 * Provides reusable functions for handling file display and processing
 *
 * @since 4.2.0
 * @package WPUF\UserDirectory
 */

namespace WPUF\UserDirectory;

/**
 * FileHelper class
 */
class FileHelper
{

    /**
     * Convert file IDs to file data with URLs and metadata
     *
     * @since 4.2.0
     *
     * @param mixed $file_ids File IDs (can be array, string, or number)
     * @return array Array of file data
     */
    public static function convert_file_ids_to_data($file_ids)
    {
        $files = [];

        // Normalize file IDs to array
        if (is_string($file_ids)) {
            $decoded = json_decode($file_ids, true);
            if (is_array($decoded)) {
                $files = $decoded;
            } else {
                // Single file ID as string
                $files = [$file_ids];
            }
        } elseif (is_array($file_ids)) {
            $files = $file_ids;
        } elseif (is_numeric($file_ids)) {
            // Single file ID as number
            $files = [$file_ids];
        }

        // Convert file IDs to file data
        $file_data = [];
        foreach ($files as $file) {
            $file_id = null;
            $file_name = '';
            $file_url = '';
            $file_size = '';
            $file_type = '';

            // Handle different file data formats
            if (is_numeric($file)) {
                // Single file ID
                $file_id = intval($file);
            } elseif (is_array($file) && isset($file['id'])) {
                // File object with ID
                $file_id = intval($file['id']);
                $file_name = $file['name'] ?? '';
                $file_url = $file['url'] ?? '';
                $file_size = $file['size'] ?? '';
                $file_type = $file['type'] ?? '';
            } elseif (is_array($file) && isset($file['attachment_id'])) {
                // File object with attachment_id
                $file_id = intval($file['attachment_id']);
                $file_name = $file['name'] ?? '';
                $file_url = $file['url'] ?? '';
                $file_size = $file['size'] ?? '';
                $file_type = $file['type'] ?? '';
            } elseif (is_string($file) && is_numeric($file)) {
                // File ID as string
                $file_id = intval($file);
            }

            // Skip invalid file IDs
            if (!$file_id || $file_id <= 0) {
                continue;
            }

            // Get attachment data
            $attachment = get_post($file_id);
            if (!$attachment || 'attachment' !== $attachment->post_type) {
                continue;
            }

            // Get file URL if not already provided
            if (empty($file_url)) {
                $file_url = wp_get_attachment_url($file_id);
            }

            // Get file name if not already provided
            if (empty($file_name)) {
                // Use the original filename from the attachment
                $file_name = basename($file_url);
                // If that's empty, fall back to post title
                if (empty($file_name)) {
                    $file_name = $attachment->post_title ?: 'Untitled';
                }
            }

            // Get file size if not already provided
            if (empty($file_size)) {
                $file_path = get_attached_file($file_id);
                if ($file_path && file_exists($file_path)) {
                    $file_size = size_format(filesize($file_path));
                } else {
                    $file_size = '';
                }
            }

            // Get file type if not already provided
            if (empty($file_type)) {
                $file_type = $attachment->post_mime_type;
            }

            $file_data[] = [
                'id' => $file_id,
                'name' => $file_name,
                'url' => $file_url,
                'size' => $file_size,
                'type' => $file_type
            ];
        }

        return $file_data;
    }

    /**
     * Get file icon HTML based on file type
     *
     * @since 4.2.0
     *
     * @param string $file_type MIME type of the file
     * @param string $class Additional CSS classes
     * @return string HTML for file icon
     */
    public static function get_file_icon_html($file_type, $class = '')
    {
        $icon_class = 'wpuf-file-icon';
        if ($class) {
            $icon_class .= ' ' . $class;
        }

        if ($file_type && strpos($file_type, 'image/') === 0) {
            // Image icon
            return sprintf(
                '<div class="%s">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M21 19V5C21 3.9 20.1 3 19 3H5C3.9 3 3 3.9 3 5V19C3 20.1 3.9 21 5 21H19C20.1 21 21 20.1 21 19ZM8.5 13.5L11 16.51L14.5 12L19 18H5L8.5 13.5Z" fill="currentColor"/>
                    </svg>
                </div>',
                esc_attr($icon_class)
            );
        }

        // Default file icon (PDF-style)
        return sprintf(
            '<div class="%s">
                <svg width="37" height="49" viewBox="0 0 37 49" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M2 49H35C36.1046 49 37 48.1046 37 47V24.5V11.25L24.75 0H2C0.895431 0 0 0.89543 0 2V47C0 48.1046 0.895432 49 2 49Z" fill="#FFC700"/>
                    <path d="M37 11.25L24.75 0V9.25C24.75 10.3546 25.6454 11.25 26.75 11.25H37Z" fill="#D99C00"/>
                    <path d="M25.9966 30.1418C25.2708 30.1418 24.644 29.991 24.1161 29.6893C23.5914 29.3845 23.1877 28.9541 22.9049 28.398C22.6221 27.8387 22.4807 27.1804 22.4807 26.4232C22.4807 25.6786 22.6221 25.025 22.9049 24.4626C23.1908 23.8971 23.5898 23.4572 24.102 23.143C24.6141 22.8257 25.2158 22.667 25.907 22.667C26.3532 22.667 26.7742 22.7393 27.1701 22.8838C27.5692 23.0252 27.9211 23.2451 28.2258 23.5436C28.5337 23.8421 28.7757 24.2223 28.9516 24.6841C29.1276 25.1429 29.2156 25.6896 29.2156 26.3243V26.8474H23.2819V25.6974H27.5801C27.577 25.3707 27.5063 25.08 27.3681 24.8255C27.2298 24.5679 27.0366 24.3652 26.7884 24.2176C26.5433 24.0699 26.2574 23.9961 25.9306 23.9961C25.5818 23.9961 25.2755 24.0809 25.0116 24.2506C24.7477 24.4171 24.5419 24.637 24.3942 24.9104C24.2496 25.1806 24.1758 25.4775 24.1727 25.8011V26.805C24.1727 27.226 24.2496 27.5873 24.4036 27.889C24.5576 28.1875 24.7728 28.4168 25.0493 28.5771C25.3258 28.7342 25.6494 28.8127 26.0202 28.8127C26.2684 28.8127 26.493 28.7781 26.6941 28.709C26.8952 28.6368 27.0696 28.5315 27.2172 28.3933C27.3649 28.255 27.4765 28.0838 27.5519 27.8795L29.1449 28.0586C29.0443 28.4797 28.8527 28.8473 28.5699 29.1615C28.2902 29.4725 27.9321 29.7145 27.4953 29.8873C27.0586 30.0569 26.559 30.1418 25.9966 30.1418Z" fill="white"/>
                    <path d="M21.0374 20.3477V29.9998H19.3313V20.3477H21.0374Z" fill="white"/>
                    <path d="M15.8707 29.9996V22.7605H17.5768V29.9996H15.8707ZM16.7285 21.7331C16.4583 21.7331 16.2258 21.6435 16.031 21.4644C15.8362 21.2822 15.7388 21.0638 15.7388 20.8093C15.7388 20.5517 15.8362 20.3333 16.031 20.1542C16.2258 19.972 16.4583 19.8809 16.7285 19.8809C17.0018 19.8809 17.2344 19.972 17.426 20.1542C17.6208 20.3333 17.7182 20.5517 17.7182 20.8093C17.7182 21.0638 17.6208 21.2822 17.426 21.4644C17.2344 21.6435 17.0018 21.7331 16.7285 21.7331Z" fill="white"/>
                    <path d="M8.16968 29.9998V20.3477H14.3531V21.8134H9.91819V24.4338H13.9289V25.8995H9.91819V29.9998H8.16968Z" fill="white"/>
                </svg>
            </div>',
            esc_attr($icon_class)
        );
    }

    /**
     * Render file grid HTML
     *
     * @since 4.2.0
     *
     * @param array $files Array of file data
     * @param array $options Rendering options
     * @return string HTML for file grid
     */
    public static function render_file_grid($files, $options = [])
    {
        $defaults = [
            'show_size' => false,
            'show_download' => true,
            'grid_class' => '!wpuf-grid !wpuf-grid-cols-2 sm:!wpuf-grid-cols-3 md:!wpuf-grid-cols-4 !wpuf-gap-3',
            'item_class' => '!wpuf-relative !wpuf-group',
            'link_class' => '!wpuf-block !wpuf-no-underline',
        ];

        $options = wp_parse_args($options, $defaults);

        if (empty($files)) {
            return '<div class="wpuf-files-empty">' . esc_html__('No files found.', 'wpuf-pro') . '</div>';
        }

        $html = '<div class="files-grid ' . esc_attr($options['grid_class']) . '">';

        foreach ($files as $file) {
            $file_name = $file['name'] ?? '';
            $file_url = $file['url'] ?? '';
            $file_size = $file['size'] ?? '';
            $file_type = $file['type'] ?? '';

            if (!$file_name) {
                continue;
            }

            $html .= '<div class="file-item ' . esc_attr($options['item_class']) . '">';

            if ($file_url && $options['show_download']) {
                $html .= '<a href="' . esc_url($file_url) . '" class="' . esc_attr($options['link_class']) . '" target="_blank">';
            }

            // Check if it's an image and show image preview
            if ($file_type && strpos($file_type, 'image/') === 0 && $file_url) {
                $html .= '<div class="file-preview !wpuf-w-full !wpuf-rounded-lg !wpuf-overflow-hidden !wpuf-transition-all !wpuf-duration-200 group-hover:!wpuf-scale-105">';
                $html .= '<img src="' . esc_url($file_url) . '" alt="' . esc_attr($file_name) . '" class="!wpuf-w-full !wpuf-object-cover">';
                $html .= '</div>';
            } else {
                // Show file type specific icon for non-image files
                $file_extension = strtoupper(pathinfo($file_url, PATHINFO_EXTENSION));
                $display_label = $file_extension ?: 'FILE';

                // Get file icon SVG path based on file type
                $icon_path = self::get_file_icon_svg_path($file_type);
                $icon_viewbox = self::get_file_icon_viewbox($file_type);

                $html .= '<div class="file-preview !wpuf-w-full !wpuf-h-28 !wpuf-bg-gray-700 !wpuf-rounded-lg !wpuf-flex !wpuf-flex-col !wpuf-items-center !wpuf-justify-center !wpuf-text-white !wpuf-font-bold !wpuf-text-sm hover:!wpuf-bg-gray-500 !wpuf-transition-all !wpuf-duration-200 group-hover:!wpuf-scale-105">';
                $html .= '<svg class="!wpuf-w-8 !wpuf-h-8 !wpuf-mb-1" fill="currentColor" viewBox="' . esc_attr($icon_viewbox) . '">';
                $html .= '<path d="' . esc_attr($icon_path) . '"></path>';
                $html .= '</svg>';
                $html .= '<span>' . esc_html($display_label) . '</span>';
                $html .= '</div>';
            }

            if ($file_url && $options['show_download']) {
                $html .= '</a>';
            }

            $html .= '<div class="file-info !wpuf-mt-2">';
            $html .= '<div class="file-name !wpuf-text-xs !wpuf-text-gray-700 !wpuf-text-center !wpuf-truncate !wpuf-font-medium">';
            $formatted_name = self::format_filename_with_extension($file_name);
            $html .= esc_html($formatted_name);
            $html .= '</div>';
            $html .= '</div>';

            $html .= '</div>';
        }

        $html .= '</div>';

        return $html;
    }

    /**
     * Get file icon SVG path based on file type
     *
     * @since 4.2.0
     *
     * @param string $file_type MIME type of the file
     * @return string SVG path for the file icon
     */
    public static function get_file_icon_svg_path($file_type) {
        // Images - Font Awesome image icon path
        if (strpos($file_type, 'image/') === 0) {
            return 'M64 32C28.7 32 0 60.7 0 96L0 416c0 35.3 28.7 64 64 64l320 0c35.3 0 64-28.7 64-64l0-320c0-35.3-28.7-64-64-64L64 32zm64 80a48 48 0 1 1 0 96 48 48 0 1 1 0-96zM272 224c8.4 0 16.1 4.4 20.5 11.5l88 144c4.5 7.4 4.7 16.7 .5 24.3S368.7 416 360 416L88 416c-8.9 0-17.2-5-21.3-12.9s-3.5-17.5 1.6-24.8l56-80c4.5-6.4 11.8-10.2 19.7-10.2s15.2 3.8 19.7 10.2l26.4 37.8 61.4-100.5c4.4-7.1 12.1-11.5 20.5-11.5z';
        }

        // Documents - Font Awesome document icon path
        if (in_array($file_type, ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'text/plain'])) {
            return 'M64 0C28.7 0 0 28.7 0 64L0 448c0 35.3 28.7 64 64 64l256 0c35.3 0 64-28.7 64-64l0-277.5c0-17-6.7-33.3-18.7-45.3L258.7 18.7C246.7 6.7 230.5 0 213.5 0L64 0zM325.5 176L232 176c-13.3 0-24-10.7-24-24L208 58.5 325.5 176z';
        }

        // Videos - Font Awesome video icon path
        if (strpos($file_type, 'video/') === 0) {
            return 'M0 256a256 256 0 1 1 512 0 256 256 0 1 1 -512 0zM188.3 147.1c-7.6 4.2-12.3 12.3-12.3 20.9l0 176c0 8.7 4.7 16.7 12.3 20.9s16.8 4.1 24.3-.5l144-88c7.1-4.4 11.5-12.1 11.5-20.5s-4.4-16.1-11.5-20.5l-144-88c-7.4-4.5-16.7-4.7-24.3-.5z';
        }

        // Audio - Font Awesome audio icon path
        if (strpos($file_type, 'audio/') === 0) {
            return 'M533.6 32.5c-10.3-8.4-25.4-6.8-33.8 3.5s-6.8 25.4 3.5 33.8C557.5 113.8 592 180.8 592 256s-34.5 142.2-88.7 186.3c-10.3 8.4-11.8 23.5-3.5 33.8s23.5 11.8 33.8 3.5C598.5 426.7 640 346.2 640 256S598.5 85.2 533.6 32.5zM473.1 107c-10.3-8.4-25.4-6.8-33.8 3.5s-6.8 25.4 3.5 33.8C475.3 170.7 496 210.9 496 256s-20.7 85.3-53.2 111.8c-10.3 8.4-11.8 23.5-3.5 33.8s23.5 11.8 33.8 3.5c43.2-35.2 70.9-88.9 70.9-149s-27.7-113.8-70.9-149zm-60.5 74.5c-10.3-8.4-25.4-6.8-33.8 3.5s-6.8 25.4 3.5 33.8C393.1 227.6 400 241 400 256s-6.9 28.4-17.7 37.3c-10.3 8.4-11.8 23.5-3.5 33.8s23.5 11.8 33.8 3.5C434.1 312.9 448 286.1 448 256s-13.9-56.9-35.4-74.5zM80 352l48 0 134.1 119.2c6.4 5.7 14.6 8.8 23.1 8.8 19.2 0 34.8-15.6 34.8-34.8l0-378.4c0-19.2-15.6-34.8-34.8-34.8-8.5 0-16.7 3.1-23.1 8.8L128 160 80 160c-26.5 0-48 21.5-48 48l0 96c0 26.5 21.5 48 48 48z';
        }

        // Archives - Font Awesome folder icon path
        if (in_array($file_type, ['application/zip', 'application/x-rar-compressed', 'application/x-7z-compressed', 'application/x-tar', 'application/gzip'])) {
            return 'M56 225.6L32.4 296.2 32.4 96c0-35.3 28.7-64 64-64l138.7 0c13.8 0 27.3 4.5 38.4 12.8l38.4 28.8c5.5 4.2 12.3 6.4 19.2 6.4l117.3 0c35.3 0 64 28.7 64 64l0 16-365.4 0c-41.3 0-78 26.4-91.1 65.6zM477.8 448L99 448c-32.8 0-55.9-32.1-45.5-63.2l48-144C108 221.2 126.4 208 147 208l378.8 0c32.8 0 55.9 32.1 45.5 63.2l-48 144c-6.5 19.6-24.9 32.8-45.5 32.8z';
        }

        // Others - Font Awesome folder icon path (same as archives)
        return 'M56 225.6L32.4 296.2 32.4 96c0-35.3 28.7-64 64-64l138.7 0c13.8 0 27.3 4.5 38.4 12.8l38.4 28.8c5.5 4.2 12.3 6.4 19.2 6.4l117.3 0c35.3 0 64 28.7 64 64l0 16-365.4 0c-41.3 0-78 26.4-91.1 65.6zM477.8 448L99 448c-32.8 0-55.9-32.1-45.5-63.2l48-144C108 221.2 126.4 208 147 208l378.8 0c32.8 0 55.9 32.1 45.5 63.2l-48 144c-6.5 19.6-24.9 32.8-45.5 32.8z';
    }

    /**
     * Get file icon viewBox based on file type
     *
     * @since 4.2.0
     *
     * @param string $file_type MIME type of the file
     * @return string ViewBox for the SVG icon
     */
    public static function get_file_icon_viewbox($file_type) {
        // Images - viewBox="0 0 448 512"
        if (strpos($file_type, 'image/') === 0) {
            return '0 0 448 512';
        }

        // Documents - viewBox="0 0 384 512"
        if (in_array($file_type, ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'text/plain'])) {
            return '0 0 384 512';
        }

        // Videos - viewBox="0 0 512 512"
        if (strpos($file_type, 'video/') === 0) {
            return '0 0 512 512';
        }

        // Audio - viewBox="0 0 640 512"
        if (strpos($file_type, 'audio/') === 0) {
            return '0 0 640 512';
        }

        // Archives & Others - viewBox="0 0 576 512"
        return '0 0 576 512';
    }

    /**
     * Format filename to show first 15 characters + extension
     *
     * @since 4.2.0
     *
     * @param string $filename Original filename
     * @return string Formatted filename
     */
    public static function format_filename_with_extension($filename) {
        if (empty($filename)) {
            return '';
        }

        // Get file extension
        $extension = pathinfo($filename, PATHINFO_EXTENSION);
        $name_without_extension = pathinfo($filename, PATHINFO_FILENAME);

        // If no extension, return original filename (truncated if needed)
        if (empty($extension)) {
            if (strlen($filename) <= 15) {
                return $filename;
            }
            return substr($filename, 0, 15) . '...';
        }

        // If filename is 15 characters or less, return as is
        if (strlen($name_without_extension) <= 15) {
            return $filename;
        }

        // Truncate to 15 characters and add extension
        $truncated_name = substr($name_without_extension, 0, 15);
        return $truncated_name . '...' . $extension;
    }

    /**
     * Get files from user meta field
     *
     * @since 4.2.0
     *
     * @param int $user_id User ID
     * @param string $meta_key Meta field key
     * @return array Array of file data
     */
    public static function get_files_from_user_meta($user_id, $meta_key)
    {
        if (!$user_id || !$meta_key) {
            return [];
        }

        $field_value = get_user_meta($user_id, $meta_key, true);

        if (empty($field_value)) {
            return [];
        }

        return self::convert_file_ids_to_data($field_value);
    }

    /**
     * Get all user files (attachments)
     *
     * @since 4.2.0
     *
     * @param int $user_id User ID
     * @param int $limit Number of files to return
     * @return array Array of file data
     */
    public static function get_user_attachments($user_id, $limit = 20)
    {
        if (!$user_id) {
            return [];
        }

        $attachments = get_posts([
            'post_type' => 'attachment',
            'post_status' => 'inherit',
            'author' => $user_id,
            'numberposts' => $limit,
            'orderby' => 'date',
            'order' => 'DESC',
        ]);

        $files = [];
        foreach ($attachments as $attachment) {
            $file_path = get_attached_file($attachment->ID);
            $file_size = '';

            if ($file_path && file_exists($file_path)) {
                $file_size = size_format(filesize($file_path));
            }

            $files[] = [
                'id' => $attachment->ID,
                'name' => basename(wp_get_attachment_url($attachment->ID)),
                'url' => wp_get_attachment_url($attachment->ID),
                'size' => $file_size,
                'type' => get_post_mime_type($attachment->ID)
            ];
        }

        return $files;
    }
}
