<?php

namespace Formatrica\Admin\Tables;

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

use Formatrica\Forms\Form_Repository;
use Formatrica\Submission\Submission_Repository;
use WP_List_Table;

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

class Form_List_Table extends WP_List_Table
{
    private Form_Repository $repository;
    private Submission_Repository $submission_repository;
    private string $status;

    public function __construct(?Form_Repository $repository = null, ?Submission_Repository $submission_repository = null)
    {
        $this->repository = $repository ?? new Form_Repository();
        $this->submission_repository = $submission_repository ?? new Submission_Repository();
        $this->status = isset($_GET['status']) ? sanitize_key(wp_unslash((string) $_GET['status'])) : 'active'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (!in_array($this->status, ['all', 'active', 'inactive'], true)) {
            $this->status = 'active';
        }

        parent::__construct([
            'singular' => __('Form', 'formatrica'),
            'plural' => __('Forms', 'formatrica'),
            'ajax' => false,
        ]);
    }

    public function get_columns(): array
    {
        return [
            'title' => __('Title', 'formatrica'),
            'shortcode' => __('Shortcode', 'formatrica'),
            'submissions' => __('# Submissions', 'formatrica'),
            'created' => __('Created', 'formatrica'),
        ];
    }

    protected function get_sortable_columns(): array
    {
        return [
            'title' => ['title', false],
            'created' => ['date', true],
        ];
    }

    public function prepare_items(): void
    {
        $status = $this->status === 'all' ? null : $this->status;
        $forms = $this->repository->all($status);
        $forms = array_map(function (array $form): array {
            $form['submission_count'] = $this->submission_repository->count_for_form((int) ($form['id'] ?? 0));
            return $form;
        }, $forms);

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

    public function get_counts(): array
    {
        return $this->repository->counts();
    }

    protected function column_title($item): string
    {
        $form_id = (int) $item['id'];
        $is_active = (int) ($item['active'] ?? 1) === 1;

        $edit_link = add_query_arg([
            'page' => 'formatrica-builder',
            'form_id' => $form_id,
        ], admin_url('admin.php'));

        $duplicate_link = add_query_arg([
            'action' => 'formatrica_duplicate',
            'form_id' => $form_id,
            '_wpnonce' => wp_create_nonce('formatrica_duplicate_' . $form_id),
        ], admin_url('admin-post.php'));

        $delete_link = add_query_arg([
            'action' => 'formatrica_delete',
            'form_id' => $form_id,
            '_wpnonce' => wp_create_nonce('formatrica_delete_' . $form_id),
        ], admin_url('admin-post.php'));

        $activate_link = add_query_arg([
            'action' => 'formatrica_activate',
            'form_id' => $form_id,
            '_wpnonce' => wp_create_nonce('formatrica_activate_' . $form_id),
        ], admin_url('admin-post.php'));

        $delete_permanent_link = add_query_arg([
            'action' => 'formatrica_delete_permanent',
            'form_id' => $form_id,
            '_wpnonce' => wp_create_nonce('formatrica_delete_permanent_' . $form_id),
        ], admin_url('admin-post.php'));

        $actions = [];

        if ($is_active) {
            $actions['edit'] = sprintf('<a href="%s">%s</a>', esc_url($edit_link), esc_html__('Edit', 'formatrica'));
            $actions['duplicate'] = sprintf('<a href="%s">%s</a>', esc_url($duplicate_link), esc_html__('Duplicate', 'formatrica'));
            $actions['deactivate'] = sprintf(
                '<a href="%s" class="fmt-deactivate-form submitdelete" data-form-title="%s">%s</a>',
                esc_url($delete_link),
                esc_attr($item['title']),
                esc_html__('Deactivate', 'formatrica')
            );
            $actions['delete'] = sprintf(
                '<a href="%s" class="fmt-delete-form submitdelete" data-form-title="%s">%s</a>',
                esc_url($delete_permanent_link),
                esc_attr($item['title']),
                esc_html__('Delete permanently', 'formatrica')
            );
        } else {
            $actions['activate'] = sprintf(
                '<a href="%s" class="fmt-activate-form" data-form-title="%s">%s</a>',
                esc_url($activate_link),
                esc_attr($item['title']),
                esc_html__('Activate', 'formatrica')
            );
            $actions['delete'] = sprintf(
                '<a href="%s" class="fmt-delete-form submitdelete" data-form-title="%s">%s</a>',
                esc_url($delete_permanent_link),
                esc_attr($item['title']),
                esc_html__('Delete permanently', 'formatrica')
            );
        }

        $title_text = esc_html($item['title']);
        if ($is_active) {
            $title = sprintf('<strong><a href="%s">%s</a></strong>', esc_url($edit_link), $title_text);
        } else {
            // Inactive: do not link to editor, and show an inline status badge
            $title = sprintf('<strong class="fmt-form--inactive">%s <span class="fmt-status-badge">%s</span></strong>', $title_text, esc_html__('Inactive', 'formatrica'));
        }

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

    protected function column_shortcode($item): string
    {
        return sprintf('<code>[formatrica id="%d"]</code>', (int) $item['id']);
    }

    protected function column_submissions($item): string
    {
        $form_id = (int) ($item['id'] ?? 0);
        $count = (int) ($item['submission_count'] ?? 0);

        if ($count <= 0 || $form_id <= 0) {
            return '0';
        }

        $label = sprintf(
            /* translators: %d: number of submissions */
            _n('%d submission', '%d submissions', $count, 'formatrica'),
            $count
        );
        $label = esc_html($label);

        $export_url = add_query_arg([
            'action' => 'formatrica_export',
            'form_id' => $form_id,
            '_wpnonce' => wp_create_nonce('formatrica_export_' . $form_id),
        ], admin_url('admin-post.php'));

        $gate = \Formatrica\Capability\Feature_Gate::get_default();
        if ($gate !== null && $gate->has(\Formatrica\Capability\Capabilities::SUBMISSIONS_PREVIEW)) {
            // Pro: the count opens the submissions list pre-filtered to this
            // form; the direct CSV download stays as a secondary action.
            $list_url = add_query_arg([
                'page' => 'formatrica-submissions',
                'form_id' => $form_id,
            ], admin_url('admin.php'));

            return sprintf(
                '<a href="%s">%s</a> <span class="row-actions" style="display:inline"><span class="export">| <a href="%s">%s</a></span></span>',
                esc_url($list_url),
                $label,
                esc_url($export_url),
                esc_html__('CSV', 'formatrica')
            );
        }

        // Free: the count is the CSV download, as before.
        return sprintf('<a href="%s">%s</a>', esc_url($export_url), $label);
    }

    protected function column_created($item): string
    {
        $time = isset($item['date']) ? strtotime($item['date']) : false;

        if (!$time) {
            return '&#8212;';
        }

        return esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $time));
    }

    public function no_items(): void
    {
        echo esc_html__('No forms found yet. Create your first form!', 'formatrica');
    }
}
