<?php
declare(strict_types=1);

namespace Itdatex\Rechnungseingang;

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

/**
 * Verarbeitet Upload-Formular-Submits aus dem Backend.
 *
 * Flow:
 *   1. Capability + Nonce pruefen
 *   2. Datei in temp-Pfad nehmen
 *   3. Format erkennen (FormatDetector)
 *   4. Parser → InvoiceData
 *   5. Validator → ValidationReport
 *   6. Storage → Datei mit Hashkette persistieren
 *   7. Repository → file_id + invoice_id schreiben + Audit
 *   8. Redirect zur Inbox mit Success/Error-Notice
 */
final class UploadHandler
{
    public const ACTION = 'reing_upload_invoice';
    public const NONCE  = 'reing_upload_invoice_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-intake' ), '', [ 'response' => 403 ] );
        }
        check_admin_referer( self::ACTION, self::NONCE );

        if ( empty( $_FILES['invoice_file']['name'] ?? '' ) ) {
            self::redirect( 'no_file' );
        }

        $file = $_FILES['invoice_file'];
        if ( (int) ( $file['error'] ?? UPLOAD_ERR_NO_FILE ) !== UPLOAD_ERR_OK ) {
            self::redirect( 'upload_error', null, [ 'code' => (int) $file['error'] ] );
        }

        $tmpPath      = (string) $file['tmp_name'];
        $originalName = sanitize_file_name( (string) $file['name'] );

        $result = ( new IngestService() )->ingest(
            $tmpPath,
            $originalName,
            IngestService::SOURCE_UPLOAD,
            (string) ( wp_get_current_user()->user_login ?: 'system' )
        );

        switch ( $result['result'] ) {
            case IngestService::RESULT_DUPLICATE:
                self::redirect( 'duplicate', $result['invoice_id'] );
                break;
            case IngestService::RESULT_INSERTED:
                self::redirect( 'uploaded', $result['invoice_id'] );
                break;
            default:
                self::redirect( 'parse_error', null, [ 'msg' => (string) ( $result['message'] ?? 'unknown' ) ] );
        }
    }

    private static function redirect( string $status, ?int $invoiceId = null, array $extra = [] ): never
    {
        $args = array_merge( [
            'page'         => 'itdatex-e-invoice-intake',
            'reing_status' => $status,
        ], $extra );
        if ( $invoiceId ) {
            $args['invoice_id'] = $invoiceId;
        }
        wp_safe_redirect( add_query_arg( $args, admin_url( 'admin.php' ) ) );
        exit;
    }
}
