<?php
/**
 * Plugin Name: Thermal Print Pro
 * Description: Classic 80mm Thermal Receipt with QR, Footer, Multi-language, Secure Download & Auto Email.
 * Version: 8.1
 * Author: Naim Reza
 * Author URI: https://naimreza.com
 */

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

use Dompdf\Dompdf;
use Dompdf\Options;

// Load Dompdf
if ( file_exists( plugin_dir_path( __FILE__ ) . 'lib/dompdf/autoload.inc.php' ) ) {
    require_once plugin_dir_path( __FILE__ ) . 'lib/dompdf/autoload.inc.php';
}

/**
 * PRICE FORMAT
 */
function tp_price($amount, $order){
    return number_format($amount,2).' '.$order->get_currency();
}

/**
 * SETTINGS
 */
add_filter('woocommerce_settings_tabs_array', function($tabs){
    $tabs['tp'] = 'Thermal Print';
    return $tabs;
},50);

add_action('woocommerce_settings_tabs_tp', function(){
    woocommerce_admin_fields(tp_fields());
});

add_action('woocommerce_update_options_tp', function(){
    woocommerce_update_options(tp_fields());
});

function tp_fields(){
    return array(
        array('title'=>'Shop Info','type'=>'title'),
        array('title'=>'Shop Name','id'=>'tp_name','type'=>'text'),
        array('title'=>'Address','id'=>'tp_addr','type'=>'textarea'),
        array('title'=>'Phone','id'=>'tp_phone','type'=>'text'),
        array('type'=>'sectionend'),
        array('title'=>'Receipt Settings','type'=>'title'),
        array('title'=>'Logo URL','id'=>'tp_logo','type'=>'text'),
        array(
            'title'=>'Footer Message',
            'id'=>'tp_footer',
            'type'=>'text',
            'default'=>'Thank you for your order. We look forward to serving you again.'
        ),
        array(
            'title'=>'Language',
            'id'=>'tp_lang',
            'type'=>'select',
            'options'=>array(
                'en'=>'English',
                'bn'=>'Bangla'
            )
        ),
        array('type'=>'sectionend')
    );
}

/**
 * MULTI LANGUAGE
 */
function tp_text($key){
    $lang = get_option('tp_lang','en');
    $t = array(
        'en'=>array(
            'order'=>'ORDER',
            'status'=>'Status',
            'subtotal'=>'Subtotal',
            'discount'=>'Discount',
            'total'=>'TOTAL',
            'customer'=>'Customer',
            'phone'=>'Phone',
            'payment'=>'Payment'
        ),
        'bn'=>array(
            'order'=>'অর্ডার',
            'status'=>'স্ট্যাটাস',
            'subtotal'=>'সাবটোটাল',
            'discount'=>'ডিসকাউন্ট',
            'total'=>'মোট',
            'customer'=>'কাস্টমার',
            'phone'=>'ফোন',
            'payment'=>'পেমেন্ট'
        )
    );
    return $t[$lang][$key] ?? $key;
}

/**
 * PDF GENERATION
 */
function tp_pdf($order_id){
    if(!class_exists('Dompdf\Dompdf')) return;
    $order = wc_get_order($order_id);
    if(!$order) return;

    $logo   = get_option('tp_logo');
    $footer = get_option('tp_footer');

    $qr = 'https://api.qrserver.com/v1/create-qr-code/?size=60x60&data=Order-'.$order_id;

    ob_start();
    ?>
<html>
<head>
<style>
@page { margin:0; }
body { font-family:Helvetica, Arial, sans-serif; font-size:11px; width:72mm; margin:4mm auto; color:#000; line-height:1.3; }
.center{text-align:center;}
.right{text-align:right;}
.bold{font-weight:bold;}
.divider { border-top:1px dashed #000; margin:6px 0; }
table{width:100%; border-collapse: collapse;}
.items-table td{padding:4px 0; vertical-align:top;}
.total-table td{padding:2px 0;}
.status-box { border:1px solid #000; padding:2px 4px; text-transform: uppercase; font-weight:bold; font-size:9px; margin-top:3px; display:inline-block; }
.logo { max-width:50px; margin-bottom:5px; }
.footer { margin-top:8px; font-size:10px; }
</style>
</head>
<body>

<div class="center">
<?php if($logo): ?><img src="<?php echo esc_url($logo); ?>" class="logo"><br><?php endif; ?>
<strong style="font-size:15px;"><?php echo esc_html(get_option('tp_name')); ?></strong><br>
<?php echo nl2br(esc_html(get_option('tp_addr'))); ?><br>
<?php if($phone = get_option('tp_phone')) echo "Tel: ".esc_html($phone); ?>
<div class="divider"></div>
<strong><?php echo tp_text('order'); ?> #<?php echo $order_id; ?></strong><br>
<span><?php echo $order->get_date_created()->date('d/m/Y H:i'); ?></span><br>
<div class="status-box"><?php echo tp_text('status'); ?>: <?php echo wc_get_order_status_name($order->get_status()); ?></div>
</div>

<div class="divider"></div>

<table class="items-table">
<?php foreach($order->get_items() as $item): ?>
<tr>
<td><?php echo $item->get_quantity(); ?>x <?php echo esc_html($item->get_name()); ?></td>
<td class="right"><?php echo tp_price($item->get_total(), $order); ?></td>
</tr>
<?php endforeach; ?>
</table>

<div class="divider"></div>

<table class="total-table">
<tr><td><?php echo tp_text('subtotal'); ?>:</td><td class="right"><?php echo tp_price($order->get_subtotal(), $order); ?></td></tr>
<?php if($order->get_total_discount()>0): ?>
<tr><td><?php echo tp_text('discount'); ?>:</td><td class="right">-<?php echo tp_price($order->get_total_discount(), $order); ?></td></tr>
<?php endif; ?>
<?php foreach($order->get_fees() as $fee): ?>
<tr><td><?php echo esc_html($fee->get_name()); ?>:</td><td class="right"><?php echo tp_price($fee->get_total(), $order); ?></td></tr>
<?php endforeach; ?>
<tr class="bold"><td style="font-size:13px; padding-top:5px;"><?php echo tp_text('total'); ?>:</td><td class="right" style="font-size:13px; padding-top:5px;"><?php echo tp_price($order->get_total(), $order); ?></td></tr>
</table>

<div class="divider"></div>

<div class="center">
<?php echo tp_text('customer'); ?>: <?php echo $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(); ?><br>
<?php echo tp_text('phone'); ?>: <?php echo $order->get_billing_phone(); ?><br>
<?php echo tp_text('payment'); ?>: <?php echo $order->get_payment_method_title(); ?><br>
<br>
<img src="<?php echo esc_url($qr); ?>" width="60" style="margin-top:5px;"><br>
<div class="footer"><?php echo esc_html($footer); ?></div>
</div>

</body>
</html>
<?php
    $html = ob_get_clean();
    $options = new Options();
    $options->set('isRemoteEnabled', true);
    $dompdf = new Dompdf($options);
    $dompdf->loadHtml($html);

    // Auto height
    $count = count($order->get_items()) + count($order->get_fees());
    $height = 130 + ($count * 12);
    $dompdf->setPaper([0,0,226.77,($height/25.4)*72], 'portrait');

    $dompdf->render();
    return $dompdf->output();
}

/**
 * SECURE DOWNLOAD HANDLER
 */
add_action('wp_ajax_tp_dl','tp_dl');
add_action('wp_ajax_nopriv_tp_dl','tp_dl');
function tp_dl(){
    $nonce = sanitize_text_field($_GET['nonce'] ?? '');
    if(!wp_verify_nonce($nonce,'tp')) die('Security error');
    $oid = absint($_GET['oid']);
    $order = wc_get_order($oid);
    if(!$order) die('Invalid order');
    if(!current_user_can('manage_woocommerce') && $order->get_customer_id()!=get_current_user_id()) die('Access denied');

    $pdf = tp_pdf($oid);
    header('Content-Type: application/pdf');
    echo $pdf;
    exit;
}

/**
 * ADMIN BUTTON
 */
add_action('woocommerce_admin_order_data_after_order_details', function($order){
    $url = admin_url('admin-ajax.php?action=tp_dl&oid='.$order->get_id().'&nonce='.wp_create_nonce('tp'));
    echo '<div style="margin-top:15px;padding:12px;border:1px solid #ddd;background:#f9f9f9;text-align:center;overflow:hidden;">
    <a target="_blank" href="'.$url.'" style="background:#2271b1;color:#fff;padding:10px 18px;text-decoration:none;font-weight:600;border-radius:4px;display:inline-block;">📄 Download Receipt</a>
    </div>';
});

/**
 * MY ACCOUNT BUTTON
 */
add_filter('woocommerce_my_account_my_orders_actions', function($actions,$order){
    $actions['tp_download'] = array(
        'url'=>admin_url('admin-ajax.php?action=tp_dl&oid='.$order->get_id().'&nonce='.wp_create_nonce('tp')),
        'name'=>'Receipt (PDF)',
    );
    return $actions;
},10,2);

/**
 * VIEW ORDER PAGE BUTTON
 */
add_action('woocommerce_view_order', function($order_id){
    $url = admin_url('admin-ajax.php?action=tp_dl&oid='.$order_id.'&nonce='.wp_create_nonce('tp'));
    echo '<p><a target="_blank" href="'.$url.'" class="button" style="background:#000;color:#fff;padding:10px 20px;">Download Receipt</a></p>';
});

/**
 * EMAIL ATTACHMENT
 */
add_filter('woocommerce_email_attachments', function($attachments,$email_id,$order){
    if(is_object($order)){
        $file = wp_upload_dir()['basedir'].'/receipt-'.$order->get_id().'.pdf';
        file_put_contents($file,tp_pdf($order->get_id()));
        $attachments[] = $file;
        register_shutdown_function(function() use($file){if(file_exists($file)) unlink($file);});
    }
    return $attachments;
},10,3);