<?php
/**
 * @var array  $sticky
 * @var array  $errors
 * @var int    $rows
 * @var string $today
 * @var string $defaultDue
 * @var string $action_url
 */
if ( ! defined( 'ABSPATH' ) ) { exit; }

use Itdatex\Ausgangsrechnung\Admin\Pages\CreatePage;

// 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.

$inv   = (array) ( $sticky['invoice'] ?? [] );
$buyer = (array) ( $sticky['buyer']   ?? [] );
$lines = (array) ( $sticky['lines']   ?? [] );

$val = static fn( array $arr, string $k, string $default = '' ): string
    => isset( $arr[ $k ] ) ? (string) $arr[ $k ] : $default;
?>
<div class="wrap">
    <h1><?php esc_html_e( 'Neue Ausgangsrechnung', 'itdatex-e-invoice-output' ); ?></h1>

    <?php if ( $errors !== [] ) : ?>
        <div class="notice notice-error"><ul style="margin:1em 1.5em; list-style:disc;">
            <?php foreach ( $errors as $err ) : ?>
                <li><?php echo esc_html( $err ); ?></li>
            <?php endforeach; ?>
        </ul></div>
    <?php endif; ?>

    <form method="post" action="<?php echo esc_url( $action_url ); ?>">
        <?php wp_nonce_field( CreatePage::ACTION, CreatePage::NONCE ); ?>

        <h2><?php esc_html_e( 'Kopfdaten', 'itdatex-e-invoice-output' ); ?></h2>
        <table class="form-table" role="presentation">
            <tr>
                <th><label for="inv_number"><?php esc_html_e( 'Rechnungs-Nr.', 'itdatex-e-invoice-output' ); ?> *</label></th>
                <td><input name="invoice[number]" id="inv_number" type="text" class="regular-text" required
                    value="<?php echo esc_attr( $val( $inv, 'number' ) ); ?>"></td>
            </tr>
            <tr>
                <th><label for="inv_issue"><?php esc_html_e( 'Rechnungsdatum', 'itdatex-e-invoice-output' ); ?> *</label></th>
                <td><input name="invoice[issue_date]" id="inv_issue" type="date" required
                    value="<?php echo esc_attr( $val( $inv, 'issue_date', $today ) ); ?>"></td>
            </tr>
            <tr>
                <th><label for="inv_due"><?php esc_html_e( 'Faellig am', 'itdatex-e-invoice-output' ); ?></label></th>
                <td><input name="invoice[due_date]" id="inv_due" type="date"
                    value="<?php echo esc_attr( $val( $inv, 'due_date', $defaultDue ) ); ?>"></td>
            </tr>
            <tr>
                <th><label for="inv_delivery"><?php esc_html_e( 'Liefer-/Leistungsdatum', 'itdatex-e-invoice-output' ); ?></label></th>
                <td><input name="invoice[delivery_date]" id="inv_delivery" type="date"
                    value="<?php echo esc_attr( $val( $inv, 'delivery_date' ) ); ?>">
                    <p class="description"><?php esc_html_e(
                        'BR-DE-TMP-32: das Liefer-/Leistungsdatum (BT-72) sollte gesetzt sein, sonst alternativ ein Leistungszeitraum (BG-14). Leer = Rechnungsdatum gilt als Leistungsdatum.',
                        'itdatex-e-invoice-output'
                    ); ?></p></td>
            </tr>
            <tr>
                <th><label for="inv_currency"><?php esc_html_e( 'Waehrung', 'itdatex-e-invoice-output' ); ?></label></th>
                <td><input name="invoice[currency]" id="inv_currency" type="text" maxlength="3" class="small-text"
                    value="<?php echo esc_attr( $val( $inv, 'currency', 'EUR' ) ); ?>"></td>
            </tr>
            <tr>
                <th><label for="inv_format"><?php esc_html_e( 'Format', 'itdatex-e-invoice-output' ); ?> *</label></th>
                <td>
                    <select name="invoice[format]" id="inv_format" required>
                        <?php
                        $curFmt = $val( $inv, 'format', \Itdatex\Ausgangsrechnung\IssueService::FORMAT_UBL );
                        foreach ( \Itdatex\Ausgangsrechnung\IssueService::supportedFormats() as $code => $label ) :
                        ?>
                            <option value="<?php echo esc_attr( $code ); ?>" <?php selected( $curFmt, $code ); ?>><?php echo esc_html( $label ); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="description"><?php esc_html_e(
                        'UBL ist das typische B2G-Format ueber Leitweg-ID. CII ist die ZUGFeRD-/Factur-X-Variante (EN 16931) — gleicher Datengehalt, anderer XML-Baum.',
                        'itdatex-e-invoice-output'
                    ); ?></p>
                </td>
            </tr>
            <tr>
                <th><label for="inv_buyerref"><?php esc_html_e( 'Leitweg-ID / Buyer Reference', 'itdatex-e-invoice-output' ); ?> *</label></th>
                <td><input name="invoice[buyer_reference]" id="inv_buyerref" type="text" class="regular-text"
                    value="<?php echo esc_attr( $val( $inv, 'buyer_reference' ) ); ?>"
                    placeholder="04011000-1234512345-06"
                    required>
                    <p class="description"><?php esc_html_e(
                        'BR-DE-15: BT-10 muss gesetzt sein. Bei B2G in DE die Leitweg-ID; bei B2B/B2C eine beliebige Kunden-/Auftragsreferenz.',
                        'itdatex-e-invoice-output'
                    ); ?></p>
                </td>
            </tr>
            <tr>
                <th><label for="inv_note"><?php esc_html_e( 'Notiz', 'itdatex-e-invoice-output' ); ?></label></th>
                <td><textarea name="invoice[note]" id="inv_note" rows="2" class="large-text"><?php echo esc_textarea( $val( $inv, 'note' ) ); ?></textarea></td>
            </tr>
        </table>

        <h2><?php esc_html_e( 'Kaeufer (Empfaenger)', 'itdatex-e-invoice-output' ); ?></h2>
        <table class="form-table" role="presentation">
            <tr>
                <th><label for="buyer_name"><?php esc_html_e( 'Name', 'itdatex-e-invoice-output' ); ?> *</label></th>
                <td><input name="buyer[name]" id="buyer_name" type="text" class="regular-text" required
                    value="<?php echo esc_attr( $val( $buyer, 'name' ) ); ?>"></td>
            </tr>
            <tr>
                <th><label for="buyer_vat"><?php esc_html_e( 'USt-IdNr.', 'itdatex-e-invoice-output' ); ?></label></th>
                <td><input name="buyer[vat_number]" id="buyer_vat" type="text" class="regular-text"
                    value="<?php echo esc_attr( $val( $buyer, 'vat_number' ) ); ?>"></td>
            </tr>
            <tr>
                <th><label for="buyer_address"><?php esc_html_e( 'Adresse', 'itdatex-e-invoice-output' ); ?> *</label></th>
                <td><textarea name="buyer[address]" id="buyer_address" rows="2" class="regular-text" required><?php echo esc_textarea( $val( $buyer, 'address' ) ); ?></textarea>
                    <p class="description"><?php esc_html_e( 'BT-50: Strasse + Hausnummer (eine Zeile pro Adress-Bestandteil).', 'itdatex-e-invoice-output' ); ?></p></td>
            </tr>
            <tr>
                <th><?php esc_html_e( 'PLZ / Stadt', 'itdatex-e-invoice-output' ); ?> *</th>
                <td>
                    <input name="buyer[postal_code]" type="text" class="small-text"
                        value="<?php echo esc_attr( $val( $buyer, 'postal_code' ) ); ?>" placeholder="10115" required>
                    <input name="buyer[city]" type="text" class="regular-text"
                        value="<?php echo esc_attr( $val( $buyer, 'city' ) ); ?>" required>
                    <p class="description"><?php esc_html_e( 'BR-DE-9: PLZ (BT-53), BR-DE-8: Stadt (BT-52).', 'itdatex-e-invoice-output' ); ?></p>
                </td>
            </tr>
            <tr>
                <th><label for="buyer_country"><?php esc_html_e( 'Land (ISO-2)', 'itdatex-e-invoice-output' ); ?> *</label></th>
                <td><input name="buyer[country_code]" id="buyer_country" type="text" class="small-text" maxlength="2"
                    value="<?php echo esc_attr( $val( $buyer, 'country_code', 'DE' ) ); ?>" required>
                    <p class="description"><?php esc_html_e( 'BT-55: ISO-3166-1 alpha-2 (DE, AT, FR, …).', 'itdatex-e-invoice-output' ); ?></p></td>
            </tr>
            <tr>
                <th><label for="buyer_email"><?php esc_html_e( 'E-Mail', 'itdatex-e-invoice-output' ); ?></label></th>
                <td><input name="buyer[contact_email]" id="buyer_email" type="email" class="regular-text"
                    value="<?php echo esc_attr( $val( $buyer, 'contact_email' ) ); ?>"></td>
            </tr>
            <tr>
                <th><label for="buyer_eas_scheme"><?php esc_html_e( 'Elektronische Adresse', 'itdatex-e-invoice-output' ); ?> *</label></th>
                <td>
                    <?php
                    $buyerEasCur = strtoupper( $val( $buyer, 'electronic_address_scheme' ) );
                    $buyerEasVal = $val( $buyer, 'electronic_address_value' );
                    // Default-Vorschlag: wenn Leitweg-ID-Format im Buyer-Reference, EAS-Scheme 0204
                    $buyerRef = $val( $inv, 'buyer_reference' );
                    if ( $buyerEasCur === '' && $buyerRef !== '' ) {
                        $buyerEasCur = '0204';
                        if ( $buyerEasVal === '' ) {
                            $buyerEasVal = $buyerRef;
                        }
                    }
                    $eas_codes_buyer = [
                        '0204' => '0204 — Leitweg-ID (DE B2G)',
                        'EM'   => 'EM — E-Mail',
                        '0088' => '0088 — GLN (Global Location Number)',
                        '9930' => '9930 — DE: USt-IdNr.',
                        '9931' => '9931 — DE: Steuernummer',
                    ];
                    if ( $buyerEasCur !== '' && ! isset( $eas_codes_buyer[ $buyerEasCur ] ) ) {
                        $eas_codes_buyer[ $buyerEasCur ] = $buyerEasCur . ' — ' . __( '(eigener Code)', 'itdatex-e-invoice-output' );
                    }
                    ?>
                    <select name="buyer[electronic_address_scheme]" id="buyer_eas_scheme" required>
                        <?php if ( $buyerEasCur === '' ) : ?>
                            <option value=""><?php esc_html_e( '— bitte waehlen —', 'itdatex-e-invoice-output' ); ?></option>
                        <?php endif; ?>
                        <?php foreach ( $eas_codes_buyer as $code => $label ) : ?>
                            <option value="<?php echo esc_attr( $code ); ?>" <?php selected( $buyerEasCur, $code ); ?>><?php echo esc_html( $label ); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <input name="buyer[electronic_address_value]" type="text" class="regular-text"
                           value="<?php echo esc_attr( $buyerEasVal ); ?>"
                           placeholder="<?php esc_attr_e( 'Wert (Leitweg-ID, E-Mail, GLN, …)', 'itdatex-e-invoice-output' ); ?>"
                           required>
                    <p class="description">
                        <?php esc_html_e(
                            'PEPPOL-EN16931-R010: Pflicht. Bei B2G in DE ueblicherweise die Leitweg-ID (Scheme 0204), bei B2B eine geschaeftliche E-Mail (Scheme EM).',
                            'itdatex-e-invoice-output'
                        ); ?>
                    </p>
                </td>
            </tr>
        </table>

        <h2><?php esc_html_e( 'Positionen', 'itdatex-e-invoice-output' ); ?></h2>
        <p class="description">
            <?php esc_html_e( 'Mindestens eine Position. Leere Zeilen werden ignoriert. Einheit: C62 = Stueck, HUR = Stunde, KGM = kg, LTR = Liter.', 'itdatex-e-invoice-output' ); ?>
        </p>
        <table class="wp-list-table widefat striped" style="margin-bottom:1em">
            <thead><tr>
                <th><?php esc_html_e( 'Name', 'itdatex-e-invoice-output' ); ?></th>
                <th style="width:6em"><?php esc_html_e( 'Menge', 'itdatex-e-invoice-output' ); ?></th>
                <th style="width:5em"><?php esc_html_e( 'Einheit', 'itdatex-e-invoice-output' ); ?></th>
                <th style="width:8em"><?php esc_html_e( 'Einzelpreis', 'itdatex-e-invoice-output' ); ?></th>
                <th style="width:5em"><?php esc_html_e( 'MwSt %', 'itdatex-e-invoice-output' ); ?></th>
                <th style="width:5em"><?php esc_html_e( 'Kat.', 'itdatex-e-invoice-output' ); ?></th>
            </tr></thead>
            <tbody>
            <?php for ( $i = 0; $i < $rows; $i++ ) :
                $r = is_array( $lines[ $i ] ?? null ) ? (array) $lines[ $i ] : [];
            ?>
                <tr>
                    <td><input name="lines[<?php echo (int) $i; ?>][name]" type="text" class="large-text"
                        value="<?php echo esc_attr( $val( $r, 'name' ) ); ?>"></td>
                    <td><input name="lines[<?php echo (int) $i; ?>][quantity]" type="number" step="0.01" min="0" class="small-text"
                        value="<?php echo esc_attr( $val( $r, 'quantity' ) ); ?>"></td>
                    <td><input name="lines[<?php echo (int) $i; ?>][unit_code]" type="text" class="small-text" maxlength="3"
                        value="<?php echo esc_attr( $val( $r, 'unit_code', $i === 0 ? 'C62' : '' ) ); ?>"></td>
                    <td><input name="lines[<?php echo (int) $i; ?>][unit_price]" type="number" step="0.01" min="0" class="small-text"
                        value="<?php echo esc_attr( $val( $r, 'unit_price' ) ); ?>"></td>
                    <td><input name="lines[<?php echo (int) $i; ?>][vat_rate]" type="number" step="0.01" min="0" class="small-text"
                        value="<?php echo esc_attr( $val( $r, 'vat_rate', $i === 0 ? '19' : '' ) ); ?>"></td>
                    <td>
                        <select name="lines[<?php echo (int) $i; ?>][vat_category]">
                            <?php $cur = $val( $r, 'vat_category', 'S' ); foreach ( [ 'S', 'AE', 'Z', 'E', 'G', 'K', 'O' ] as $code ) : ?>
                                <option value="<?php echo esc_attr( $code ); ?>" <?php selected( $cur, $code ); ?>><?php echo esc_html( $code ); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                </tr>
            <?php endfor; ?>
            </tbody>
        </table>

        <?php submit_button( __( 'Rechnung erstellen', 'itdatex-e-invoice-output' ) ); ?>
    </form>
</div>
