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

add_action('init', 'kgdc_get_custom_coupon_code_to_session');
function kgdc_get_custom_coupon_code_to_session(){
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if ( isset( $_GET['coupon_code'] ) ) {
        // Ensure that customer session is started
        if( !WC()->session->has_session() )
            WC()->session->set_customer_session_cookie(true);

        // Check and register coupon code in a custom session variable
        $coupon_code = WC()->session->get('coupon_code');
        if(empty($coupon_code)){
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $coupon_code = sanitize_text_field( wp_unslash( $_GET['coupon_code'] ) );
            WC()->session->set( 'coupon_code', $coupon_code ); // Set the coupon code in session
        }
    }
}
add_action( 'woocommerce_before_checkout_form', 'kgdc_add_discout_to_checkout', 999, 0 );
add_action( 'woocommerce_before_cart_totals', 'kgdc_add_discout_to_checkout', 999 );

function kgdc_add_discout_to_checkout( ) {
    // Set coupon code
    $coupon_code = WC()->session->get('coupon_code');
    if ( ! empty( $coupon_code ) && ! WC()->cart->has_discount( $coupon_code ) ){
        WC()->cart->add_discount( $coupon_code ); // apply the coupon discount
        WC()->session->__unset('coupon_code'); // remove coupon code from session
    }
}

function kgdc_bulk_action( $bulk_actions ) {
    $bulk_actions[ 'export_to_pdf' ] = __( 'Export to WooCommerce Products Catalog', 'kg-digital-catalog-for-woocommerce' );
    return $bulk_actions;
}
add_filter( 'bulk_actions-edit-product', 'kgdc_bulk_action' );

function kgdc_bulk_callback( $redirect_to, $doaction, $product_ids ) {
    if ( $doaction !== 'export_to_pdf' ) {
        return $redirect_to;
    }
    kgdc_generate_pdf($product_ids);
    exit;
}
add_filter( 'handle_bulk_actions-edit-product', 'kgdc_bulk_callback', 10, 3 );

// Handler for Export All Catalogue shortcut
add_action('admin_init', 'kgdc_handle_all_products_export');
function kgdc_handle_all_products_export() {
    if (isset($_GET['kgdc_export_all']) && current_user_can('manage_options')) {
        if ( ! isset($_GET['_wpnonce']) || ! wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'kgdc_export_all_nonce') ) {
            wp_die( esc_html__( 'Security check failed. Please refresh the page and try again.', 'kg-digital-catalog-for-woocommerce' ) );
        }
        $args = array(
            'post_type'      => 'product',
            'posts_per_page' => -1,
            'post_status'    => 'publish',
            'fields'         => 'ids',
        );
        
        // phpcs:disable WordPress.Security.NonceVerification.Recommended
        if (isset($_GET['product_cat']) && !empty($_GET['product_cat'])) {
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
            $args['tax_query'] = array(
                array(
                    'taxonomy' => 'product_cat',
                    'field'    => 'slug',
                    'terms'    => sanitize_text_field( wp_unslash( $_GET['product_cat'] ) ),
                )
            );
        }

        if (isset($_GET['s']) && !empty($_GET['s'])) {
            $args['s'] = sanitize_text_field( wp_unslash( $_GET['s'] ) );
        }
        // phpcs:enable

        $product_ids = get_posts($args);
        
        if (!empty($product_ids)) {
            kgdc_generate_pdf($product_ids);
        } else {
            wp_die(esc_html__('No products found to export.', 'kg-digital-catalog-for-woocommerce'));
        }
        exit;
    }
}

function kgdc_generate_pdf($product_ids) {
    if (empty($product_ids)) return;

    // Silence errors and clear buffers to prevent PDF corruption
    @ini_set('display_errors', '0'); // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged
    @error_reporting(0); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.prevent_path_disclosure_error_reporting
    while (ob_get_level()) {
        ob_end_clean();
    }
    ob_start();

    require_once plugin_dir_path( __FILE__ ). 'admin/dompdf/autoload.inc.php';
    
    $options = new \Dompdf\Options();
    $options->set('isRemoteEnabled', true);
    $options->set('isHtml5ParserEnabled', true);
    $options->set('defaultFont', 'dejavusans');
    $upload_dir_info = wp_upload_dir();
    $options->set('chroot', array( realpath($upload_dir_info['basedir']), realpath(plugin_dir_path(__FILE__)) ));
    
    $dompdf = new \Dompdf\Dompdf($options);

    $compnay_logo = get_option('kgdc_compnay_logo');
    $cname = get_option('kgdc_compnay_name');
    $phone_number = get_option('kgdc_phone_number');
    $email_id = get_option('kgdc_email_id');
    $compnay_address = get_option('kgdc_compnay_address');
    $disable_logo = get_option('kgdc_disable_logo');
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $product_cat = isset( $_REQUEST['product_cat'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['product_cat'] ) ) : '';
    $display_cat = $product_cat ? ucwords(strtolower($product_cat)) : esc_html__('All Products', 'kg-digital-catalog-for-woocommerce');

    // Filter products (exclude draft, out of stock)
    $filtered_ids = array();
    foreach($product_ids as $pid){
        $prod = wc_get_product($pid);
        if ($prod && $prod->get_status() === 'publish' && $prod->is_in_stock()) {
            $filtered_ids[] = $pid;
        }
    }
    $product_ids = $filtered_ids;

    if (empty($product_ids)) {
        wp_die(esc_html__('No products found to export after filtering.', 'kg-digital-catalog-for-woocommerce'));
    }

    // Logo image paths
    $image_file = '';
    if ( ! $disable_logo ) {
        if ($compnay_logo) {
            $upload_dir = wp_upload_dir();
            $image_path = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $compnay_logo);
            if (file_exists($image_path)) {
                $image_file = str_replace('\\', '/', $image_path); // Use absolute local path
            } else {
                $image_file = $compnay_logo; // remote url
            }
        }
        if (!$image_file || (!file_exists($image_file) && strpos($image_file, 'http') === false)) {
            $image_file = str_replace('\\', '/', plugin_dir_path(__FILE__) . 'admin/images/logo.png');
        }
    }
    
    // Layout Helpers
    if (!function_exists('kgdc_get_clean_price')) {
        function kgdc_get_clean_price($product) {
            if (!$product) return '';
            
            $price = $product->get_price_html();
            
            // Hide WordPress screen reader text ("Original price was:")
            $price = preg_replace('/<span [^>]*class="[^"]*screen-reader-text[^"]*"[^>]*>.*?<\/span>/is', '', $price);
            
            // Clean up spacing and dashes for range formatting
            $price = str_replace(array('&nbsp;', '&#8211;', '&ndash;'), array(' ', ' - ', ' - '), $price);
            
            // Strip tags but preserve <del> (sale strike) and <ins>
            $clean_price = strip_tags($price, '<del><ins>');
            
            return $clean_price;
        }
    }

    $layouttype = get_option('kgdc_pdf_layout_type');
    
    // Utilizing default theme colors (black/white/neutral palette)
    $text_color = '#333333';
    $btn_color = '#222222';
    $btn_text_color = '#ffffff';
    $btn_label = get_option('kgdc_button_text', 'BUY NOW');
    
    $header_title_color = '#000000';
    $contact_icon_color = '#000000';
    $contact_text_color = '#333333';
    $product_title_color = '#000000';
    $product_price_color = '#000000';
    
    $company_link = get_option('kgdc_compnay_link');

    $pdf_style_path = plugin_dir_path(__FILE__) . 'admin/css/kgdc-pdf-style.css';
    $pdf_style = file_exists($pdf_style_path) ? file_get_contents($pdf_style_path) : '';

    $html = '<!DOCTYPE html><html><head><meta charset="UTF-8"><style>' . $pdf_style . '</style></head><body>';


    // Icon base64 generations removed in favor of explicit text labels

    $html .= '<header>
        <table class="header-table"><tr>';
    if ($image_file) {
        $logo_html = '<img src="'.$image_file.'" class="logo-img">';
        if ($company_link) {
            $logo_html = '<a href="'.esc_url($company_link).'" target="_blank" style="text-decoration:none;">'.$logo_html.'</a>';
        }
        $html .= '<td width="30%" align="left">'.$logo_html.'</td>';
    } else {
        $html .= '<td width="30%"></td>';
    }
    
    $html .= '<td width="40%" class="company-name" align="center">'.($cname ? esc_html($cname) : 'Products Catalog').'</td>';
    
    $html .= '<td width="30%" align="right">';
    if ($email_id || $phone_number) {
        $html .= '<table class="header-contact-table" cellpadding="0" cellspacing="0">';
        if ($email_id) {
            $html .= '<tr><td style="padding-right:6px; text-align:right; font-weight:bold; color:'.esc_attr($contact_icon_color).';">Email:</td><td align="left" style="vertical-align:middle;">'.esc_html($email_id).'</td></tr>';
        }
        if ($phone_number) {
            $html .= '<tr><td style="padding-right:6px; text-align:right; font-weight:bold; color:'.esc_attr($contact_icon_color).';">Phone:</td><td align="left" style="vertical-align:middle;">'.esc_html($phone_number).'</td></tr>';
        }
        $html .= '</table>';
    }
    $html .= '</td>';
    
    $html .= '</tr></table>
    </header>';

    $html .= '<footer>
        <table class="footer-table"><tr>
            <td width="40%" style="line-height: 1.4;">'.($compnay_address ? '<strong>Address:</strong><br>'.nl2br(esc_html($compnay_address)) : '').'</td>
            <td width="20%" align="center">Page <span class="page-number"></span></td>
            <td width="40%" align="right" style="line-height: 1.4;">';
            
    if ($email_id || $phone_number) {
        $html .= '<table cellpadding="0" cellspacing="0" style="float:right; font-size:10px; color:'.esc_attr($contact_text_color).';">';
        if ($email_id) {
            $html .= '<tr><td style="padding-right:6px; text-align:right; font-weight:bold; color:'.esc_attr($contact_icon_color).'; padding-bottom:4px;">Email:</td><td align="left" style="vertical-align:middle; padding-bottom:4px;">'.esc_html($email_id).'</td></tr>';
        }
        if ($phone_number) {
            $html .= '<tr><td style="padding-right:6px; text-align:right; font-weight:bold; color:'.esc_attr($contact_icon_color).';">Phone:</td><td align="left" style="vertical-align:middle;">'.esc_html($phone_number).'</td></tr>';
        }
        $html .= '</table>';
    }

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

    $html .= '<main>';
    $html .= '<div class="main-title">'.$display_cat.'</div>';

    if ($layouttype == 2) {
        // Grid Layout
        $html .= '<table class="grid-container">';
        $k = 0;
        foreach($product_ids as $product_id) {
            $product = wc_get_product( $product_id );
            if (!$product) continue;
            
            if ($k % 3 == 0) $html .= '<tr>';
            
            $title = $product->get_title();
            $price = kgdc_get_clean_price($product);
            $image_id = get_post_thumbnail_id( $product_id );
            
            $image_path = get_attached_file($image_id);
            if ($image_path && file_exists($image_path)) {
                $image_url = str_replace('\\', '/', $image_path);
            } else {
                $image_url = str_replace('\\', '/', plugin_dir_path(__FILE__) . 'admin/images/logo.png');
            }
            
            $buy_url = esc_url(get_permalink($product_id) . '?add-to-cart=' . $product_id . '&coupon_code=' . get_option('kgdc_coupan_code'));
            
            $html .= '<td width="33.33%" valign="top">
                <table class="grid-item" cellpadding="0" cellspacing="0">
                    <tr><td align="center" class="grid-img-td"><img src="'.$image_url.'" class="grid-img"></td></tr>
                    <tr><td class="grid-title">'.esc_html($title).'</td></tr>
                    <tr><td class="grid-price">'.wp_kses_post($price).'</td></tr>
                    <tr><td align="center"><a href="'.$buy_url.'" class="btn">'.esc_html($btn_label).'</a></td></tr>
                </table>
            </td>';
            
            if ($k % 3 == 2) $html .= '</tr>';
            $k++;
        }
        if ($k % 3 != 0) {
            while ($k % 3 != 0) {
                $html .= '<td width="33.33%"></td>';
                $k++;
            }
            $html .= '</tr>';
        }
        $html .= '</table>';
        
    } elseif ($layouttype == 3) {
        // Left - Right Layout
        $html .= '<table class="lr-table">';
        foreach($product_ids as $product_id) {
            $product = wc_get_product( $product_id );
            if (!$product) continue;
            
            $title = $product->get_title();
            $price = kgdc_get_clean_price($product);
            $short_desc = $product->get_short_description();
            if (empty($short_desc)) {
                $short_desc = __('Premium quality product with excellent features.', 'kg-digital-catalog-for-woocommerce');  
            }
            $image_id = get_post_thumbnail_id( $product_id );
            $image_path = get_attached_file($image_id);
            if ($image_path && file_exists($image_path)) {
                $image_url = str_replace('\\', '/', $image_path);
            } else {
                $image_url = str_replace('\\', '/', plugin_dir_path(__FILE__) . 'admin/images/logo.png');
            }
            $buy_url = esc_url(get_permalink($product_id) . '?add-to-cart=' . $product_id . '&coupon_code=' . get_option('kgdc_coupan_code'));
            
            $html .= '<tr><td colspan="2" style="padding:0;"><table class="lr-item" width="100%" cellpadding="0" cellspacing="0"><tr>
                <td class="lr-img-td">
                    <img src="'.$image_url.'" class="lr-img">
                </td>
                <td class="lr-content-td" valign="middle">
                    <div class="lr-title">'.esc_html($title).'</div>
                    <div class="lr-desc">'.wp_kses_post($short_desc).'</div>
                    <div class="lr-price">'.wp_kses_post($price).'</div>
                    <a href="'.$buy_url.'" class="btn btn-green">'.esc_html($btn_label).'</a>
                </td>
            </tr></table></td></tr>';
        }
        $html .= '</table>';
        
    } else {
        // List Layout
        $html .= '<table class="list-table">
            <thead>
                <tr>
                    <th width="8%" style="border-top-left-radius:8px;">ID</th>
                    <th width="15%">Image</th>
                    <th width="40%">Product Name</th>
                    <th width="17%">Price</th>
                    <th width="20%" style="text-align:center; border-top-right-radius:8px;">Action</th>
                </tr>
            </thead>
            <tbody>';
        
        $i = 1;
        foreach($product_ids as $product_id) {
            $product = wc_get_product( $product_id );
            if (!$product) continue;
            
            $title = $product->get_title();
            $price = kgdc_get_clean_price($product);
            $image_id = get_post_thumbnail_id( $product_id );
            $image_path = get_attached_file($image_id);
            if ($image_path && file_exists($image_path)) {
                $image_url = str_replace('\\', '/', $image_path);
            } else {
                $image_url = str_replace('\\', '/', plugin_dir_path(__FILE__) . 'admin/images/logo.png');
            }
            $buy_url = esc_url(get_permalink($product_id) . '?add-to-cart=' . $product_id . '&coupon_code=' . get_option('kgdc_coupan_code'));
            
            $html .= '<tr>
                <td style="color: #718096; font-weight: 600;">'.$i.'</td>
                <td><img src="'.$image_url.'" class="list-prod-img"></td>
                <td class="list-prod-title">'.esc_html($title).'</td>
                <td class="list-prod-price">'.wp_kses_post($price).'</td>
                <td align="center">
                    <a href="'.$buy_url.'" class="btn">'.esc_html($btn_label).'</a>
                </td>
            </tr>';
            $i++;
        }
        $html .= '</tbody></table>';
    }

    $html .= '</main></body></html>';

    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();

    $pdf_name = ($product_cat ? $product_cat : 'product').'_catalog_'.wp_rand().'.pdf';
    $upload_dir = wp_upload_dir();
    
    // Save to server
    $output = $dompdf->output();
    file_put_contents($upload_dir['basedir'].'/'.$pdf_name, $output);
    
    $postId = wp_insert_post(array('post_title'=>$pdf_name, 'post_type'=>'kgdc_pdf_history', 'post_status'=>'publish' ));
    update_post_meta( $postId, 'kgdc_pdf_history', $upload_dir['baseurl'].'/'.$pdf_name );
    
    // Force clean the buffer one last time before outputting binary data to browser
    while (ob_get_level()) {
        ob_end_clean();
    }
    
    $dompdf->stream($pdf_name, array("Attachment" => true));
}
