<?php
declare(strict_types=1);

namespace Itdatex\Ausgangsrechnung\Admin\Pages;

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

use Itdatex\Ausgangsrechnung\Admin\Menu;
use Itdatex\Ausgangsrechnung\DownloadHandler;
use Itdatex\Ausgangsrechnung\Plugin;
use Itdatex\Ausgangsrechnung\StornoService;
use Itdatex\EInvoiceCore\InvoiceRepository;

/**
 * Read-only Detail-Ansicht einer ausgegangenen Rechnung.
 */
final class InvoiceDetail
{
    public function register(): void
    {
        add_filter( 'admin_title', [ self::class, 'filter_admin_title' ], 10, 2 );
    }

    public static function filter_admin_title( string $admin_title, string $title ): string
    {
        if ( $title !== '' ) {
            return $admin_title;
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin-title filter, kein State-Change.
        $page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( (string) $_GET['page'] ) ) : '';
        if ( $page !== Menu::SLUG_DETAIL ) {
            return $admin_title;
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin-title filter, kein State-Change.
        $id    = isset( $_GET['id'] ) ? (int) $_GET['id'] : 0;
        $label = __( 'Rechnung', 'itdatex-e-invoice-output' );
        if ( $id > 0 ) {
            $invoice = ( new InvoiceRepository( 'outgoing' ) )->findInvoice( $id );
            if ( $invoice && ! empty( $invoice->invoice_number ) ) {
                $label .= ' ' . (string) $invoice->invoice_number;
            }
        }
        return $label . $admin_title;
    }

    public static function render(): void
    {
        if ( ! current_user_can( Plugin::CAPABILITY ) ) {
            wp_die( esc_html__( 'Keine Berechtigung.', 'itdatex-e-invoice-output' ), '', [ 'response' => 403 ] );
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only view, keine Mutation ohne separaten Nonce-Check.
        $id   = isset( $_GET['id'] ) ? (int) $_GET['id'] : 0;
        $repo = new InvoiceRepository( 'outgoing' );
        $invoice = $id > 0 ? $repo->findInvoice( $id ) : null;

        // Sicherheit: nur outgoing-Rechnungen in dieser View anzeigen
        if ( $invoice && (string) $invoice->direction !== 'outgoing' ) {
            $invoice = null;
        }
        if ( ! $invoice ) {
            echo '<div class="wrap"><h1>' . esc_html__( 'Rechnung nicht gefunden', 'itdatex-e-invoice-output' ) . '</h1>';
            echo '<p><a href="' . esc_url( admin_url( 'admin.php?page=' . Menu::SLUG_LIST ) ) . '">'
                . esc_html__( '← Zurueck zur Liste', 'itdatex-e-invoice-output' ) . '</a></p></div>';
            return;
        }

        $file       = $repo->findFile( (int) $invoice->file_id );
        $auditTrail = $repo->auditForInvoice( (int) $invoice->id );
        $reportData = $invoice->validation_report ? json_decode( (string) $invoice->validation_report, true ) : null;
        $downloadUrl = $file ? wp_nonce_url(
            add_query_arg(
                [ 'action' => DownloadHandler::ACTION, 'file_id' => (int) $file->id ],
                admin_url( 'admin-post.php' )
            ),
            DownloadHandler::ACTION . '_' . (int) $file->id,
            DownloadHandler::NONCE
        ) : '';

        // Storno-Beziehung ermitteln.
        $meta               = json_decode( (string) ( $invoice->raw_meta ?? '' ), true );
        $isStornoInvoice    = is_array( $meta ) && (int) ( $meta['invoice']['type_code'] ?? 380 ) === StornoService::TYPE_CODE_CORRECTED;
        $precedingNumber    = is_array( $meta ) ? (string) ( $meta['invoice']['preceding_number'] ?? '' ) : '';
        $existingStorno     = ( ! $isStornoInvoice ) ? ( new StornoService( $repo ) )->findStornoFor( (int) $invoice->id ) : null;

        include AUSRG_DIR . 'admin/views/page-detail.php';
    }
}
