<?php

namespace Formatrica\Admin\Tables;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Formatrica\Submission\Submission_Repository;

if (!class_exists('WP_List_Table')) {
    require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}

/**
 * Submissions admin list (Free surface)
 * columns UUID / Form / Status / Created / ID, form + status filters, search,
 * bulk delete, CSV export. The UUID cell carries the Pro preview trigger when
 * the package + capability allow it (P4; the wporg package renders plain text —
 * hide-not-lock).
 */
final class Submission_List_Table extends \WP_List_Table
{
    /** @var array<string, mixed> */
    private array $counts = ['total' => 0];

    public function __construct(private Submission_Repository $repo, private string $preview_mode = 'none')
    {
        parent::__construct([
            'singular' => 'submission',
            'plural' => 'submissions',
            'ajax' => false,
        ]);
    }

    public function get_columns(): array
    {
        return [
            'cb' => '<input type="checkbox" />',
            'uuid' => __('Submission UUID', 'formatrica'),
            'form' => __('Form', 'formatrica'),
            'status' => __('Status', 'formatrica'),
            'created_at' => __('Created', 'formatrica'),
            'id' => __('ID', 'formatrica'),
        ];
    }

    protected function get_sortable_columns(): array
    {
        return [
            'uuid' => ['uuid', false],
            'form' => ['form', false],
            'status' => ['status', false],
            'created_at' => ['created_at', true],
            'id' => ['id', false],
        ];
    }

    protected function get_bulk_actions(): array
    {
        return [
            'mark_read'   => __('Mark as read', 'formatrica'),
            'mark_unread' => __('Mark as unread', 'formatrica'),
            'delete'      => __('Delete', 'formatrica'),
            'export'      => __('Export CSV', 'formatrica'),
        ];
    }

    public function prepare_items(): void
    {
        $per_page = 20;
        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- read-only list filters
        $args = [
            'form_id' => isset($_GET['form_id']) ? (int) $_GET['form_id'] : 0,
            'status' => isset($_GET['status']) ? sanitize_key(wp_unslash($_GET['status'])) : '',
            'search' => isset($_GET['s']) ? sanitize_text_field(wp_unslash($_GET['s'])) : '',
            'orderby' => isset($_GET['orderby']) ? sanitize_key(wp_unslash($_GET['orderby'])) : 'created_at',
            'order' => isset($_GET['order']) ? sanitize_key(wp_unslash($_GET['order'])) : 'desc',
            'per_page' => $per_page,
            'paged' => $this->get_pagenum(),
        ];
        // phpcs:enable

        $result = $this->repo->paginate($args);
        $this->items = $result['rows'];
        $this->counts['total'] = $result['total'];

        $this->set_pagination_args([
            'total_items' => $result['total'],
            'per_page' => $per_page,
            'total_pages' => (int) ceil($result['total'] / $per_page),
        ]);

        $this->_column_headers = [$this->get_columns(), [], $this->get_sortable_columns()];
    }

    protected function column_cb($item): string
    {
        return sprintf('<input type="checkbox" name="submission[]" value="%d" />', (int) $item['id']);
    }

    protected function column_uuid($item): string
    {
        $uuid = esc_html($item['uuid']);

        if ($this->preview_mode === 'open') {
            // Pro preview available: the UUID opens the preview dialog.
            $label = sprintf(
                '<a href="#" class="fmt-submission-preview" data-submission-id="%d"><code>%s</code></a>',
                (int) $item['id'],
                $uuid
            );
        } elseif ($this->preview_mode === 'locked') {
            // Full bundle without the capability: UUID with a locked badge.
            $label = sprintf(
                '<code>%s</code> <span class="fmt-pro-badge" title="%s">%s</span>',
                $uuid,
                esc_attr__('Submission preview is a Pro feature.', 'formatrica'),
                esc_html__('Pro', 'formatrica')
            );
        } else {
            // wporg package: plain text — hide, never lock.
            $label = '<code>' . $uuid . '</code>';
        }

        $actions = [];

        // Download PDF (Pro documents.pdf). Streamed by Submission_Pdf_Controller.
        $gate = \Formatrica\Capability\Feature_Gate::get_default();
        if ($gate !== null && $gate->has(\Formatrica\Capability\Capabilities::DOCUMENTS_PDF)) {
            $actions['pdf'] = sprintf(
                '<a href="%s">%s</a>',
                esc_url(wp_nonce_url(
                    admin_url('admin-post.php?action=formatrica_submission_pdf&submission_id=' . (int) $item['id']),
                    'formatrica_submission_pdf_' . (int) $item['id']
                )),
                esc_html__('Download PDF', 'formatrica')
            );
        }

        $mark_to = $item['status'] === 'read' ? 'new' : 'read';
        $actions['mark'] = sprintf(
            '<a href="%s">%s</a>',
            esc_url(wp_nonce_url(
                admin_url('admin-post.php?action=formatrica_mark_submission&submission_id=' . (int) $item['id'] . '&status=' . $mark_to),
                'formatrica_mark_submission_' . (int) $item['id']
            )),
            $item['status'] === 'read' ? esc_html__('Mark as unread', 'formatrica') : esc_html__('Mark as read', 'formatrica')
        );

        $actions['delete'] = sprintf(
            '<a href="%s" onclick="return confirm(%s);">%s</a>',
            esc_url(wp_nonce_url(
                admin_url('admin-post.php?action=formatrica_delete_submission&submission_id=' . (int) $item['id']),
                'formatrica_delete_submission_' . (int) $item['id']
            )),
            "'" . esc_js(__('Delete this submission permanently?', 'formatrica')) . "'",
            esc_html__('Delete', 'formatrica')
        );

        return $label . $this->row_actions($actions);
    }

    protected function column_form($item): string
    {
        $title = $item['form_title'] !== '' ? $item['form_title'] : __('(deleted form)', 'formatrica');
        $url = add_query_arg(['page' => 'formatrica-submissions', 'form_id' => (int) $item['form_id']], admin_url('admin.php'));
        return sprintf('<a href="%s">%s</a>', esc_url($url), esc_html($title));
    }

    protected function column_status($item): string
    {
        $status = $item['status'] === 'read' ? 'read' : 'new';
        $label = $status === 'read' ? __('Read', 'formatrica') : __('New', 'formatrica');
        return sprintf('<span class="fmt-status-badge fmt-status-badge--%s">%s</span>', esc_attr($status), esc_html($label));
    }

    protected function column_created_at($item): string
    {
        $timestamp = strtotime((string) $item['created_at']);
        if ($timestamp === false) {
            return esc_html((string) $item['created_at']);
        }
        return esc_html(wp_date(get_option('date_format') . ' ' . get_option('time_format'), $timestamp));
    }

    protected function column_id($item): string
    {
        return esc_html((string) (int) $item['id']);
    }

    protected function column_default($item, $column_name): string
    {
        return esc_html((string) ($item[$column_name] ?? ''));
    }

    /**
     * Form + status filter dropdowns above the table.
     */
    protected function extra_tablenav($which): void
    {
        if ($which !== 'top') {
            return;
        }

        // phpcs:disable WordPress.Security.NonceVerification.Recommended
        $current_form = isset($_GET['form_id']) ? (int) $_GET['form_id'] : 0;
        $current_status = isset($_GET['status']) ? sanitize_key(wp_unslash($_GET['status'])) : '';
        // phpcs:enable

        echo '<div class="alignleft actions">';

        echo '<select name="form_id">';
        echo '<option value="0">' . esc_html__('All forms', 'formatrica') . '</option>';
        foreach ($this->repo->forms_with_submissions() as $form) {
            printf(
                '<option value="%d"%s>%s</option>',
                (int) $form['id'],
                selected($current_form, (int) $form['id'], false),
                esc_html($form['title'])
            );
        }
        echo '</select>';

        echo '<select name="status">';
        echo '<option value="">' . esc_html__('All statuses', 'formatrica') . '</option>';
        printf('<option value="new"%s>%s</option>', selected($current_status, 'new', false), esc_html__('New', 'formatrica'));
        printf('<option value="read"%s>%s</option>', selected($current_status, 'read', false), esc_html__('Read', 'formatrica'));
        echo '</select>';

        submit_button(__('Filter', 'formatrica'), '', 'filter_action', false);
        // Export the checked submissions (respects the active filters, since the
        // checkboxes belong to the filtered list). Disabled until at least one
        // row is selected — see the enabling script in Submissions_Page.
        printf(
            ' <button type="submit" name="fmt_export" value="1" class="button" id="fmt-export-selected" disabled="disabled">%s</button>',
            esc_html__('Export CSV', 'formatrica')
        );
        echo '</div>';
    }

    public function no_items(): void
    {
        esc_html_e('No submissions yet.', 'formatrica');
    }
}
