<?php
namespace BLR\Backline\Core;

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

final class Views {
    public static function render(string $view, array $ctx = []): string {
        $view = ltrim($view, '/');
        $path = BLR_BA_DIR . 'app/Views/' . $view . '.php';
        if (!file_exists($path)) {
            return '<div class="container-fluid p-0"><div class="alert alert-danger">' . esc_html__('Missing view:', 'blr-backline') . ' ' . esc_html($view) . '</div></div>';
        }

        ob_start();
        $ctx = $ctx;
        include $path;
        return (string) ob_get_clean();
    }

    public static function render_layout(array $ctx, string $page_html): void {
        $layout_name = (string)($ctx['layout'] ?? 'app');
        $layout = BLR_BA_DIR . 'app/Views/layouts/' . ($layout_name === 'auth' ? 'auth.php' : 'app.php');
        if (!file_exists($layout)) {
            header('Content-Type: text/html; charset=utf-8');
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Internal plugin view HTML.
            echo $page_html;
            return;
        }

        $ctx['page_html'] = $page_html;
        include $layout;
    }

    public static function current_page_from_query_arg(string $arg = 'pg'): int {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only pagination query arg.
        $value = isset($_GET[$arg]) ? absint((string) wp_unslash($_GET[$arg])) : 1;
        return max(1, $value);
    }

    public static function pagination_summary_data(\WP_Query $query, string $arg = 'pg'): array {
    $total = (int) ($query->found_posts ?? 0);
    $per_page = (int) ($query->get('posts_per_page') ?: 0);
    $current_page = self::current_page_from_query_arg($arg);

    if ($total <= 0 || $per_page <= 0) {
        return [
            'total' => 0,
            'from' => 0,
            'to' => 0,
            'current_page' => $current_page,
            'per_page' => $per_page,
        ];
    }

    $from = (($current_page - 1) * $per_page) + 1;
    $to = min($current_page * $per_page, $total);

    return [
        'total' => $total,
        'from' => $from,
        'to' => $to,
        'current_page' => $current_page,
        'per_page' => $per_page,
    ];
}


    public static function delete_error_message_from_query_arg(string $arg = 'delete_error'): string {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only query arg for user-facing flash notices.
        $code = isset($_GET[$arg]) ? sanitize_key((string) wp_unslash($_GET[$arg])) : '';

        switch ($code) {
            case 'missing_id':
                return __('Nothing could be deleted because the record ID was missing.', 'blr-backline');
            case 'invalid_method':
                return __('Delete requests must be submitted from the delete form.', 'blr-backline');
            case 'invalid_nonce':
                return __('That delete request expired or failed the security check. Refresh the page and try again.', 'blr-backline');
            case 'forbidden':
                return __('You do not have permission to delete that record.', 'blr-backline');
            case 'delete_failed':
                return __('The record could not be deleted. Please try again.', 'blr-backline');
            default:
                return '';
        }
    }

    public static function render_pagination_summary(\WP_Query $query, string $label = 'posts', string $arg = 'pg'): string {
        $data = self::pagination_summary_data($query, $arg);

        if ($data['total'] <= 0) {
            return sprintf(
                /* translators: 1: number currently shown, 2: total number of items, 3: item label. */
                esc_html__('Viewing %1$s of %2$s %3$s', 'blr-backline'),
                number_format_i18n(0),
                number_format_i18n(0),
                esc_html($label)
            );
        }

        return sprintf(
            /* translators: 1: first item number on the page, 2: last item number on the page, 3: total number of items, 4: item label. */
            esc_html__('Viewing %1$s–%2$s of %3$s %4$s', 'blr-backline'),
            number_format_i18n($data['from']),
            number_format_i18n($data['to']),
            number_format_i18n($data['total']),
            esc_html($label)
        );
    }

    public static function render_pagination(\WP_Query $query, string $base_url, string $arg = 'pg'): string {
        $total_pages = (int) ($query->max_num_pages ?? 0);
        if ($total_pages <= 1) {
            return '';
        }

        $current_page = self::current_page_from_query_arg($arg);
        $query_args = [];
        foreach ((array) $_GET as $key => $value) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only query args for pagination links.
            $key = sanitize_key((string) $key);
            if ($key === '' || $key === $arg) {
                continue;
            }

            if (is_array($value)) {
                $query_args[$key] = array_map('sanitize_text_field', wp_unslash($value));
            } else {
                $query_args[$key] = sanitize_text_field((string) wp_unslash($value));
            }
        }

        $base = add_query_arg(array_merge($query_args, [$arg => '%#%']), $base_url);
        $links = paginate_links([
            'base'      => $base,
            'format'    => '',
            'current'   => $current_page,
            'total'     => $total_pages,
            'type'      => 'array',
            'prev_text' => '&laquo;',
            'next_text' => '&raquo;',
        ]);

        if (empty($links) || !is_array($links)) {
            return '';
        }

        $html = '<nav class="mt-3" aria-label="' . esc_attr__('Pagination', 'blr-backline') . '"><ul class="pagination mb-0">';
        foreach ($links as $link) {
            $html .= '<li class="page-item">' . str_replace('page-numbers', 'page-link', $link) . '</li>';
        }
        $html .= '</ul></nav>';

        return $html;
    }
}
