<?php

namespace GriffinForms\Admin\Html\Pages\Lists;

trait ListTable
{
    protected function thClasses($column_name)
    {
        $css_class = '';
        
        $css_class .= 'column-' . $column_name;
        
        if (in_array($column_name, $this->sortables)) {
            $css_class .= ' manage-column';
        }
        
        if (array_search ($column_name, $this->list_columns) === 1) {
            $css_class .= ' column-primary';
        }
        
        if ($this->order_by === $column_name) {
            $css_class .= ' sorted ' . $this->order;
            return $css_class;
        }
        
        if (in_array($column_name, $this->sortables)) {
            $css_class .= ' sortable desc';
        }
        
        return $css_class;
    }
    
    protected function headRow()
    {
        echo '<tr>';
        foreach ($this->list_columns as $list_column) {
            $method = $this->purgeString($list_column) . 'Head';
            if (method_exists($this, $method)) {
                $this->$method($list_column);
            } else {
                $this->defaultHead($list_column);
            }
        }
        echo '</tr>';
    }
    
    protected function tableHead()
    {
        echo '<thead>';
        $this->headRow();
        echo '</thead>';
    }
    
    protected function tableBody()
    {   
        if (empty($this->list_data)) {
            echo '<tr class="no-items">';
            echo '<td class="colspanchange" colspan="' . count($this->list_columns) . '">';
            echo esc_html($this->lang->getText('no_items_found'));
            echo '</td></tr>';
            return;
        }
        
        foreach ($this->list_data as $item) {
            echo '<tr id="' . esc_attr($this->type . '-' . $item->id) . '" class="iedit author-self level-0 type-' . esc_attr($this->type) . ' hentry" data-gf-itemid="' . absint($item->id) . '">';
            foreach ($this->list_columns as $index => $list_column) {
                $method = $list_column . 'Cell';
                if (method_exists($this, $method)) {
                    $this->$method($index, $list_column, $item);
                } else {
                    $this->defaultCell($index, $list_column, $item);
                }
            }
            echo '</tr>';
        }
    }
    
    protected function tableFoot()
    {
        echo '<tfoot>';
        $this->headRow();
        echo '</tfoot>';
    }
    
    protected function checkBoxHead()
    {
        echo '<td id="cb" class="manage-column column-cb check-column">';
        echo '<label class="screen-reader-text" for="cb-select-all-1">Select All</label><input id="cb-select-all-1" type="checkbox"></td>';
    }
    
    protected function checkBoxCell($index, $list_column, $item)
    {
        echo '<th scope="row" class="check-column">';
        echo '<input id="cb-select-' . absint($item->id) . '" type="checkbox"';
        echo ' class="griffinforms-listitem-cb"';
        echo ' value="' . absint($item->id) . '">';
        echo '</th>';
    }
    
    protected function defaultHead($list_column) {
        echo '<th scope="col" id="' . esc_attr($list_column) . '" ';
        echo 'class="' . esc_attr($this->thClasses($list_column)) . '" abbr="' . esc_attr($list_column) . '">';
        
        if (in_array($list_column, $this->sortables)) {
            $this->sortableHeading($list_column);
        } else {
            $this->standardHeading($list_column);
        }
        
        echo '</th>';
    }
        
    protected function defaultCell($index, $list_column, $item) {
        if ($index === 1) {
            $this->primaryCell($list_column, $item);
        } else {
            $this->secondaryCell($list_column, $item);;
        }
    }
    
    protected function sortableHeading($list_column)
    {
        $text = $this->purgeString($list_column) . 'HeadingText';
        echo '<a href="' . esc_url($this->sortUrl($list_column)) . '">';
        $this->$text($list_column);
        echo '<span class="sorting-indicators"><span class="sorting-indicator asc" aria-hidden="true"></span>';
        echo '<span class="sorting-indicator desc" aria-hidden="true"></span></span></a>';
    }
    
    protected function standardHeading($list_column)
    {
        $heading_text = $this->purgeString($list_column) . 'HeadingText';
                
        if (method_exists($this, $heading_text)) {
            $this->$heading_text($list_column);
        } else {
            echo '<span>' . esc_html($this->lang->getText($list_column . 'list_head')) . '</span>';
        }
        
    }
    
    protected function sortUrl($list_column)
    {
        $url_attrs = array_map('sanitize_text_field', $_GET);

        if ($this->order_by === $list_column) {
            // Flip the order when the same column is clicked
            $url_attrs['order'] = ($this->order === 'asc') ? 'desc' : 'asc';
        }

        // Always set the column to order by
        $url_attrs['order_by'] = $list_column;

        // Construct the URL
        $url = get_admin_url() . 'admin.php?' . http_build_query($url_attrs);
        return $url;
    }

    protected function getItemUrl($item)
    {
        return get_admin_url() . 'admin.php?page=griffinforms-' . $this->type . '&id=' . $item->id;
    }
    
    protected function primaryCell($list_column, $item)
    {
        $css_classes = $list_column . ' column-' . $list_column . ' has-row-actions column-primary ' . $this->type . '-' . $list_column;
        $item_url = get_admin_url() . 'admin.php?page=griffinforms-' . $this->type . '&id=' . $item->id;
        $text = $list_column . 'CellText';
        
        echo '<td class="' . esc_attr($css_classes) . ' text-truncate">';
        echo '<strong><a class="row-title" href="' . esc_url($this->getItemUrl($item)) . '">';
        
        if (method_exists($this, $text)) {
            $this->$text($list_column, $item);
        } else {
            echo esc_html($item->$list_column);
        }
        
        echo '</a></strong>';
        $this->rowActions($item);
        echo '</td>';
    }
    
    protected function secondaryCell($list_column, $item)
    {
        $css_classes = $list_column . ' column-' . $list_column;

        echo '<td class="' . esc_attr($css_classes) . ' text-truncate">';

        $base_method = str_replace('_', '', $list_column) . 'CellText';

        // Check for a stored variant preference and try the variant method first.
        $variant_method = '';
        if (isset($this->column_prefs)) {
            $prefs       = $this->column_prefs->load((string) $this->type);
            $variant_key = $prefs['variants'][$list_column] ?? '';
            if ($variant_key !== '') {
                $variant_method = $base_method . ucfirst($variant_key);
            }
        }

        if ($variant_method !== '' && method_exists($this, $variant_method)) {
            $this->$variant_method($list_column, $item);
        } elseif (method_exists($this, $base_method)) {
            $this->$base_method($list_column, $item);
        } else {
            // Third-party columns: fire action hook instead of method dispatch.
            // Hook name: griffinforms_column_cell_{list_type}_{column_key}
            $action = 'griffinforms_column_cell_'
                    . sanitize_key((string) $this->type) . '_'
                    . sanitize_key($list_column);
            if (has_action($action)) {
                do_action($action, $item, $list_column);
            } else {
                // Final fallback: direct property access with escaping.
                echo esc_html($item->$list_column ?? '');
            }
        }

        echo '</td>';
    }

    protected function nameCellText($list_column, $item)
    {
        $name = empty($item->name) ? '<em>' . $this->lang->getText('name_not_set') . '</em>': $item->name;
        echo wp_kses_post($name);
    }
    
    protected function nameHeadingText($list_column)
    {
        echo '<span>' . esc_html($this->lang->getText($list_column, 'list_head')) . '</span>';
    }
    
    protected function authorHeadingText($list_column)
    {
        echo '<span>' . esc_html($this->lang->getText($list_column, 'list_head')) . '</span>';
    }
    
    protected function createdHeadingText($list_column)
    {
        echo '<span>' . esc_html($this->lang->getText($list_column, 'list_head')) . '</span>';
    }
    
    protected function formHeadingText($list_column)
    {
        echo '<span>' . esc_html($this->lang->getText($list_column, 'list_head')) . '</span>';
    }
    
    protected function authorCellText($list_item, $item)
    {
        $author_id = $item->author;
        $user = get_user_by('id', $author_id);


        if ($user === false) {
            echo esc_html($this->lang->getText('user_not_registered'));
        } else {
            echo '<a target="_blank" href="' . esc_url(get_edit_profile_url($author_id)) . '">';
            echo esc_html($user->user_nicename);
            echo '</a>';
            echo '<br>';
            echo '<span class="small text-muted">';
            echo esc_html($user->user_firstname . ' ' . $user->user_lastname);
            echo '</span>';
        }

    }

    protected function renderUserColumn(string $user_id_or_login): void
    {
        $user = get_user_by('id', $user_id_or_login)
             ?: get_user_by('login', $user_id_or_login);

        if (!$user) {
            echo '<span class="text-muted">' . esc_html($this->lang->getText('user_not_registered')) . '</span>';
            return;
        }

        echo '<a target="_blank" href="' . esc_url(get_edit_profile_url($user->ID)) . '">';
        echo esc_html($user->user_nicename);
        echo '</a><br><span class="small text-muted">';
        echo esc_html(trim($user->user_firstname . ' ' . $user->user_lastname));
        echo '</span>';
    }
    
    protected function lasteditorHeadingText($list_column)
    {
        echo '<span>' . esc_html__('Last Editor', 'griffinforms-form-builder') . '</span>';
    }

    protected function lasteditorCellText($list_column, $item)
    {
        $this->renderUserColumn((string) ($item->last_editor ?? ''));
    }

    protected function lasteditorCellTextNicename($list_column, $item)
    {
        $user = get_user_by('id', $item->last_editor ?? 0);
        echo $user ? esc_html($user->user_nicename) : '<span class="text-muted">—</span>';
    }

    protected function lasteditedCellText($list_column, $item)
    {
        $ts = strtotime($item->last_edited ?? '');
        if (!$ts) {
            echo '<span class="text-muted">—</span>';
            return;
        }
        echo esc_html(wp_date(get_option('date_format'), $ts));
        echo '<br> at ';
        echo esc_html(wp_date(get_option('time_format'), $ts));
    }

    protected function createdCellText($list_item, $item)
    {
        $item_date = strtotime($item->created);
        $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);
    }
    
    protected function rowActions($item)
    {
        echo '<div class="row-actions">';

        $last_key = array_key_last($this->row_actions);
        foreach ($this->row_actions as $index => $row_action) {
            echo '<span class="' . esc_attr($row_action) . '">';
            $method = 'rowAction' . str_replace('_', '', $row_action);
            if (method_exists($this, $method)) {
                $this->$method($item);
            } else {
                do_action('griffinforms_submissions_row_action_' . sanitize_key($row_action), $item);
            }
            if ($last_key !== $index) {
                echo ' | ';
            }
            echo '</span>';
        }

        echo '</div>';
    }
    
    protected function rowActionEdit($item)
    {
        $url = admin_url() . 'admin.php?page=griffinforms-' . $this->type . '&id=' . $item->id;
        echo '<a href="' . esc_url($url) . '">' . esc_html($this->lang->getText('edit', 'row_action')) . '</a>'; 
    }
    
    protected function rowActionTrash($item)
    {
        $nonce = wp_create_nonce('delete_item');
        echo '<a class="griffinforms-delete-list-item submitdelete" data-bs-target="#griffinforms-deletelistitem-modal" data-bs-toggle="modal" data-gf-id="' . absint($item->id) . '">' . esc_html($this->lang->getText('delete', 'row_action')) . '</a>'; 
    }
}