<?php

namespace GriffinForms\Admin\Html\Pages\Lists;

class Logs extends \GriffinForms\Admin\Html\Pages\Lists\Format
{   
    protected $meta;
    protected $sql;
    protected $inline_js;
    protected $order_by = 'date_time';
    protected $type_counts = [];
    protected $disabled_alert;
    
    protected function setType()
    {
        $this->type = 'log';
    }

    protected function setDisabledAlert()
    {
        $this->maybeLoggingDisabledNotice();
    }

    protected function setTypeCounts()
    {
        $this->type_counts = $this->sql->getLogTypeCounts();
    }

    protected function addNewButton()
    {
        
    }
    
    protected function setFilterNames()
    {
        $this->filter_names = array(
            'search',
            'type',
            'date_from',
            'date_to',
            'item_type'
        );
    }
    
    protected function setFilterLinks()
    {
        $types = \GriffinForms\Admin\Choices\General::getInstance()->getChoices('log_message_types', false);
        $this->filter_links = array_merge(array('all'), $types);
    }
    
    protected function registerColumns(): void
    {
        $r = $this->column_registry;

        $r->register('log', 'checkbox',   ['label' => '',                                                     'locked' => true, 'default_on' => true]);
        $r->register('log', 'message',    ['label' => $this->lang->getText('message', 'list_head'),           'locked' => true, 'default_on' => true]);

        $r->register('log', 'log_type',   ['label' => $this->lang->getText('log_type', 'list_head'),          'default_on' => true, 'sortable' => true]);
        $r->register('log', 'category',   ['label' => $this->lang->getText('category', 'list_head'),          'default_on' => true]);
        $r->register('log', 'item_type',  ['label' => $this->lang->getText('item_type', 'list_head'),         'default_on' => true]);
        $r->register('log', 'date_time',  ['label' => $this->lang->getText('date_time', 'list_head'),         'default_on' => true, 'sortable' => true]);

        $r->register('log', 'id',         ['label' => __('ID', 'griffinforms-form-builder'),                  'default_on' => false]);

        parent::registerColumns();
    }

    protected function setRowActions()
    {
        $this->row_actions = array(
            'view',
            'trash'
        );
    }

    protected function rowActionView($item)
    {
        echo '<a href="' . esc_url($this->getItemUrl($item)) . '">' . esc_html($this->lang->getText('view', 'row_action')) . '</a>';
    }

    protected function messageCellText($list_column, $item)
    {
        $raw = $item->message ?? '';
        if (is_string($raw) && strlen($raw) > 1 && ($raw[0] === '{' || $raw[0] === '[')) {
            $decoded = json_decode($raw, true);
            if (json_last_error() === JSON_ERROR_NONE) {
                $type  = ! empty($item->log_type) ? ucfirst((string) $item->log_type) : '';
                $cat   = ! empty($item->category) ? (string) $item->category : '';
                $label = $cat !== '' ? $cat : ($type !== '' ? $type : esc_html__('Log entry', 'griffinforms-form-builder'));
                echo esc_html($label);
                return;
            }
        }
        echo esc_html((string) $raw);
    }
    
    protected function itemFilters()
    {
        echo '<div class="alignleft actions">';
        $this->itemTypeFilter();
        $this->dateFilter();
        echo '</div>';
    }

    protected function itemTypeFilter()
    {
        if (!is_object($this->sql) || !method_exists($this->sql, 'getDistinctItemTypes')) {
            return;
        }

        $types = (array) $this->sql->getDistinctItemTypes();
        if (empty($types)) {
            return; // nothing to filter by
        }

        $filters = $this->getListFilters();
        $selected = isset($filters['item_type']) ? sanitize_text_field($filters['item_type']) : '';

        echo '<label class="screen-reader-text" for="filter-by-item-type">' . esc_html__('Filter by item type', 'griffinforms-form-builder') . '</label>';
        echo '<select name="item_type" id="filter-by-item-type">';
        echo '<option value="">' . esc_html__('All item types', 'griffinforms-form-builder') . '</option>';
        foreach ($types as $type) {
            echo '<option value="' . esc_attr($type) . '" ' . selected($selected, $type, false) . '>' . esc_html($type) . '</option>';
        }
        echo '</select>';
    }

    protected function getFilterLink($type)
    {
        $count = isset($this->type_counts[$type]) ? $this->type_counts[$type] : 0;
        
        $link_class = '';
        $filters = $this->getListFilters();
        
        if (!empty($filters) and isset($filters['type']) and $filters['type'] == $type) {
            $link_class = 'current';
        }
        
        $filter_url = $this->list_url . '&type=' . $type;

        echo '<a href="' . esc_url($filter_url) . '" class="' . esc_attr($link_class) . '" aria-current="page">';
        echo esc_html($this->lang->getText('type_' . $type, 'filter_link'));
        echo ' <span class="count">(';
        echo absint($count);
        echo ')</span>';
        echo '</a>';
    }

    protected function successFilterLink()
    {
        $this->getFilterLink('success');
    }

    protected function errorFilterLink()
    {
        $this->getFilterLink('error');
    }

    protected function infoFilterLink()
    {
        $this->getFilterLink('info');
    }

    protected function warningFilterLink()
    {
        $this->getFilterLink('warning');   
    }

    protected function logTypeHeadingText()
    {
        echo esc_html($this->lang->getText('log_type', 'heading_text'));
    }

    protected function dateTimeHeadingText()
    {
        echo esc_html($this->lang->getText('date_time', 'heading_text'));
    }

    protected function dateTimeCellText($list_item, $item)
    {
        $item_date = strtotime($item->date_time);
        $current_date = strtotime('now');

        $date_format = get_option('date_format');
        $time_format = get_option('time_format');

        $formatted_item_date = wp_date($date_format, $item_date);
        $formatted_item_time = wp_date($time_format, $item_date);

        $is_today = wp_date('d', $item_date) === wp_date('d');
        $is_yesterday = absint(wp_date('d', $item_date)) === (absint(wp_date('d')) - 1);
        
        if ($is_today) {
            echo esc_html($this->lang->getText('Today', 'date'));
        } elseif ($is_yesterday) {
            echo esc_html($this->lang->getText('Yesterday', 'date'));
        } else {
            echo esc_html($formatted_item_date);
        }
        
        echo '<br> at ';
        echo esc_html($formatted_item_time);
    }

    /**
     * Print a WordPress admin warning notice if logging is disabled in settings.
     */
    protected function maybeLoggingDisabledNotice()
    {
        if (!is_object($this->settings) || !method_exists($this->settings, 'getOption')) {
            return;
        }

        $enabled = (int) $this->settings->getOption('enable_native_logging');
        if ($enabled !== 1) {
            echo '<div class="notice notice-warning"><p>';
            echo esc_html__('Native logging is currently disabled in GriffinForms settings. No new log entries are being recorded.', 'griffinforms-form-builder');
            echo $this->settingsLinkHtml();
            echo '</p></div>';
            return;
        }

        // Logging is enabled — check if only a subset of message types are being recorded
        $selected = $this->settings->getOption('log_message_types');
        if (!is_array($selected)) {
            $maybe = maybe_unserialize($selected);
            if ($maybe !== false) {
                $selected = $maybe;
            }
        }

        // Choices: value => label
        $choices = \GriffinForms\Admin\Choices\General::getInstance()->getChoices('log_message_types');
        if (empty($choices) || !is_array($choices)) {
            return; // nothing to compare against
        }

        // Normalize
        $all_keys = array_keys($choices);
        $selected = is_array($selected) ? array_values(array_intersect($all_keys, array_map('strval', $selected))) : array();

        // If no selection saved, treat as "all" (default behavior) => no notice
        if (empty($selected)) {
            return;
        }

        // If fewer than all are selected, inform the user which ones are active
        if (count($selected) < count($all_keys)) {
            $labels = array();
            foreach ($selected as $key) {
                $labels[] = isset($choices[$key]) ? $choices[$key] : $key;
            }
            echo '<div class="notice notice-info"><p>';
            echo esc_html__('Logging is enabled, but limited to the following message types:', 'griffinforms-form-builder') . ' ';
            echo esc_html(implode(', ', array_map('sanitize_text_field', (array) $selected)));
            echo $this->settingsLinkHtml();
            echo '</p></div>';
        }
    }

    private function settingsLinkHtml(): string
    {
        $url = admin_url('admin.php?page=griffinforms-settings-general');
        return '<br><a href="' . esc_url($url) . '" target="_blank">' . esc_html__('Change log settings', 'griffinforms-form-builder') . '</a>';
    }

    protected function idCellText($list_column, $item)
    {
        echo '<span class="badge text-bg-secondary">' . absint($item->id) . '</span>';
    }
}