<?php

namespace TheLion\UseyourDrive\Integrations;

defined('ABSPATH') || exit;

add_filter('useyourdrive_render_formfield_data', [__NAMESPACE__.'\\FormHelpers', 'render_form_value'], 10, 3);

class FormHelpers
{
    public static function render_form_value($data, $ashtml, $formclass)
    {
        $uploaded_files = json_decode($data);

        if (empty($uploaded_files) || (0 === count((array) $uploaded_files))) {
            return $data;
        }

        // Get folder information based on first uploaded file
        $iterator = new \ArrayIterator($uploaded_files);
        $first_entry = $iterator->current();
        $folder_name = (in_array(dirname($first_entry->path), ['\\', '/']) ? 'Google Drive' : dirname($first_entry->path));
        $folder_location = ($ashtml && isset($first_entry->folderurl)) ? '<a href="'.urldecode($first_entry->folderurl).'">'.$folder_name.'</a>' : $folder_name;

        // Fill our custom field with the details of our upload session
        $formated_value = sprintf(esc_html__('%d file(s) uploaded to %s:', 'wpcloudplugins'), count((array) $uploaded_files), $folder_location);

        if (!$ashtml) {
            // Render TEXT only
            $formated_value .= "\r\n";
            foreach ($uploaded_files as $file) {
                $formated_value .= basename($file->path).' ('.$file->size.")\r\n";
            }

            return $formated_value;
        }

        // Render HTML
        ob_start();
        $current = 0;

        echo $formated_value; ?><table cellpadding="0" cellspacing="0" width="100%" border="0" style="cellspacing:0;line-height:22px;border:none;table-layout:auto;width:100%;">
    <?php foreach ($uploaded_files as $file) {            ?>
    <tr style="<?php echo ($current % 2) ? 'background: #fafafa;' : ''; ?> height: 26px;">
        <td style="width:20px;padding-right:10px;padding-left:5px;border:none;">
            <img alt="" height="16" src="<?php echo \TheLion\UseyourDrive\Helpers::get_default_thumbnail_icon($file->type); ?>" style="border:0;display:block;outline:none;text-decoration:none;height:auto;width:16px;max-width:16px;" width="16">
        </td>
        <td style="padding-right:10px;border:none;">
            <a href="<?php echo urldecode($file->link); ?>" target="_blank"><?php echo basename($file->path).' ('.$file->size.')'; ?></a>
            <?php echo (!empty($file->description)) ? '<br/><div style="font-weight:normal; max-height: 200px; overflow-y: auto;word-break: break-word;">'.nl2br($file->description).'</div>' : ''; ?>
        </td>
    </tr>
    <?php ++$current;
    } ?>
</table><?php

    // Remove any newlines
    return trim(preg_replace('/\s+/', ' ', ob_get_clean()));
    }
}
