<?php

namespace Formatrica\Admin\Pages;

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

use Formatrica\Admin\Tables\Form_List_Table;

final class Form_List_Page
{
    private ?Form_List_Table $table = null;

    public function load(): void
    {
        $this->ensure_table();
        $this->table->prepare_items();
    }

    public function render(): void
    {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to access this page.', 'formatrica'));
        }

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

        $icon_url = FORMATRICA_URL . 'assets/formatrica.svg';

        echo '<div class="wrap">';
        echo '<h1 class="wp-heading-inline"><img src="' . esc_url($icon_url) . '" alt="' . esc_attr__('Formatrica', 'formatrica') . '" style="width:24px;height:24px;margin-right:8px;vertical-align:middle;" />' . esc_html__('Forms', 'formatrica') . '</h1>';
        echo '<a href="' . esc_url($create_url) . '" class="page-title-action">' . esc_html__('Add New', 'formatrica') . '</a>';
        echo '<hr class="wp-header-end" />';

        $this->print_views();
        $this->ensure_table();

        echo '<form method="post">';
        $this->table->display();
        echo '</form>';
        echo '</div>';

        $this->print_delete_script();
    }

    private function current_status(): string
    {
        $status = isset($_GET['status']) ? sanitize_key(wp_unslash((string) $_GET['status'])) : 'active'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (!in_array($status, ['all', 'active', 'inactive'], true)) {
            $status = 'active';
        }
        return $status;
    }

    private function print_views(): void
    {
        $status = $this->current_status();

        $counts = $this->table->get_counts();

        $base = admin_url('admin.php');
        $page_param = ['page' => 'formatrica'];

        $views = [
            'all' => [
                'label' => __('All', 'formatrica'),
                'count' => (int) ($counts['all'] ?? 0),
            ],
            'active' => [
                'label' => __('Active', 'formatrica'),
                'count' => (int) ($counts['active'] ?? 0),
            ],
            'inactive' => [
                'label' => __('Inactive', 'formatrica'),
                'count' => (int) ($counts['inactive'] ?? 0),
            ],
        ];

        echo '<ul class="subsubsub">';
        $i = 0;
        foreach ($views as $key => $view) {
            $url = add_query_arg(array_merge($page_param, ['status' => $key]), $base);
            $current_class = $status === $key ? 'current' : '';
            $sep = $i++ === 2 ? '' : ' | ';
            printf(
                '<li class="%1$s"><a href="%2$s" class="%3$s">%4$s <span class="count">(%5$d)</span></a>%6$s</li>',
                esc_attr($key),
                esc_url($url),
                esc_attr($current_class),
                esc_html($view['label']),
                (int) $view['count'],
                esc_html($sep)
            );
        }
        echo '</ul>';
    }

    private function print_delete_script(): void
    {
        $css = '.fmt-delete-form{color:#b32d2e !important}'
            . '.fmt-delete-form:hover{color:#dc3232 !important}'
            . '.fmt-deactivate-form{color:#d63638 !important}'
            . '.fmt-deactivate-form:hover{color:#cc181a !important}'
            . '.fmt-form--inactive{color:#646970}'
            . '.fmt-status-badge{background:#dcdcde;color:#3c434a;padding:2px 6px;border-radius:3px;font-size:11px;margin-left:6px;vertical-align:middle}';

        $css = wp_kses_no_null($css, ['slash_zero' => 'keep']);
        $css = preg_replace('#</style#i', '<\\/style', $css);
        wp_register_style('formatrica-form-list', false, [], FORMATRICA_VERSION);
        wp_enqueue_style('formatrica-form-list');
        wp_add_inline_style('formatrica-form-list', $css);

        $js_data = [
            'thisForm'       => __('this form', 'formatrica'),
            'confirmDelete'  => __('Are you sure you want to permanently delete', 'formatrica'),
            'deleteWarning'  => __('This will permanently delete the form and all its submissions. This action cannot be undone.', 'formatrica'),
            'deactivateForm' => __('Deactivate form', 'formatrica'),
            'deactivateNote' => __('The form will be disabled on the front\u2011end but submissions will be retained. You can delete permanently later.', 'formatrica'),
        ];

        $js = '(function(){document.addEventListener("DOMContentLoaded",function(){'
            . 'var i18n=' . wp_json_encode($js_data) . ';'
            . 'document.querySelectorAll(".fmt-delete-form").forEach(function(l){'
            . 'l.addEventListener("click",function(e){'
            . 'var t=this.dataset.formTitle||i18n.thisForm;'
            . 'if(!confirm(i18n.confirmDelete+" \""+t+"\"?\\n\\n"+i18n.deleteWarning)){e.preventDefault()}'
            . '})});'
            . 'document.querySelectorAll(".fmt-deactivate-form").forEach(function(l){'
            . 'l.addEventListener("click",function(e){'
            . 'var t=this.dataset.formTitle||i18n.thisForm;'
            . 'if(!confirm(i18n.deactivateForm+": \""+t+"\"?\\n\\n"+i18n.deactivateNote)){e.preventDefault()}'
            . '})});'
            . '})})();';

        $js = wp_kses_no_null($js, ['slash_zero' => 'keep']);
        $js = preg_replace('#</script#i', '<\\/script', $js);
        wp_register_script('formatrica-form-list', false, [], FORMATRICA_VERSION, true);
        wp_enqueue_script('formatrica-form-list');
        wp_add_inline_script('formatrica-form-list', $js);
    }

    private function ensure_table(): void
    {
        if (null === $this->table) {
            if (!function_exists('convert_to_screen')) {
                require_once ABSPATH . 'wp-admin/includes/template.php';
            }

            $this->table = new Form_List_Table();
        }
    }
}
