<?php

namespace GriffinForms\Admin\Html\Pages\Single;

class Log extends \GriffinForms\Admin\Html\Pages\Single\Format
{   
    protected $type = 'log';
    protected $fields = ['id', 'date_time', 'log_type', 'item_type', 'item_id', 'category', 'message'];
    
    public function html()
    {
        echo '<div class="griffinforms-toast">';
        $this->toastAlert();
        echo '</div>';
        $this->setSnackBar();
        $this->spinnerOverlay();
        echo '<div class="container w-75 mt-3">';
        $this->topNav();
        echo '</div>';
        echo '<div class="container w-75 mt-3 py-3">';
        echo '<div class="griffinforms-itempage-heading row">';
        echo '<div class="col">';
        echo '<h3>';
        echo esc_html($this->headingText());
        echo ' <span class="gf-log-page__entry-id">' . esc_html($this->headingSubtext()) . '</span>';
        echo '</h3>';
        echo '</div>';
        echo '</div>';
        $this->itemLocation();
        echo '</div>';
        $this->logHtml();
        echo '<div class="container griffinforms-item-options w-75 mt-3">';
        echo '</div>';
        $this->setFooterJs();
    }

    public function itemOptions()
    {
    }

    protected function logHtml()
    {
        if (empty($this->item) || !is_object($this->item)) {
            echo '<div class="container w-75 mt-3">';
            echo '<div class="notice notice-warning"><p>' . esc_html__('No log entry found.', 'griffinforms-form-builder') . '</p></div>';
            echo '</div>';
            return;
        }

        $raw_message = $this->item->getProp('message');
        $message = is_array($raw_message) ? wp_json_encode($raw_message) : (string) $raw_message;
        $related_url = $this->getRelatedItemUrl();
        $item_type = (string) $this->item->getProp('item_type');
        $item_id = absint($this->item->getProp('item_id'));
        $category = (string) $this->item->getProp('category');
        $log_type = (string) $this->item->getProp('log_type');

        echo '<div class="container w-75 mt-3 gf-log-page">';
        echo '<div class="gf-log-page__layout">';

        echo '<section class="gf-log-page__panel gf-log-page__panel--message">';
        echo '<div class="gf-log-page__panel-head">';
        echo '<div class="gf-log-page__panel-title-wrap">';
        echo '<span class="gf-log-page__panel-icon" aria-hidden="true">' . wp_kses_post($this->mIcon('chat', 'rounded', 'return')) . '</span>';
        echo '<h2 class="gf-log-page__panel-title">' . esc_html__('Message', 'griffinforms-form-builder') . '</h2>';
        echo '</div>';
        echo '</div>';
        echo '<div class="gf-log-page__message">';
        echo '<p class="gf-log-page__message-text">' . ($message !== '' ? wp_kses_post($message) : esc_html__('No message stored for this log entry.', 'griffinforms-form-builder')) . '</p>';
        echo '</div>';
        echo '</section>';

        echo '<section class="gf-log-page__panel gf-log-page__panel--details">';
        echo '<div class="gf-log-page__panel-head">';
        echo '<div class="gf-log-page__panel-title-wrap">';
        echo '<span class="gf-log-page__panel-icon" aria-hidden="true">' . wp_kses_post($this->mIcon('content_paste', 'rounded', 'return')) . '</span>';
        echo '<h2 class="gf-log-page__panel-title">' . esc_html__('Details', 'griffinforms-form-builder') . '</h2>';
        echo '</div>';
        echo '</div>';
        echo '<dl class="gf-log-page__details">';
        $this->renderDetailRow($this->lang->getText('id', 'label'), $this->getFormattedId(), 'manage_search');
        $this->renderDetailRow($this->lang->getText('date_time', 'label'), $this->getFormattedDateTime(), 'calendar_month');
        $this->renderDetailRow($this->lang->getText('log_type', 'label'), $this->getFormattedLogType(), 'flag');
        $this->renderDetailRow($this->lang->getText('item_type', 'label'), $item_type !== '' ? esc_html($item_type) : __('Not available', 'griffinforms-form-builder'), 'category');
        $this->renderDetailRow($this->lang->getText('item_id', 'label'), $this->getFormattedItemId(), 'link', true);
        $this->renderDetailRow($this->lang->getText('category', 'label'), $category !== '' ? esc_html($category) : __('Not available', 'griffinforms-form-builder'), 'sell');
        $this->renderDetailRow($this->lang->getText('message', 'label'), $message !== '' ? wp_kses_post($message) : esc_html__('No message stored.', 'griffinforms-form-builder'), 'chat', true);
        echo '</dl>';
        if ($related_url) {
            echo '<div class="gf-log-page__details-actions">';
            echo '<a class="button button-primary" href="' . esc_url($related_url) . '" target="_blank" rel="noopener noreferrer">' . esc_html__('Open related item', 'griffinforms-form-builder') . '</a>';
            echo '</div>';
        }
        echo '</section>';

        echo '</div>';

        echo '<section class="gf-log-page__panel gf-log-page__panel--metadata">';
        echo '<div class="gf-log-page__panel-head">';
        echo '<div class="gf-log-page__panel-title-wrap">';
        echo '<span class="gf-log-page__panel-icon" aria-hidden="true">' . wp_kses_post($this->mIcon('article', 'rounded', 'return')) . '</span>';
        echo '<h2 class="gf-log-page__panel-title">' . esc_html__('Record', 'griffinforms-form-builder') . '</h2>';
        echo '</div>';
        echo '</div>';
        echo '<div class="gf-log-page__record">';
        echo '<div class="gf-log-page__record-icon">';
        echo '<img src="' . esc_url($this->getLogTypeIconUrl()) . '" alt="" width="48" height="48" loading="lazy" decoding="async" />';
        echo '</div>';
        echo '<div class="gf-log-page__record-body">';
        echo '<div class="gf-log-page__record-title">' . esc_html($this->getFormattedLogType()) . '</div>';
        echo '<div class="gf-log-page__record-subtitle">' . esc_html($item_type !== '' ? $item_type : __('Unknown item type', 'griffinforms-form-builder')) . '</div>';
        echo '</div>';
        echo '</div>';
        echo '</section>';

        echo '</div>';
    }

    /** Field renderers **/
    protected function getFormattedId(): string
    {
        return (string) $this->item->getProp('id');
    }

    protected function getFormattedLogType(): string
    {
        $log_type = $this->item->getProp('log_type');
        return (string) $log_type;
    }

    protected function getLogTypeIconUrl(): string
    {
        $log_type = sanitize_key((string) $this->item->getProp('log_type'));
        if ($log_type === '') {
            $log_type = 'info';
        }

        $icon_path = trailingslashit($this->config->getRootPath()) . 'admin/images/log-type-icons/' . $log_type . '.svg';
        if (!file_exists($icon_path)) {
            $log_type = 'info';
        }

        return $this->config->getRootUrl() . 'admin/images/log-type-icons/' . $log_type . '.svg';
    }

    protected function getItemType()
    {
        echo esc_html((string) $this->item->getProp('item_type'));
    }

    protected function getFormattedItemId(): string
    {
        $id = $this->item->getProp('item_id');
        $id_int = absint($id);

        if (empty($id) || $id_int <= 0) {
            return __('Not available', 'griffinforms-form-builder');
        }

        $output = (string) $id;

        $url = $this->getRelatedItemUrl();
        if ($url) {
            $output .= ' <a href="' . esc_url($url) . '" class="button-link" target="_blank" rel="noopener noreferrer">' . esc_html__('Open', 'griffinforms-form-builder') . '</a>';
        }

        return $output;
    }

    protected function getCategory()
    {
        echo esc_html((string) $this->item->getProp('category'));
    }

    protected function getMessage()
    {
        $val = $this->item->getProp('message');
        if (is_array($val)) {
            $val = implode(', ', array_map('sanitize_text_field', $val));
        }
        echo esc_html((string) $val);
    }

    protected function getFormattedDateTime(): string
    {
        // Prefer `date_time`, fallback to `created` if unavailable
        $gmt = (string) $this->item->getProp('date_time');
        if ($gmt === '') {
            $gmt = (string) $this->item->getProp('created');
        }

        if ($gmt === '') {
            return '-';
        }

        // WP-configured formats
        $format = trim(get_option('date_format') . ' ' . get_option('time_format'));

        // Convert stored GMT datetime to a Unix timestamp, then format in site timezone
        $ts = strtotime($gmt . ' UTC');
        if ($ts === false) {
            return $gmt;
        }

        // wp_date() respects site timezone and i18n
        return wp_date($format, $ts);
    }

    protected function renderDetailRow(string $label, string $value, string $icon_class, bool $allow_html = false): void
    {
        echo '<div class="gf-log-page__detail">';
        echo '<dt class="gf-log-page__detail-label">';
        echo '<span class="gf-log-page__detail-icon" aria-hidden="true">' . wp_kses_post($this->mIcon($icon_class, 'rounded', 'return')) . '</span>';
        echo esc_html($label);
        echo '</dt>';
        echo '<dd class="gf-log-page__detail-value">';
        echo $allow_html ? wp_kses_post($value) : esc_html($value);
        echo '</dd>';
        echo '</div>';
    }

    protected function getRelatedItemUrl(): string
    {
        $type = (string) $this->item->getProp('item_type');
        $id_int = absint($this->item->getProp('item_id'));

        if ($type === '' || $id_int <= 0) {
            return '';
        }

        return $this->resolveItemAdminUrl($type, $id_int);
    }
    
    /**
     * Resolve admin edit URL for a given GriffinForms item type and id.
     * Allows override via 'griffinforms_log_item_admin_pages' filter.
     */
    protected function resolveItemAdminUrl(string $item_type, int $item_id): string
    {
        $map = array(
            'form'       => 'griffinforms-form',
            'submission' => 'griffinforms-submission',
        );
        /**
         * Filter the page slug map for item admin URLs.
         * Return an associative array of item_type => page slug.
         */
        $map = apply_filters('griffinforms_log_item_admin_pages', $map);

        $key = strtolower(trim($item_type));
        if (!isset($map[$key]) || $map[$key] === '') {
            return '';
        }

        $page = $map[$key];
        $url  = add_query_arg(array('page' => $page, 'id' => $item_id), admin_url('admin.php'));
        return (string) $url;
    }
}
