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

/**
 * Vygeneruje PDF faktury a vrátí cestu k souboru.
 *
 * @param int $invoice_id
 * @return string|false
 */
function elementsell_generate_invoice_pdf_file( $invoice_id ) {
    $invoice = elementsell_get_invoice( $invoice_id );

    if ( ! $invoice ) {
        return false;
    }

    if ( ! empty( $invoice->pdf_path ) && file_exists( $invoice->pdf_path ) ) {
        @unlink( $invoice->pdf_path );
    }

    $order = elementsell_get_order( (int) $invoice->order_id );

    if ( ! $order ) {
        return false;
    }

    $autoload = dirname( __DIR__, 2 ) . '/vendor_invoice/autoload.php';

    if ( ! file_exists( $autoload ) ) {
        error_log( 'ElementSell: chybí vendor_invoice/autoload.php' );
        return false;
    }

    elementsell_pdf_init_tcpdf();

    require_once $autoload;

    if ( ! class_exists( 'ElementSell_TCPDF', false ) ) {
        class ElementSell_TCPDF extends \TCPDF {
            public function Error( $msg ) {
                throw new Exception( $msg );
            }
        }
    }

    $layout     = elementsell_get_invoice_pdf_layout();
    $is_modern  = ( $layout === 'modern' );
    $margin     = $is_modern ? 16 : 10;

    try {
        $pdf = new ElementSell_TCPDF( 'P', 'mm', 'A4', true, 'UTF-8', false );
        $pdf->SetCreator( 'ElementSell' );
        $pdf->SetAuthor( (string) get_option( 'faktury_jmeno', '' ) );
        $pdf->SetTitle( 'Faktura ' . $invoice->invoice_number );
        $pdf->setPrintHeader( false );
        $pdf->setPrintFooter( false );
        $pdf->SetMargins( $margin, $margin, $margin );
        $pdf->SetAutoPageBreak( true, $is_modern ? 18 : 15 );

        $font = elementsell_pdf_get_font_family_for_layout( $layout );
        $pdf->SetFont( $font, '', $is_modern ? 11 : 12 );
        $pdf->AddPage();

        if ( $invoice->type === 'demo' ) {
            elementsell_pdf_draw_demo_watermark( $pdf );
            $pdf->SetFont( $font, '', $is_modern ? 11 : 12 );
        }

        $content_y = $margin;

        if ( $is_modern ) {
            $page_w = $pdf->getPageWidth();
            $pdf->SetFillColor( 38, 37, 30 );
            $pdf->Rect( $margin, 14, $page_w - ( $margin * 2 ), 1.2, 'F' );

            $logo_path = elementsell_pdf_prepare_image( (string) get_option( 'faktury_logo', '' ) );

            if ( $logo_path ) {
                $pdf->Image(
                    $logo_path,
                    $margin,
                    20,
                    0,
                    18,
                    elementsell_pdf_tcpdf_image_type( $logo_path ),
                    '',
                    'T',
                    false,
                    300,
                    '',
                    false,
                    false,
                    0,
                    false,
                    false,
                    false
                );
                $content_y = 42;
            } else {
                $content_y = 20;
            }
        } else {
            $logo_path = elementsell_pdf_prepare_image( (string) get_option( 'faktury_logo', '' ) );

            if ( $logo_path ) {
                $pdf->Image(
                    $logo_path,
                    10,
                    12,
                    0,
                    22,
                    elementsell_pdf_tcpdf_image_type( $logo_path ),
                    '',
                    'T',
                    false,
                    300,
                    '',
                    false,
                    false,
                    0,
                    false,
                    false,
                    false
                );
                $content_y = 38;
            }
        }

        $pdf->SetY( $content_y );
        $pdf->writeHTML( elementsell_build_invoice_pdf_html( $invoice, $order ), true, false, true, false, '' );

        $signature_path = elementsell_pdf_prepare_image( (string) get_option( 'faktury_podpis', '' ) );

        if ( $signature_path ) {
            $signature_gap = $is_modern ? 16 : 6;
            $signature_w   = $is_modern ? 48 : 42;
            $signature_y   = min( $pdf->GetY() + $signature_gap, $is_modern ? 245 : 250 );
            $pdf->Image(
                $signature_path,
                $margin,
                $signature_y,
                $signature_w,
                0,
                elementsell_pdf_tcpdf_image_type( $signature_path ),
                '',
                'T',
                false,
                300,
                '',
                false,
                false,
                0,
                false,
                false,
                false
            );
        }

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

        if ( ! $upload_dir ) {
            return false;
        }

        $filepath = trailingslashit( $upload_dir ) . $filename;

        $pdf->Output( $filepath, 'F' );

        if ( ! file_exists( $filepath ) ) {
            error_log( 'ElementSell: PDF faktury se nepodařilo uložit: ' . $filepath );
            return false;
        }

        global $wpdb;

        $wpdb->update(
            elementsell_get_invoices_table_name(),
            [
                'pdf_path'   => $filepath,
                'updated_at' => current_time( 'mysql' ),
            ],
            [ 'id' => (int) $invoice->id ],
            [ '%s', '%s' ],
            [ '%d' ]
        );

        return $filepath;
    } catch ( Exception $e ) {
        error_log( 'ElementSell: chyba generování PDF faktury: ' . $e->getMessage() );
        return false;
    }
}

/**
 * modern = výchozí, legacy = starý layout (záloha).
 *
 * Přepnutí:
 *   define( 'ELEMENTSELL_INVOICE_PDF_LAYOUT', 'legacy' );
 *   nebo filtr elementsell_invoice_pdf_layout
 *
 * @return string modern|legacy
 */
function elementsell_get_invoice_pdf_layout() {
    $layout = 'modern';

    if ( defined( 'ELEMENTSELL_INVOICE_PDF_LAYOUT' ) ) {
        $layout = (string) ELEMENTSELL_INVOICE_PDF_LAYOUT;
    }

    $layout = (string) apply_filters( 'elementsell_invoice_pdf_layout', $layout );

    return $layout === 'legacy' ? 'legacy' : 'modern';
}

/**
 * @param string $path
 * @return string JPEG|PNG|''
 */
function elementsell_pdf_tcpdf_image_type( $path ) {
    $info = @getimagesize( (string) $path );

    if ( ! is_array( $info ) || empty( $info['mime'] ) ) {
        return '';
    }

    if ( $info['mime'] === 'image/jpeg' ) {
        return 'JPEG';
    }

    if ( $info['mime'] === 'image/png' ) {
        return 'PNG';
    }

    return '';
}

/**
 * @return void
 */
function elementsell_pdf_init_tcpdf() {
    $tcpdf_main = dirname( __DIR__, 2 ) . '/vendor_invoice/tecnickcom/tcpdf/';

    if ( ! defined( 'K_PATH_MAIN' ) ) {
        define( 'K_PATH_MAIN', $tcpdf_main );
    }

    if ( ! defined( 'K_PATH_FONTS' ) ) {
        define( 'K_PATH_FONTS', K_PATH_MAIN . 'fonts/' );
    }
}

/**
 * @return string
 */
function elementsell_pdf_get_fonts_path() {
    elementsell_pdf_init_tcpdf();

    return K_PATH_FONTS;
}

/**
 * Výchozí font — bezpatkový (moderní faktury).
 *
 * @return string
 */
function elementsell_pdf_get_font_family() {
    return elementsell_pdf_get_font_family_for_layout( 'modern' );
}

/**
 * @param string $layout modern|legacy
 * @return string
 */
function elementsell_pdf_get_font_family_for_layout( $layout ) {
    $path = elementsell_pdf_get_fonts_path();

    if ( $layout === 'legacy' ) {
        if ( file_exists( $path . 'freeserif.php' ) ) {
            return 'freeserif';
        }

        if ( file_exists( $path . 'dejavusans.php' ) ) {
            return 'dejavusans';
        }

        return 'helvetica';
    }

    if ( file_exists( $path . 'dejavusans.php' ) ) {
        return 'dejavusans';
    }

    if ( file_exists( $path . 'freeserif.php' ) ) {
        return 'freeserif';
    }

    return 'helvetica';
}

/**
 * @return string
 */
function elementsell_pdf_get_font_family_bold() {
    $layout = function_exists( 'elementsell_get_invoice_pdf_layout' )
        ? elementsell_get_invoice_pdf_layout()
        : 'modern';
    $path   = elementsell_pdf_get_fonts_path();

    if ( $layout === 'legacy' ) {
        if ( file_exists( $path . 'freeserifb.php' ) ) {
            return 'freeserifb';
        }

        if ( file_exists( $path . 'dejavusansb.php' ) ) {
            return 'dejavusansb';
        }

        return 'helvetica';
    }

    if ( file_exists( $path . 'dejavusansb.php' ) ) {
        return 'dejavusansb';
    }

    if ( file_exists( $path . 'freeserifb.php' ) ) {
        return 'freeserifb';
    }

    return 'helvetica';
}

/**
 * @return bool
 */
function elementsell_pdf_is_vat_payer() {
    $option = get_option( 'faktury_platce_dph', 0 );

    return ( $option === 'ano' || (int) $option === 1 );
}

/**
 * @param \TCPDF $pdf
 */
function elementsell_pdf_draw_demo_watermark( $pdf ) {
    $page_width  = $pdf->getPageWidth();
    $page_height = $pdf->getPageHeight();
    $center_x    = $page_width / 2;
    $center_y    = $page_height / 2;
    $font_family = elementsell_pdf_get_font_family_bold();

    $pdf->SetAlpha( 0.08 );
    $pdf->SetFont( $font_family, '', 90 );
    $pdf->SetTextColor( 0, 0, 0 );
    $pdf->StartTransform();
    $pdf->Rotate( -28, $center_x, $center_y );
    $pdf->SetXY( $center_x - 70, $center_y - 12 );
    $pdf->Cell( 140, 24, 'DEMO', 0, 0, 'C', false, '', 0, false, 'T', 'M' );
    $pdf->StopTransform();
    $pdf->SetAlpha( 1 );
    $pdf->SetTextColor( 0, 0, 0 );
}

/**
 * Adresář pro cache PNG→JPEG konverzí (jeden soubor na zdrojový obrázek).
 *
 * @return string
 */
function elementsell_pdf_get_image_cache_dir() {
    $upload_dir = wp_upload_dir();

    if ( ! empty( $upload_dir['error'] ) ) {
        return '';
    }

    $cache_dir = trailingslashit( $upload_dir['basedir'] ) . 'elementsell-pdf-cache';

    if ( ! wp_mkdir_p( $cache_dir ) ) {
        return '';
    }

    $index_file = trailingslashit( $cache_dir ) . 'index.php';

    if ( ! file_exists( $index_file ) ) {
        file_put_contents( $index_file, "<?php\n// Silence is golden.\n" );
    }

    return $cache_dir;
}

/**
 * Připraví obrázek pro TCPDF (PNG bez alpha -> JPEG).
 *
 * @param string $image_path
 * @return string|false
 */
function elementsell_pdf_prepare_image( $image_path ) {
    if ( empty( $image_path ) ) {
        return false;
    }

    $local_path = elementsell_invoice_image_source( $image_path );

    if ( empty( $local_path ) || ! file_exists( $local_path ) ) {
        return false;
    }

    $image_info = @getimagesize( $local_path );

    if ( ! $image_info ) {
        return false;
    }

    if ( $image_info['mime'] === 'image/jpeg' ) {
        return $local_path;
    }

    if ( $image_info['mime'] !== 'image/png' ) {
        return $local_path;
    }

    $cache_dir = elementsell_pdf_get_image_cache_dir();

    if ( $cache_dir === '' ) {
        return $local_path;
    }

    $source_mtime = (int) filemtime( $local_path );
    $cache_key    = md5( $local_path . '|' . (string) $source_mtime );
    $output_path  = trailingslashit( $cache_dir ) . 'elementsell-' . $cache_key . '.jpg';

    if ( file_exists( $output_path ) && filemtime( $output_path ) >= $source_mtime ) {
        return $output_path;
    }

    if ( ! function_exists( 'imagecreatefrompng' ) ) {
        return $local_path;
    }

    $image = @imagecreatefrompng( $local_path );

    if ( ! $image ) {
        return false;
    }

    $width  = imagesx( $image );
    $height = imagesy( $image );
    $canvas = imagecreatetruecolor( $width, $height );
    $white  = imagecolorallocate( $canvas, 255, 255, 255 );

    imagefill( $canvas, 0, 0, $white );
    imagecopy( $canvas, $image, 0, 0, 0, 0, $width, $height );

    imagejpeg( $canvas, $output_path, 90 );
    imagedestroy( $image );
    imagedestroy( $canvas );

    if ( ! file_exists( $output_path ) ) {
        return false;
    }

    return $output_path;
}

/**
 * @param string $url
 * @return string
 */
function elementsell_invoice_image_source( $url ) {
    if ( empty( $url ) ) {
        return '';
    }

    if ( file_exists( $url ) ) {
        return $url;
    }

    $upload_dir = wp_upload_dir();
    $baseurl    = $upload_dir['baseurl'];
    $basedir    = $upload_dir['basedir'];

    if ( strpos( $url, $baseurl ) === 0 ) {
        $path = $basedir . substr( $url, strlen( $baseurl ) );

        if ( file_exists( $path ) ) {
            return $path;
        }
    }

    return '';
}

/**
 * @param object $invoice
 * @param object $order
 * @return string
 */
/**
 * HTML tělo PDF faktury — routuje modern / legacy.
 *
 * @param object $invoice
 * @param object $order
 * @return string
 */
function elementsell_build_invoice_pdf_html( $invoice, $order ) {
    if ( elementsell_get_invoice_pdf_layout() === 'legacy' ) {
        return elementsell_build_invoice_pdf_html_legacy( $invoice, $order );
    }

    return elementsell_build_invoice_pdf_html_modern( $invoice, $order );
}

/**
 * Moderní TCPDF-safe layout (bezpatkové, víc prostoru).
 *
 * @param object $invoice
 * @param object $order
 * @return string
 */
function elementsell_build_invoice_pdf_html_modern( $invoice, $order ) {
    $is_vat_payer = elementsell_pdf_is_vat_payer();
    $vat_rate     = 21.0;
    $stored_rate  = get_option( 'faktury_dph_sazba', false );

    if ( false !== $stored_rate ) {
        $vat_rate = (float) $stored_rate;
    }

    $is_demo    = ( $invoice->type === 'demo' );
    $is_paid    = ( $invoice->status === 'paid' );
    $total      = (float) $invoice->price;
    $vat_amount = 0.0;
    $base       = $total;

    if ( $is_vat_payer && $vat_rate > 0 ) {
        $vat_amount = ( $total * $vat_rate ) / ( 100 + $vat_rate );
        $base       = $total - $vat_amount;
    }

    $issue_date = $invoice->issue_date
        ? mysql2date( 'j. n. Y', $invoice->issue_date, false )
        : current_time( 'j. n. Y' );

    $paid_label    = $is_paid ? 'Zaplaceno' : 'Čeká na úhradu';
    $status_color  = $is_paid ? '#1d7a3a' : '#b45309';
    $vat_label     = $is_vat_payer ? 'Plátce DPH' : 'Neplátce DPH';
    $invoice_title = $is_demo
        ? 'Doklad DEMO č. ' . $invoice->invoice_number
        : 'Faktura č. ' . $invoice->invoice_number;

    $customer_name    = trim( $order->first_name . ' ' . $order->surname );
    $customer_company = (string) elementsell_get_order_field( $order->id, 'company' );
    $customer_address = (string) elementsell_get_order_field( $order->id, 'address' );
    $customer_ico     = (string) elementsell_get_order_field( $order->id, 'ico' );
    $customer_dic     = (string) elementsell_get_order_field( $order->id, 'dic' );
    $supplier_dic     = (string) get_option( 'faktury_dic', '' );

    $ink   = '#26251e';
    $muted = '#6b6a63';
    $line  = '#d8d7d1';
    $soft  = '#f7f7f4';

    // Accent bar kreslí generate() přes Rect — HTML začíná titulem vpravo (vlevo logo).
    $html  = '<table border="0" cellspacing="0" cellpadding="0" width="100%">';
    $html .= '<tr>';
    $html .= '<td width="46%" valign="top">&nbsp;</td>';
    $html .= '<td width="54%" valign="top" align="right">';
    $html .= '<div style="font-size:17pt; font-weight:bold; color:' . $ink . '; line-height:1.3;">' . esc_html( $invoice_title ) . '</div>';
    $html .= '<div style="font-size:10pt; font-weight:bold; color:' . $ink . '; margin-top:8px;">' . esc_html( $vat_label ) . '</div>';
    $html .= '<div style="font-size:9pt; color:' . $muted . '; margin-top:6px;">Datum vystavení: ' . esc_html( $issue_date ) . '</div>';
    $html .= '</td>';
    $html .= '</tr>';
    $html .= '</table>';

    $html .= '<table border="0" cellspacing="0" cellpadding="0" width="100%" style="margin-top:18px; margin-bottom:14px;">';
    $html .= '<tr><td bgcolor="' . $line . '" style="font-size:1px; line-height:1px; height:1px;">&nbsp;</td></tr>';
    $html .= '</table>';

    $html .= '<table border="0" cellspacing="0" cellpadding="0" width="100%">';
    $html .= '<tr>';

    $html .= '<td width="47%" valign="top" style="padding-right:12px;">';
    $html .= '<div style="font-size:9pt; font-weight:bold; color:' . $muted . ';">DODAVATEL</div>';
    $html .= '<div style="font-size:10pt; color:' . $ink . '; margin-top:12px; line-height:1.7;">';
    $html .= '<strong>' . esc_html( (string) get_option( 'faktury_jmeno', '' ) ) . '</strong><br>';
    $html .= nl2br( esc_html( (string) get_option( 'faktury_adresa', '' ) ) ) . '<br>';
    $html .= 'IČO: ' . esc_html( (string) get_option( 'faktury_ico', '' ) );

    if ( $is_vat_payer && $supplier_dic !== '' ) {
        $html .= '<br>DIČ: ' . esc_html( $supplier_dic );
    }

    $html .= '<br>' . esc_html( elementsell_get_invoice_supplier_email() );
    $html .= '<br>' . esc_html( elementsell_get_invoice_supplier_web() );
    $html .= '</div>';
    $html .= '</td>';

    $html .= '<td width="6%">&nbsp;</td>';

    $html .= '<td width="47%" valign="top">';
    $html .= '<div style="font-size:9pt; font-weight:bold; color:' . $muted . ';">ODBĚRATEL</div>';
    $html .= '<div style="font-size:10pt; color:' . $ink . '; margin-top:12px; line-height:1.7;">';

    if ( $customer_name !== '' ) {
        $html .= '<strong>' . esc_html( $customer_name ) . '</strong><br>';
    }

    if ( $customer_company !== '' ) {
        $html .= esc_html( $customer_company ) . '<br>';
    }

    if ( $customer_address !== '' ) {
        $html .= esc_html( $customer_address ) . '<br>';
    }

    if ( $customer_ico !== '' ) {
        $html .= 'IČO: ' . esc_html( $customer_ico );
    }

    if ( $customer_dic !== '' ) {
        $html .= ( $customer_ico !== '' ? '<br>' : '' ) . 'DIČ: ' . esc_html( $customer_dic );
    }

    if ( ! empty( $order->email ) ) {
        $html .= ( $customer_ico !== '' || $customer_dic !== '' ? '<br>' : '' ) . esc_html( $order->email );
    }

    $html .= '</div>';
    $html .= '</td>';

    $html .= '</tr></table>';

    $html .= '<table border="0" cellspacing="0" cellpadding="0" width="100%" style="margin-top:22px; margin-bottom:12px;">';
    $html .= '<tr><td bgcolor="' . $line . '" style="font-size:1px; line-height:1px; height:1px;">&nbsp;</td></tr>';
    $html .= '</table>';

    if ( $is_vat_payer && $vat_rate > 0 ) {
        $html .= '<table border="0" cellspacing="0" cellpadding="10" width="100%">';
        $html .= '<tr bgcolor="' . $soft . '">';
        $html .= '<td width="40%" style="font-size:9pt; font-weight:bold; color:' . $ink . '; border-bottom:1px solid ' . $line . ';">Popis</td>';
        $html .= '<td width="20%" align="right" style="font-size:9pt; font-weight:bold; color:' . $ink . '; border-bottom:1px solid ' . $line . ';">Bez DPH</td>';
        $html .= '<td width="20%" align="right" style="font-size:9pt; font-weight:bold; color:' . $ink . '; border-bottom:1px solid ' . $line . ';">DPH ' . esc_html( rtrim( rtrim( number_format( $vat_rate, 0 ), '0' ), ',' ) ) . ' %</td>';
        $html .= '<td width="20%" align="right" style="font-size:9pt; font-weight:bold; color:' . $ink . '; border-bottom:1px solid ' . $line . ';">S DPH</td>';
        $html .= '</tr>';
        $html .= '<tr>';
        $html .= '<td style="font-size:10pt; color:' . $ink . '; border-bottom:1px solid ' . $line . '; line-height:1.6;">' . esc_html( $invoice->product_name ?: '—' ) . '</td>';
        $html .= '<td align="right" style="font-size:10pt; color:' . $ink . '; border-bottom:1px solid ' . $line . ';">' . esc_html( elementsell_format_invoice_amount( $base ) ) . '</td>';
        $html .= '<td align="right" style="font-size:10pt; color:' . $ink . '; border-bottom:1px solid ' . $line . ';">' . esc_html( elementsell_format_invoice_amount( $vat_amount ) ) . '</td>';
        $html .= '<td align="right" style="font-size:10pt; color:' . $ink . '; border-bottom:1px solid ' . $line . ';">' . esc_html( elementsell_format_invoice_amount( $total ) ) . '</td>';
        $html .= '</tr>';
        $html .= '</table>';
    } else {
        $html .= '<table border="0" cellspacing="0" cellpadding="10" width="100%">';
        $html .= '<tr bgcolor="' . $soft . '">';
        $html .= '<td width="70%" style="font-size:9pt; font-weight:bold; color:' . $ink . '; border-bottom:1px solid ' . $line . ';">Popis</td>';
        $html .= '<td width="30%" align="right" style="font-size:9pt; font-weight:bold; color:' . $ink . '; border-bottom:1px solid ' . $line . ';">Cena</td>';
        $html .= '</tr>';
        $html .= '<tr>';
        $html .= '<td style="font-size:10pt; color:' . $ink . '; border-bottom:1px solid ' . $line . '; line-height:1.6;">' . esc_html( $invoice->product_name ?: '—' ) . '</td>';
        $html .= '<td align="right" style="font-size:10pt; color:' . $ink . '; border-bottom:1px solid ' . $line . ';">' . esc_html( elementsell_format_invoice_amount( $total ) ) . '</td>';
        $html .= '</tr>';
        $html .= '</table>';
    }

    $html .= '<table border="0" cellspacing="0" cellpadding="0" width="100%" style="margin-top:22px;">';
    $html .= '<tr>';
    $html .= '<td width="48%" valign="bottom">';
    $html .= '<div style="font-size:11pt; font-weight:bold; color:' . $status_color . ';">' . esc_html( $paid_label ) . '</div>';
    $html .= '</td>';
    $html .= '<td width="52%" align="right" valign="top">';
    $html .= '<table border="0" cellspacing="0" cellpadding="10" width="100%" bgcolor="' . $soft . '">';

    if ( $is_vat_payer && $vat_rate > 0 ) {
        $html .= '<tr>';
        $html .= '<td style="font-size:9pt; color:' . $muted . ';">Základ DPH</td>';
        $html .= '<td align="right" style="font-size:9pt; color:' . $ink . ';">' . esc_html( elementsell_format_invoice_amount( $base ) ) . '</td>';
        $html .= '</tr>';
        $html .= '<tr>';
        $html .= '<td style="font-size:9pt; color:' . $muted . ';">DPH</td>';
        $html .= '<td align="right" style="font-size:9pt; color:' . $ink . ';">' . esc_html( elementsell_format_invoice_amount( $vat_amount ) ) . '</td>';
        $html .= '</tr>';
    }

    $html .= '<tr>';
    $html .= '<td style="font-size:11pt; font-weight:bold; color:' . $ink . '; border-top:1px solid ' . $line . ';">Celkem</td>';
    $html .= '<td align="right" style="font-size:12pt; font-weight:bold; color:' . $ink . '; border-top:1px solid ' . $line . ';">' . esc_html( elementsell_format_invoice_amount( $total ) ) . '</td>';
    $html .= '</tr>';
    $html .= '</table>';
    $html .= '</td>';
    $html .= '</tr>';
    $html .= '</table>';

    return $html;
}

/**
 * Starý PDF layout — záloha pro rollback.
 *
 * @param object $invoice
 * @param object $order
 * @return string
 */
function elementsell_build_invoice_pdf_html_legacy( $invoice, $order ) {
    $is_vat_payer = elementsell_pdf_is_vat_payer();
    $vat_rate     = 21.0;
    $stored_rate  = get_option( 'faktury_dph_sazba', false );

    if ( false !== $stored_rate ) {
        $vat_rate = (float) $stored_rate;
    }

    $is_demo = ( $invoice->type === 'demo' );
    $is_paid = ( $invoice->status === 'paid' );
    $total   = (float) $invoice->price;
    $vat_amount = 0.0;
    $base    = $total;

    if ( $is_vat_payer && $vat_rate > 0 ) {
        $vat_amount = ( $total * $vat_rate ) / ( 100 + $vat_rate );
        $base       = $total - $vat_amount;
    }

    $issue_date = $invoice->issue_date
        ? mysql2date( 'j. n. Y', $invoice->issue_date, false )
        : current_time( 'j. n. Y' );

    $paid_label = $is_paid ? 'Zaplaceno' : 'Čeká na úhradu';
    $vat_label  = $is_vat_payer ? 'Plátce DPH' : 'Neplátce DPH';
    $invoice_title = $is_demo
        ? 'Toto není Faktura č. ' . $invoice->invoice_number
        : 'Faktura č. ' . $invoice->invoice_number;

    $customer_name    = trim( $order->first_name . ' ' . $order->surname );
    $customer_company = (string) elementsell_get_order_field( $order->id, 'company' );
    $customer_address = (string) elementsell_get_order_field( $order->id, 'address' );
    $customer_ico     = (string) elementsell_get_order_field( $order->id, 'ico' );
    $customer_dic     = (string) elementsell_get_order_field( $order->id, 'dic' );

    $supplier_dic = (string) get_option( 'faktury_dic', '' );

    $html  = '<table border="0" cellspacing="0" cellpadding="0" width="100%">';
    $html .= '<tr><td colspan="2" style="border-top: 2px solid #000000; font-size: 1px; line-height: 1px;">&nbsp;</td></tr>';
    $html .= '<tr><td width="55%">&nbsp;</td>';
    $html .= '<td width="45%" align="right" style="font-size: 16pt; font-weight: bold;">' . esc_html( $invoice_title ) . '</td></tr>';
    $html .= '<tr><td width="55%">&nbsp;</td>';
    $html .= '<td width="45%" align="right" style="font-size: 11pt; font-weight: bold;">' . esc_html( $vat_label ) . '</td></tr>';
    $html .= '<tr><td width="55%">&nbsp;</td>';
    $html .= '<td width="45%" align="right" style="font-size: 10pt; color: #555555;">Datum vystavení: ' . esc_html( $issue_date ) . '</td></tr>';
    $html .= '<tr><td colspan="2" style="border-bottom: 2px solid #000000; font-size: 1px; line-height: 1px; padding-bottom: 8px;">&nbsp;</td></tr>';
    $html .= '</table>';

    $html .= '<table border="0" cellspacing="0" cellpadding="6" width="100%" style="margin-top: 8px;">';
    $html .= '<tr>';
    $html .= '<td width="50%" valign="top"><h3 style="margin: 0 0 8px 0; font-size: 12pt;">Dodavatel</h3>';
    $html .= '<p style="margin: 0 0 4px 0;"><strong>Jméno dodavatele:</strong> ' . esc_html( (string) get_option( 'faktury_jmeno', '' ) ) . '</p>';
    $html .= '<p style="margin: 0 0 4px 0;"><strong>Adresa:</strong> ' . nl2br( esc_html( (string) get_option( 'faktury_adresa', '' ) ) ) . '</p>';
    $html .= '<p style="margin: 0 0 4px 0;"><strong>IČO:</strong> ' . esc_html( (string) get_option( 'faktury_ico', '' ) ) . '</p>';

    if ( $is_vat_payer && $supplier_dic ) {
        $html .= '<p style="margin: 0 0 4px 0;"><strong>DIČ:</strong> ' . esc_html( $supplier_dic ) . '</p>';
    }

    $html .= '<p style="margin: 0 0 4px 0;"><strong>Email:</strong> ' . esc_html( elementsell_get_invoice_supplier_email() ) . '</p>';
    $html .= '<p style="margin: 0 0 4px 0;"><strong>Web:</strong> ' . esc_html( elementsell_get_invoice_supplier_web() ) . '</p>';
    $html .= '</td>';
    $html .= '<td width="50%" valign="top"><h3 style="margin: 0 0 8px 0; font-size: 12pt;">Odběratel</h3>';

    if ( $customer_name ) {
        $html .= '<p style="margin: 0 0 4px 0;"><strong>Jméno:</strong> ' . esc_html( $customer_name ) . '</p>';
    }

    if ( $customer_company ) {
        $html .= '<p style="margin: 0 0 4px 0;"><strong>Firma:</strong> ' . esc_html( $customer_company ) . '</p>';
    }

    if ( $customer_address ) {
        $html .= '<p style="margin: 0 0 4px 0;"><strong>Adresa:</strong> ' . esc_html( $customer_address ) . '</p>';
    }

    if ( $customer_ico ) {
        $html .= '<p style="margin: 0 0 4px 0;"><strong>IČO:</strong> ' . esc_html( $customer_ico ) . '</p>';
    }

    if ( $customer_dic ) {
        $html .= '<p style="margin: 0 0 4px 0;"><strong>DIČ:</strong> ' . esc_html( $customer_dic ) . '</p>';
    }

    if ( $order->email ) {
        $html .= '<p style="margin: 0 0 4px 0;"><strong>Email:</strong> ' . esc_html( $order->email ) . '</p>';
    }

    $html .= '</td></tr></table>';
    $html .= '<hr style="border: 1px solid #000000; margin: 12px 0;">';

    if ( $is_vat_payer && $vat_rate > 0 ) {
        $html .= '<table border="0" cellspacing="6" cellpadding="4" width="100%">';
        $html .= '<tr>';
        $html .= '<td width="40%" style="font-weight: bold;">Popis</td>';
        $html .= '<td width="20%" align="right" style="font-weight: bold;">Cena bez DPH</td>';
        $html .= '<td width="20%" align="right" style="font-weight: bold;">Daň ' . esc_html( rtrim( rtrim( number_format( $vat_rate, 0 ), '0' ), ',' ) ) . ' %</td>';
        $html .= '<td width="20%" align="right" style="font-weight: bold;">Cena s DPH</td>';
        $html .= '</tr>';
        $html .= '<tr>';
        $html .= '<td>' . esc_html( $invoice->product_name ?: '—' ) . '</td>';
        $html .= '<td align="right">' . esc_html( elementsell_format_invoice_amount( $base ) ) . '</td>';
        $html .= '<td align="right">' . esc_html( elementsell_format_invoice_amount( $vat_amount ) ) . '</td>';
        $html .= '<td align="right">' . esc_html( elementsell_format_invoice_amount( $total ) ) . '</td>';
        $html .= '</tr></table>';
    } else {
        $html .= '<table border="0" cellspacing="6" cellpadding="4" width="100%">';
        $html .= '<tr>';
        $html .= '<td width="50%" style="font-weight: bold;">Popis</td>';
        $html .= '<td width="50%" align="right" style="font-weight: bold;">Cena</td>';
        $html .= '</tr>';
        $html .= '<tr>';
        $html .= '<td>' . esc_html( $invoice->product_name ?: '—' ) . '</td>';
        $html .= '<td align="right">' . esc_html( elementsell_format_invoice_amount( $total ) ) . '</td>';
        $html .= '</tr></table>';
    }

    $html .= '<hr style="border: 1px solid #000000; margin: 12px 0;">';
    $html .= '<table border="0" cellspacing="0" cellpadding="4" width="100%">';
    $html .= '<tr>';
    $html .= '<td width="50%" style="font-size: 12pt; font-weight: bold; color: ' . ( $is_paid ? '#1d7a3a' : '#b45309' ) . ';">' . esc_html( $paid_label ) . '</td>';
    $html .= '<td width="50%" align="right" style="font-size: 14pt; font-weight: bold;">Celkem: ' . esc_html( elementsell_format_invoice_amount( $total ) ) . '</td>';
    $html .= '</tr>';
    $html .= '</table>';

    return $html;
}

/**
 * @param int $order_id
 * @return string|false
 */
function elementsell_get_invoice_pdf_for_order( $order_id ) {
    elementsell_sync_invoice_with_order( $order_id );

    $invoice = elementsell_get_invoice_by_order_id( $order_id );

    if ( ! $invoice ) {
        error_log( 'ElementSell: faktura pro objednávku ' . intval( $order_id ) . ' neexistuje.' );
        return false;
    }

    $pdf_path = elementsell_generate_invoice_pdf_file( (int) $invoice->id );

    if ( ! $pdf_path ) {
        error_log( 'ElementSell: PDF faktury se nepodařilo vygenerovat pro objednávku ' . intval( $order_id ) . '.' );
    }

    return $pdf_path;
}
