<?php
declare(strict_types=1);

namespace Itdatex\Ausgangsrechnung;

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

use Itdatex\Ausgangsrechnung\Admin\Menu;
use Itdatex\Ausgangsrechnung\Settings as SettingsStore;

/**
 * Admin-post-Endpoint zum Stornieren einer Rechnung. Baut den Storno-Draft
 * via StornoService und leitet ihn dann durch die uebliche Ausstell-Pipeline
 * (IssueService).
 *
 * PRG-Muster: bei Erfolg Redirect zur neuen Storno-Rechnung.
 */
final class StornoHandler
{
    public const ACTION = 'ausrg_storno';
    public const NONCE  = 'ausrg_storno_nonce';

    public function register(): void
    {
        add_action( 'admin_post_' . self::ACTION, [ $this, 'handle' ] );
    }

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

        $originalId = isset( $_POST['invoice_id'] ) ? (int) $_POST['invoice_id'] : 0;
        if ( $originalId <= 0 ) {
            wp_die( esc_html__( 'Ungueltige Anfrage.', 'itdatex-e-invoice-output' ), '', [ 'response' => 400 ] );
        }
        check_admin_referer( self::ACTION . '_' . $originalId, self::NONCE );

        $seller = SettingsStore::seller();
        if ( $seller->name === '' ) {
            self::redirectTo( $originalId, 'no_seller' );
            return;
        }

        $stornoNumber = Numbering::nextSuggestion();
        $service      = new StornoService();
        $build        = $service->buildStornoDraft( $originalId, $stornoNumber, $seller );

        if ( $build['result'] !== StornoService::RESULT_OK ) {
            self::redirectTo( $originalId, 'storno_' . $build['result'] );
            return;
        }

        $draft  = $build['draft'];
        $result = ( new IssueService() )->issue(
            $draft,
            wp_get_current_user()->user_login ?: 'system',
            IssueService::FORMAT_UBL
        );

        if ( $result['result'] === IssueService::RESULT_ISSUED ) {
            Numbering::consumeIfMatched( $draft->invoiceNumber );
            wp_safe_redirect( add_query_arg(
                [ 'page' => Menu::SLUG_DETAIL, 'id' => (int) $result['invoice_id'], 'ausrg_status' => 'stornoed' ],
                admin_url( 'admin.php' )
            ) );
            exit;
        }

        self::redirectTo( $originalId, 'storno_issue_failed' );
    }

    private static function redirectTo( int $invoiceId, string $status ): void
    {
        wp_safe_redirect( add_query_arg(
            [ 'page' => Menu::SLUG_DETAIL, 'id' => $invoiceId, 'ausrg_status' => $status ],
            admin_url( 'admin.php' )
        ) );
        exit;
    }
}
