<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

add_action( 'admin_post_elementsell_download_issued_invoices_zip', 'elementsell_handle_download_issued_invoices_zip' );
add_action( 'admin_post_elementsell_download_billing_invoices_zip', 'elementsell_handle_download_billing_invoices_zip' );
add_action( 'admin_post_elementsell_download_issued_invoice', 'elementsell_handle_download_issued_invoice' );

/**
 * @param int $year
 * @param int $month
 * @return string
 */
function elementsell_build_invoice_zip_suffix( $year, $month ) {
    if ( $year > 0 && $month > 0 ) {
        return sprintf( '%04d-%02d', $year, $month );
    }

    if ( $year > 0 ) {
        return sprintf( '%04d', $year );
    }

    return 'vse';
}

/**
 * @param array<int, array{path: string, name: string}> $files
 * @param string                                     $zip_basename
 * @return void
 */
function elementsell_send_pdf_files_zip_download( $files, $zip_basename ) {
    if ( empty( $files ) ) {
        wp_die( esc_html__( 'Žádné PDF faktury ke stažení.', 'platebni-formular' ) );
    }

    if ( ! class_exists( 'ZipArchive' ) ) {
        wp_die( esc_html__( 'Na serveru není dostupný ZipArchive.', 'platebni-formular' ) );
    }

    $zip      = new ZipArchive();
    $tmp_file = wp_tempnam( 'elementsell-invoices-zip' );

    if ( ! $tmp_file || $zip->open( $tmp_file, ZipArchive::OVERWRITE ) !== true ) {
        wp_die( esc_html__( 'Export ZIP se nepodařil.', 'platebni-formular' ) );
    }

    $added = 0;

    foreach ( $files as $file ) {
        $path = isset( $file['path'] ) ? (string) $file['path'] : '';
        $name = isset( $file['name'] ) ? (string) $file['name'] : '';

        if ( $path === '' || $name === '' || ! file_exists( $path ) ) {
            continue;
        }

        $zip->addFile( $path, $name );
        ++$added;
    }

    $zip->close();

    if ( $added === 0 ) {
        @unlink( $tmp_file );
        wp_die( esc_html__( 'Nepodařilo se připravit žádné PDF faktury.', 'platebni-formular' ) );
    }

    $filename = sanitize_file_name( $zip_basename ) . '.zip';

    nocache_headers();
    header( 'Content-Type: application/zip' );
    header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
    header( 'Content-Length: ' . filesize( $tmp_file ) );

    readfile( $tmp_file );
    @unlink( $tmp_file );
    exit;
}

/**
 * @param object $invoice
 * @return string|false
 */
function elementsell_get_issued_invoice_pdf_path( $invoice ) {
    if ( ! empty( $invoice->pdf_path ) && file_exists( $invoice->pdf_path ) ) {
        return $invoice->pdf_path;
    }

    if ( ! function_exists( 'elementsell_generate_invoice_pdf_file' ) ) {
        return false;
    }

    return elementsell_generate_invoice_pdf_file( (int) $invoice->id );
}

/**
 * @param object $invoice
 * @return string|false
 */
function elementsell_get_billing_invoice_pdf_path( $invoice ) {
    if ( ! empty( $invoice->pdf_path ) && file_exists( $invoice->pdf_path ) ) {
        return $invoice->pdf_path;
    }

    if ( ! function_exists( 'elementsell_billing_generate_invoice_pdf' ) ) {
        return false;
    }

    return elementsell_billing_generate_invoice_pdf( (int) $invoice->id );
}

/**
 * @param int $year
 * @param int $month
 * @return array<int, array{path: string, name: string}>
 */
function elementsell_collect_issued_invoice_zip_files( $year, $month ) {
    $invoices = elementsell_get_issued_invoices_filtered(
        [
            'year'  => $year,
            'month' => $month,
            'limit' => 500,
        ]
    );

    $files = [];

    foreach ( $invoices as $invoice ) {
        $pdf_path = elementsell_get_issued_invoice_pdf_path( $invoice );

        if ( ! $pdf_path || ! file_exists( $pdf_path ) ) {
            continue;
        }

        $files[] = [
            'path' => $pdf_path,
            'name' => 'faktura-' . sanitize_file_name( (string) $invoice->invoice_number ) . '.pdf',
        ];
    }

    return $files;
}

/**
 * @param int    $year
 * @param int    $month
 * @param string $kind
 * @return array<int, array{path: string, name: string}>
 */
function elementsell_collect_billing_invoice_zip_files( $year, $month, $kind = '' ) {
    elementsell_billing_ensure_tables();

    $invoices = elementsell_billing_get_invoices_filtered(
        [
            'year'         => $year,
            'month'        => $month,
            'invoice_kind' => $kind,
            'limit'        => 500,
        ]
    );

    $files = [];

    foreach ( $invoices as $invoice ) {
        $pdf_path = elementsell_get_billing_invoice_pdf_path( $invoice );

        if ( ! $pdf_path || ! file_exists( $pdf_path ) ) {
            continue;
        }

        $files[] = [
            'path' => $pdf_path,
            'name' => 'faktura-' . sanitize_file_name( (string) $invoice->invoice_number ) . '.pdf',
        ];
    }

    return $files;
}

/**
 * @return void
 */
function elementsell_handle_download_issued_invoices_zip() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'Nemáte oprávnění.', 'platebni-formular' ) );
    }

    check_admin_referer( 'elementsell_download_issued_invoices_zip' );

    $year  = isset( $_POST['issued_year'] ) ? (int) $_POST['issued_year'] : 0;
    $month = isset( $_POST['issued_month'] ) ? (int) $_POST['issued_month'] : 0;
    $files = elementsell_collect_issued_invoice_zip_files( $year, $month );
    $suffix = elementsell_build_invoice_zip_suffix( $year, $month );

    elementsell_send_pdf_files_zip_download( $files, 'faktury-vystavene-' . $suffix );
}

/**
 * @return void
 */
function elementsell_handle_download_billing_invoices_zip() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'Nemáte oprávnění.', 'platebni-formular' ) );
    }

    check_admin_referer( 'elementsell_download_billing_invoices_zip' );

    $year  = isset( $_POST['billing_year'] ) ? (int) $_POST['billing_year'] : 0;
    $month = isset( $_POST['billing_month'] ) ? (int) $_POST['billing_month'] : 0;
    $kind  = isset( $_POST['billing_kind'] ) ? sanitize_key( wp_unslash( (string) $_POST['billing_kind'] ) ) : '';
    $files  = elementsell_collect_billing_invoice_zip_files( $year, $month, $kind );
    $suffix = elementsell_build_invoice_zip_suffix( $year, $month );

    if ( $kind === 'fee' ) {
        $suffix .= '-poplatek';
    } elseif ( $kind === 'card_verification' ) {
        $suffix .= '-karta';
    }

    elementsell_send_pdf_files_zip_download( $files, 'faktury-elementsell-' . $suffix );
}

/**
 * @return void
 */
function elementsell_handle_download_issued_invoice() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'Nemáte oprávnění.', 'platebni-formular' ) );
    }

    $invoice_id = isset( $_GET['invoice_id'] ) ? (int) $_GET['invoice_id'] : 0;

    check_admin_referer( 'elementsell_download_issued_invoice_' . $invoice_id );

    $invoice = elementsell_get_invoice( $invoice_id );

    if ( ! $invoice || (string) $invoice->type === 'demo' ) {
        wp_die( esc_html__( 'Faktura nebyla nalezena.', 'platebni-formular' ) );
    }

    $pdf_path = elementsell_get_issued_invoice_pdf_path( $invoice );

    if ( ! $pdf_path || ! file_exists( $pdf_path ) ) {
        wp_die( esc_html__( 'PDF faktury se nepodařilo připravit.', 'platebni-formular' ) );
    }

    $filename = 'faktura-' . sanitize_file_name( (string) $invoice->invoice_number ) . '.pdf';

    nocache_headers();
    header( 'Content-Type: application/pdf' );
    header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
    header( 'Content-Length: ' . filesize( $pdf_path ) );
    readfile( $pdf_path );
    exit;
}

/**
 * @param int $invoice_id
 * @return string
 */
function elementsell_get_issued_invoice_download_url( $invoice_id ) {
    return wp_nonce_url(
        admin_url( 'admin-post.php?action=elementsell_download_issued_invoice&invoice_id=' . (int) $invoice_id ),
        'elementsell_download_issued_invoice_' . (int) $invoice_id
    );
}

/**
 * @param string $action
 * @param array  $fields
 * @param bool   $disabled
 * @return void
 */
function elementsell_render_invoices_zip_download_button( $action, $fields, $disabled = false ) {
    ?>
    <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="elementsell-invoices-zip-form">
        <?php wp_nonce_field( $action ); ?>
        <input type="hidden" name="action" value="<?php echo esc_attr( $action ); ?>">
        <?php foreach ( $fields as $name => $value ) : ?>
            <input type="hidden" name="<?php echo esc_attr( $name ); ?>" value="<?php echo esc_attr( (string) $value ); ?>">
        <?php endforeach; ?>
        <button type="submit" class="button"<?php disabled( $disabled ); ?>>Stáhnout vše (ZIP)</button>
    </form>
    <?php
}
