<?php
/**
 * @var object       $invoice
 * @var object|null  $file
 * @var array        $auditTrail
 * @var array|null   $reportData
 * @var string       $downloadUrl
 * @var bool         $isStornoInvoice
 * @var string       $precedingNumber
 * @var object|null  $existingStorno
 */
if ( ! defined( 'ABSPATH' ) ) { exit; }

use Itdatex\Ausgangsrechnung\Admin\Menu;
use Itdatex\Ausgangsrechnung\PaymentHandler;
use Itdatex\Ausgangsrechnung\StornoHandler;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
// Rationale: view files are lexically included from Admin\Pages\* renderers,
// so every $var below is a file-local template variable, not a real global.
?>
<div class="wrap">
    <h1 class="wp-heading-inline">
        <?php esc_html_e( 'Rechnung', 'itdatex-e-invoice-output' ); ?>
        <?php echo esc_html( (string) ( $invoice->invoice_number ?: '#' . $invoice->id ) ); ?>
    </h1>
    <?php if ( $downloadUrl !== '' ) : ?>
        <a href="<?php echo esc_url( $downloadUrl ); ?>" class="page-title-action">
            <?php esc_html_e( 'XML herunterladen', 'itdatex-e-invoice-output' ); ?>
        </a>
    <?php endif; ?>
    <a href="<?php echo esc_url( add_query_arg(
        [ 'page' => Menu::SLUG_CREATE, 'buyer_from' => (int) $invoice->id ],
        admin_url( 'admin.php' )
    ) ); ?>" class="page-title-action">
        <?php esc_html_e( 'Neue Rechnung fuer diesen Kunden', 'itdatex-e-invoice-output' ); ?>
    </a>
    <a href="<?php echo esc_url( admin_url( 'admin.php?page=' . Menu::SLUG_LIST ) ); ?>" class="page-title-action">
        <?php esc_html_e( '← Liste', 'itdatex-e-invoice-output' ); ?>
    </a>
    <hr class="wp-header-end">

    <?php if ( $isStornoInvoice && $precedingNumber !== '' ) : ?>
        <div class="notice notice-warning inline" style="margin:1em 0">
            <p><strong><?php esc_html_e( 'STORNO', 'itdatex-e-invoice-output' ); ?></strong> —
                <?php
                /* translators: %s: Rechnungsnummer der Original-Rechnung */
                echo esc_html( sprintf( __( 'Korrektur-Rechnung zu %s (BT-3=384).', 'itdatex-e-invoice-output' ), $precedingNumber ) );
                ?>
            </p>
        </div>
    <?php elseif ( $existingStorno ) : ?>
        <div class="notice notice-warning inline" style="margin:1em 0">
            <p><strong><?php esc_html_e( 'Storniert.', 'itdatex-e-invoice-output' ); ?></strong>
                <?php
                $stornoUrl = add_query_arg(
                    [ 'page' => Menu::SLUG_DETAIL, 'id' => (int) $existingStorno->id ],
                    admin_url( 'admin.php' )
                );
                $link = '<a href="' . esc_url( $stornoUrl ) . '"><strong>'
                        . esc_html( (string) $existingStorno->invoice_number ) . '</strong></a>';
                echo wp_kses_post( sprintf(
                    /* translators: %s: HTML-Link zur Storno-Rechnung */
                    __( 'Storno-Rechnung: %s', 'itdatex-e-invoice-output' ),
                    $link
                ) );
                ?>
            </p>
        </div>
    <?php endif; ?>

    <?php
    $statusClass = match ( (string) $invoice->validation_status ) {
        'valid'    => 'notice-success',
        'warnings' => 'notice-warning',
        'invalid'  => 'notice-error',
        default    => 'notice-info',
    };
    ?>
    <div class="notice <?php echo esc_attr( $statusClass ); ?> inline">
        <p>
            <strong><?php esc_html_e( 'Validierung:', 'itdatex-e-invoice-output' ); ?></strong>
            <?php echo esc_html( (string) $invoice->validation_status ); ?>
            (errors: <?php echo (int) $invoice->validation_errors; ?>,
             warnings: <?php echo (int) $invoice->validation_warnings; ?>)
        </p>
    </div>

    <table class="form-table" role="presentation" style="margin-top:1em">
        <tr>
            <th><?php esc_html_e( 'Format', 'itdatex-e-invoice-output' ); ?></th>
            <td><?php echo esc_html( (string) $invoice->format ); ?></td>
        </tr>
        <tr>
            <th><?php esc_html_e( 'Ausgestellt am', 'itdatex-e-invoice-output' ); ?></th>
            <td><?php echo esc_html( (string) ( $invoice->issue_date ?: '—' ) ); ?></td>
        </tr>
        <tr>
            <th><?php esc_html_e( 'Faellig am', 'itdatex-e-invoice-output' ); ?></th>
            <td><?php echo esc_html( (string) ( $invoice->due_date ?: '—' ) ); ?></td>
        </tr>
        <tr>
            <th><?php esc_html_e( 'Kaeufer', 'itdatex-e-invoice-output' ); ?></th>
            <td><?php echo esc_html( (string) ( $invoice->buyer_name ?: '—' ) ); ?></td>
        </tr>
        <tr>
            <th><?php esc_html_e( 'Leitweg-ID', 'itdatex-e-invoice-output' ); ?></th>
            <td><?php echo esc_html( (string) ( $invoice->buyer_reference ?: '—' ) ); ?></td>
        </tr>
        <tr>
            <th><?php esc_html_e( 'Betraege', 'itdatex-e-invoice-output' ); ?></th>
            <td>
                <?php esc_html_e( 'Netto:', 'itdatex-e-invoice-output' ); ?>
                <strong><?php echo esc_html( number_format( (float) $invoice->total_net, 2, ',', '.' ) ); ?>
                    <?php echo esc_html( (string) $invoice->currency ); ?></strong>
                &nbsp;|&nbsp;
                <?php esc_html_e( 'MwSt:', 'itdatex-e-invoice-output' ); ?>
                <strong><?php echo esc_html( number_format( (float) $invoice->total_tax, 2, ',', '.' ) ); ?></strong>
                &nbsp;|&nbsp;
                <?php esc_html_e( 'Brutto:', 'itdatex-e-invoice-output' ); ?>
                <strong><?php echo esc_html( number_format( (float) $invoice->total_gross, 2, ',', '.' ) ); ?></strong>
            </td>
        </tr>
        <tr>
            <th><?php esc_html_e( 'Zahlung', 'itdatex-e-invoice-output' ); ?></th>
            <td>
                <?php
                $paymentStatus = (string) $invoice->payment_status;
                $paymentLabel  = match ( $paymentStatus ) {
                    'paid'     => __( 'bezahlt',  'itdatex-e-invoice-output' ),
                    'disputed' => __( 'strittig', 'itdatex-e-invoice-output' ),
                    default    => __( 'offen',    'itdatex-e-invoice-output' ),
                };
                ?>
                <strong><?php echo esc_html( $paymentLabel ); ?></strong>
                <?php if ( in_array( $paymentStatus, [ 'open', 'paid' ], true ) ) : ?>
                    <?php $newStatus = $paymentStatus === 'paid' ? 'open' : 'paid'; ?>
                    <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="display:inline; margin-left:1em">
                        <?php wp_nonce_field( PaymentHandler::ACTION . '_' . (int) $invoice->id, PaymentHandler::NONCE ); ?>
                        <input type="hidden" name="action"          value="<?php echo esc_attr( PaymentHandler::ACTION ); ?>">
                        <input type="hidden" name="invoice_id"      value="<?php echo (int) $invoice->id; ?>">
                        <input type="hidden" name="payment_status"  value="<?php echo esc_attr( $newStatus ); ?>">
                        <?php submit_button(
                            $newStatus === 'paid'
                                ? __( 'Als bezahlt markieren', 'itdatex-e-invoice-output' )
                                : __( 'Als offen markieren',   'itdatex-e-invoice-output' ),
                            'secondary',
                            'submit',
                            false
                        ); ?>
                    </form>
                <?php endif; ?>
            </td>
        </tr>
        <?php if ( $file ) : ?>
        <tr>
            <th><?php esc_html_e( 'Datei', 'itdatex-e-invoice-output' ); ?></th>
            <td>
                <?php echo esc_html( (string) $file->original_name ); ?>
                (<?php echo esc_html( size_format( (int) $file->size_bytes ) ); ?>,
                 <?php echo esc_html( (string) $file->mime ); ?>)
                <br>
                <code style="font-size:11px"><?php esc_html_e( 'SHA-256:', 'itdatex-e-invoice-output' ); ?>
                    <?php echo esc_html( (string) $file->sha256 ); ?></code>
            </td>
        </tr>
        <?php endif; ?>
    </table>

    <?php
    /**
     * Erweiterungspunkt fuer Pro-/Bundle-Plugins: KoSIT-Tiefenvalidierung
     * (Pro) haengt sich hier ein und rendert ihre Findings-Card. Spiegelt
     * 'reing_invoice_view_after_validation' aus dem Eingangs-Plugin.
     *
     * @param object     $invoice
     * @param array|null $reportData
     */
    do_action( 'ausrg_invoice_view_after_validation', $invoice, $reportData );
    ?>

    <?php
    // Nur Befunde rendern, die der Nutzer wirklich braucht: Errors und
    // Warnings. Severity 'info' enthaelt aktuell ausschliesslich
    // Plugin-eigene Hinweise (z.B. "UBL-XSD-Validierung kommt in einer
    // spaeteren Stufe"), die fuer jede UBL-Rechnung gleich sind und im
    // Detail-View nur Laerm verursachen. Wer sie braucht, kann ueber das
    // Filter den Default ueberschreiben.
    $issuesRaw = is_array( $reportData['issues'] ?? null ) ? $reportData['issues'] : [];
    $visible   = (array) apply_filters(
        'ausrg_detail_visible_severities',
        [ 'error', 'warning' ]
    );
    $issues = array_values( array_filter(
        $issuesRaw,
        static fn( $iss ) => in_array( (string) ( $iss['severity'] ?? '' ), $visible, true )
    ) );
    $order  = [ 'error' => 0, 'warning' => 1, 'info' => 2 ];
    usort( $issues, static function ( $a, $b ) use ( $order ) {
        $sa = $order[ (string) ( $a['severity'] ?? 'info' ) ] ?? 9;
        $sb = $order[ (string) ( $b['severity'] ?? 'info' ) ] ?? 9;
        return $sa <=> $sb;
    } );
    ?>
    <?php if ( $issues !== [] ) : ?>
        <h2>
            <?php esc_html_e( 'Validierungs-Befunde', 'itdatex-e-invoice-output' ); ?>
            <span class="title-count" style="color:#50575e;font-size:14px">(<?php echo (int) count( $issues ); ?>)</span>
        </h2>
        <table class="wp-list-table widefat striped">
            <thead><tr>
                <th style="width:6em"><?php esc_html_e( 'Schwere',  'itdatex-e-invoice-output' ); ?></th>
                <th style="width:5em"><?php esc_html_e( 'Quelle',   'itdatex-e-invoice-output' ); ?></th>
                <th><?php esc_html_e( 'Meldung', 'itdatex-e-invoice-output' ); ?></th>
            </tr></thead>
            <tbody>
            <?php foreach ( $issues as $iss ) :
                $sev = (string) ( $iss['severity'] ?? 'info' );
                [ $bg, $fg, $label ] = match ( $sev ) {
                    'error'   => [ '#fcebec', '#b32d2e', __( 'Fehler',  'itdatex-e-invoice-output' ) ],
                    'warning' => [ '#fcf9e8', '#8a6d09', __( 'Warnung', 'itdatex-e-invoice-output' ) ],
                    default   => [ '#f0f6fc', '#2271b1', __( 'Hinweis', 'itdatex-e-invoice-output' ) ],
                };
                ?>
                <tr>
                    <td>
                        <span style="display:inline-block;padding:1px 8px;border-radius:2px;background:<?php echo esc_attr( $bg ); ?>;color:<?php echo esc_attr( $fg ); ?>;font-size:11px;font-family:monospace">
                            <?php echo esc_html( $label ); ?>
                        </span>
                    </td>
                    <td><code style="font-size:11px"><?php echo esc_html( (string) ( $iss['source'] ?? '' ) ); ?></code></td>
                    <td><?php echo esc_html( (string) ( $iss['message'] ?? '' ) ); ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    <?php elseif ( $reportData !== null && (string) $invoice->validation_status === 'valid' ) : ?>
        <p class="description" style="margin-top:1em">
            <?php esc_html_e( 'Validierung sauber — keine Befunde von Schema, XSD oder Pflichtfeld-Plausibilitaet.', 'itdatex-e-invoice-output' ); ?>
        </p>
    <?php endif; ?>

    <?php if ( ! $isStornoInvoice && ! $existingStorno ) : ?>
        <h2><?php esc_html_e( 'Aktionen', 'itdatex-e-invoice-output' ); ?></h2>
        <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"
              onsubmit="return confirm(<?php echo esc_attr( wp_json_encode(
                  __( 'Diese Rechnung wirklich stornieren? Eine neue Korrektur-Rechnung (BT-3=384) mit negierten Betraegen wird ausgestellt und mit BT-25 auf die Original-Rechnung verweisen.', 'itdatex-e-invoice-output' )
              ) ); ?>);">
            <?php wp_nonce_field( StornoHandler::ACTION . '_' . (int) $invoice->id, StornoHandler::NONCE ); ?>
            <input type="hidden" name="action"     value="<?php echo esc_attr( StornoHandler::ACTION ); ?>">
            <input type="hidden" name="invoice_id" value="<?php echo (int) $invoice->id; ?>">
            <?php submit_button(
                __( 'Rechnung stornieren', 'itdatex-e-invoice-output' ),
                'delete',
                'submit',
                false
            ); ?>
            <span class="description" style="margin-left:1em">
                <?php esc_html_e(
                    'Erzeugt eine Korrektur-Rechnung mit negierten Positionen und Bezug auf diese Rechnung.',
                    'itdatex-e-invoice-output'
                ); ?>
            </span>
        </form>
    <?php endif; ?>

    <?php if ( $auditTrail !== [] ) : ?>
        <h2><?php esc_html_e( 'Audit-Trail', 'itdatex-e-invoice-output' ); ?></h2>
        <table class="wp-list-table widefat striped">
            <thead><tr>
                <th><?php esc_html_e( 'Zeitpunkt', 'itdatex-e-invoice-output' ); ?></th>
                <th><?php esc_html_e( 'Akteur', 'itdatex-e-invoice-output' ); ?></th>
                <th><?php esc_html_e( 'Aktion', 'itdatex-e-invoice-output' ); ?></th>
                <th><?php esc_html_e( 'Detail', 'itdatex-e-invoice-output' ); ?></th>
            </tr></thead>
            <tbody>
            <?php foreach ( $auditTrail as $a ) : ?>
                <tr>
                    <td><?php echo esc_html( (string) $a->created_at ); ?></td>
                    <td><?php echo esc_html( (string) $a->actor ); ?></td>
                    <td><?php echo esc_html( (string) $a->action ); ?></td>
                    <td><?php echo esc_html( (string) $a->detail ); ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>
