<?php
/**
 * Plugin Name: ScanVault Label Designer
 * Plugin URI:  https://scan-vault.com/label-designer/
 * Description: Drag-and-drop label designer for WooCommerce. Create custom labels with Text, Barcode, QR Code, and Images.
 * Version:     2.2.6
 * Author:      Molay Soltan
 * Author URI:  https://scan-vault.com
 * License:     GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: scanvault-label-designer
 * Domain Path: /languages
 * Requires at least: 5.8
 * Requires PHP: 7.4
 * WC requires at least: 6.0
 * WC tested up to: 9.0
 */

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

// Plugin constants
define( 'SVLD_VERSION',    '2.2.6' );
define( 'SVLD_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'SVLD_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'SVLD_PLUGIN_FILE', __FILE__ );

// ---------------------------------------------------------------------------
// Freemius SDK Integration
// ---------------------------------------------------------------------------

// Freemius auto-deactivation mechanism for free/premium switching
if ( function_exists( 'svld_fs' ) ) {
    svld_fs()->set_basename( true, __FILE__ );
} else {
    // DO NOT REMOVE THIS IF, IT IS ESSENTIAL FOR THE
    // PLUGIN TO WORK WHEN INSTALLED DIRECTLY FROM ZIP.
    if ( ! function_exists( 'svld_fs' ) ) {
        // Create a helper function for easy SDK access.
        function svld_fs() {
            global $svld_fs;

            if ( ! isset( $svld_fs ) ) {
                // Include Freemius SDK.
                require_once dirname( __FILE__ ) . '/vendor/freemius/start.php';

                $svld_fs = fs_dynamic_init( array(
                    'id'                  => '27816',
                    'slug'                => 'scanvault-label-designer',
                    'type'                => 'plugin',
                    'public_key'          => 'pk_556e881b04db8eb6f50a994de1bfb',
                    'is_premium'          => false,
                    'premium_suffix'      => 'Pro',
                    'has_premium_version' => true,
                    'has_addons'          => false,
                    'has_paid_plans'      => true,
                    'is_org_compliant'    => true,
                    'trial'               => array(
                        'days'               => 14,
                        'is_require_payment' => false,
                    ),
                    'menu'                => array(
                        'slug'    => 'svld-designer',
                        'support' => false,
                    ),
                ) );
            }

            return $svld_fs;
        }

        // Init Freemius.
        svld_fs();
        // Signal that SDK was initiated.
        do_action( 'svld_fs_loaded' );
    }
}

// Tell Freemius pricing page which icon to use
add_filter( 'fs_plugin_icon_scanvault-label-designer', function() {
    return SVLD_PLUGIN_DIR . 'assets/img/scanvault-label-designer.png';
} );

// Customize Freemius opt-in message
function scanvault_label_designer_fs_custom_connect_message(
    $message,
    $user_first_name,
    $plugin_title,
    $user_login,
    $site_link,
    $freemius_link
) {
    return sprintf(
        // translators: %1$s: user's first name, %2$s: plugin title
        __( 'Hey %1$s, help us improve %2$s by sharing basic usage data. You can always opt out. In return, get security updates and new features automatically.', 'scanvault-label-designer' ),
        $user_first_name,
        '<b>' . $plugin_title . '</b>'
    );
}
add_filter(
    'svld_fs_connect_message',
    'scanvault_label_designer_fs_custom_connect_message',
    10,
    6
);

// Skip email confirmation - allow anonymous usage
function scanvault_label_designer_fs_is_allow_anonymous() {
    return true;
}
add_filter(
    'svld_fs_is_allow_anonymous',
    'scanvault_label_designer_fs_is_allow_anonymous'
);

// ---------------------------------------------------------------------------
// WooCommerce dependency check
// ---------------------------------------------------------------------------

/**
 * Check if user has Pro plan.
 * Checks own Freemius license first, then falls back to ScanVault Business tier.
 */
function svld_is_pro(): bool {
    // Check own Freemius license first
    if ( function_exists( 'svld_fs' ) ) {
        try {
            if ( svld_fs()->is_paying() ) {
                return true;
            }
        } catch ( \Exception $e ) {
            // Continue to fallback
        }
    }

    // ScanVault Business also grants Label Designer access
    if ( function_exists( 'wbs_is_business' ) && wbs_is_business() ) {
        return true;
    }

    return false;
}
function svld_check_woocommerce(): bool {
    return class_exists( 'WooCommerce' );
}

add_action( 'admin_notices', function () {
    if ( ! svld_check_woocommerce() ) {
        echo '<div class="notice notice-error"><p><strong>ScanVault Label Designer</strong> requires WooCommerce to be installed and active.</p></div>';
    }
} );

// ---------------------------------------------------------------------------
// HPOS compatibility declaration
// ---------------------------------------------------------------------------
add_action( 'before_woocommerce_init', function () {
    if ( class_exists( \Automattic\WooCommerce\Utilities\FeaturesUtil::class ) ) {
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
    }
} );

// ---------------------------------------------------------------------------
// Bootstrap
// ---------------------------------------------------------------------------
function svld_init(): void {
    if ( ! svld_check_woocommerce() ) {
        return;
    }

    // Reset default layout when the plugin version changes, or when the stored
    // layout has stale elements that are missing the 'visible' field (legacy structure).
    $installed_version = get_option( 'svld_layout_version', '0' );
    $needs_reset       = version_compare( $installed_version, SVLD_VERSION, '<' );

    if ( ! $needs_reset ) {
        // Also check for stale layout: if any element lacks 'visible', reset.
        $stored_layout = get_option( 'svld_layout', [] );
        if ( is_array( $stored_layout ) && ! empty( $stored_layout ) ) {
            foreach ( $stored_layout as $el ) {
                if ( ! array_key_exists( 'visible', $el ) ) {
                    $needs_reset = true;
                    break;
                }
            }
        } elseif ( empty( $stored_layout ) ) {
            $needs_reset = true;
        }
    }

    if ( $needs_reset ) {
        update_option( 'svld_layout', svld_default_layout() );
        update_option( 'svld_layout_version', SVLD_VERSION );
    }

    require_once SVLD_PLUGIN_DIR . 'includes/class-svld-menu.php';
    require_once SVLD_PLUGIN_DIR . 'includes/class-svld-ajax.php';
    require_once SVLD_PLUGIN_DIR . 'includes/class-svld-renderer.php';
    require_once SVLD_PLUGIN_DIR . 'includes/class-svld-product-loop.php';
    require_once SVLD_PLUGIN_DIR . 'includes/class-svld-order-loop.php';
    require_once SVLD_PLUGIN_DIR . 'includes/class-svld-metabox.php';
    require_once SVLD_PLUGIN_DIR . 'includes/class-svld-scanner-bridge.php';

    new SVLD_Menu();
    new SVLD_Ajax();
    new SVLD_Product_Loop();
    new SVLD_Order_Loop();
    new SVLD_Metabox();
    new SVLD_Scanner_Bridge();
}
add_action( 'plugins_loaded', 'svld_init' );

// ---------------------------------------------------------------------------
// Activation/Deactivation hooks
// ---------------------------------------------------------------------------
register_activation_hook( __FILE__, 'svld_activate' );
register_deactivation_hook( __FILE__, 'svld_deactivate' );

function svld_activate(): void {
    // Reset layout when the plugin version changes (layout schema updated)
    $installed_version = get_option( 'svld_layout_version', '0' );
    if ( version_compare( $installed_version, SVLD_VERSION, '<' ) ) {
        update_option( 'svld_layout', svld_default_layout() );
        update_option( 'svld_layout_version', SVLD_VERSION );
    } elseif ( ! get_option( 'svld_layout' ) ) {
        update_option( 'svld_layout', svld_default_layout() );
        update_option( 'svld_layout_version', SVLD_VERSION );
    }

    // Default label settings
    $defaults = [
        'svld_print_on_product_page' => '1',
        'svld_print_on_order_page'   => '1',
        'svld_print_bulk_action'     => '1',
    ];
    foreach ( $defaults as $key => $value ) {
        if ( false === get_option( $key ) ) {
            update_option( $key, $value );
        }
    }

    // Schedule PDF cleanup cron (daily)
    if ( ! wp_next_scheduled( 'svld_pdf_cleanup' ) ) {
        wp_schedule_event( time(), 'daily', 'svld_pdf_cleanup' );
    }
}

function svld_deactivate(): void {
    // Clear PDF cleanup cron
    wp_clear_scheduled_hook( 'svld_pdf_cleanup' );
}

// PDF cleanup callback
add_action( 'svld_pdf_cleanup', 'svld_cleanup_pdf_files' );

function svld_cleanup_pdf_files(): void {
    $upload_dir = wp_upload_dir();
    $pdf_dir = $upload_dir['basedir'] . '/svld-labels/';

    if ( ! is_dir( $pdf_dir ) ) {
        return;
    }

    $files = glob( $pdf_dir . '*.pdf' );
    $now = time();
    $max_age = DAY_IN_SECONDS; // 24 hours

    foreach ( $files as $file ) {
        if ( $now - filemtime( $file ) > $max_age ) {
            wp_delete_file( $file );
        }
    }
}

/**
 * Returns all built-in preset layouts keyed by slug.
 */
function svld_get_preset_layouts(): array {
    return [
        'product'  => [
            'name'         => __( 'Product Label', 'scanvault-label-designer' ),
            'label_type'   => 'product',
            'label_width'  => 100,
            'label_height' => 50,
            'layout'       => svld_default_layout(),
        ],
        'shipping' => [
            'name'        => __( 'Shipping Label', 'scanvault-label-designer' ),
            'label_type'  => 'shipping',
            'label_width' => 100,
            'label_height'=> 150,
            'layout'      => [
                [ 'id'=>'text_1000','type'=>'text','label'=>'From','x'=>5,'y'=>5,'width'=>90,'height'=>7,'fontSize'=>7,'bold'=>false,'align'=>'left','visible'=>true,'dataSource'=>'site_url','customText'=>'','multiLine'=>false,'proportional'=>false ],
                [ 'id'=>'text_1001','type'=>'text','label'=>'To - Name','x'=>5,'y'=>20,'width'=>90,'height'=>9,'fontSize'=>11,'bold'=>true,'align'=>'left','visible'=>true,'dataSource'=>'customer_full_name','customText'=>'','multiLine'=>false,'proportional'=>false ],
                [ 'id'=>'text_1002','type'=>'text','label'=>'Shipping Address','x'=>5,'y'=>31,'width'=>90,'height'=>30,'fontSize'=>9,'bold'=>false,'align'=>'left','visible'=>true,'dataSource'=>'shipping_address','customText'=>'','multiLine'=>true,'proportional'=>false ],
                [ 'id'=>'text_1003','type'=>'text','label'=>'Order #','x'=>5,'y'=>66,'width'=>55,'height'=>8,'fontSize'=>9,'bold'=>false,'align'=>'left','visible'=>true,'dataSource'=>'order_number','customText'=>'','multiLine'=>false,'proportional'=>false ],
                [ 'id'=>'text_1004','type'=>'text','label'=>'Shipping Method','x'=>5,'y'=>76,'width'=>70,'height'=>7,'fontSize'=>8,'bold'=>false,'align'=>'left','visible'=>true,'dataSource'=>'shipping_method','customText'=>'','multiLine'=>false,'proportional'=>false ],
                [ 'id'=>'barcode_1005','type'=>'barcode','label'=>'Barcode','x'=>5,'y'=>88,'width'=>70,'height'=>20,'visible'=>true,'showText'=>true,'dataSource'=>'order_number','multiLine'=>false,'proportional'=>false ],
                [ 'id'=>'qr_1006','type'=>'qr','label'=>'QR','x'=>78,'y'=>88,'width'=>20,'height'=>20,'visible'=>true,'dataSource'=>'product_link','multiLine'=>false,'proportional'=>false ],
            ],
        ],
        'invoice'  => [
            'name'        => __( 'Invoice Label', 'scanvault-label-designer' ),
            'label_type'  => 'invoice',
            'label_width' => 210,
            'label_height'=> 297,
            'layout'      => [
                [ 'id'=>'text_1000','type'=>'text','label'=>'Shop Name','x'=>5,'y'=>5,'width'=>100,'height'=>12,'fontSize'=>14,'bold'=>true,'align'=>'left','visible'=>true,'dataSource'=>'site_url','customText'=>'','multiLine'=>false,'proportional'=>false ],
                [ 'id'=>'text_1001','type'=>'text','label'=>'Invoice Title','x'=>140,'y'=>5,'width'=>65,'height'=>12,'fontSize'=>14,'bold'=>true,'align'=>'right','visible'=>true,'dataSource'=>'custom','customText'=>'INVOICE','multiLine'=>false,'proportional'=>false ],
                [ 'id'=>'text_1002','type'=>'text','label'=>'Order #','x'=>140,'y'=>20,'width'=>65,'height'=>7,'fontSize'=>9,'bold'=>false,'align'=>'right','visible'=>true,'dataSource'=>'order_number','customText'=>'','multiLine'=>false,'proportional'=>false ],
                [ 'id'=>'text_1003','type'=>'text','label'=>'Order Date','x'=>140,'y'=>29,'width'=>65,'height'=>7,'fontSize'=>9,'bold'=>false,'align'=>'right','visible'=>true,'dataSource'=>'order_date','customText'=>'','multiLine'=>false,'proportional'=>false ],
                [ 'id'=>'text_1004','type'=>'text','label'=>'Bill To','x'=>5,'y'=>50,'width'=>90,'height'=>7,'fontSize'=>9,'bold'=>true,'align'=>'left','visible'=>true,'dataSource'=>'custom','customText'=>'BILL TO:','multiLine'=>false,'proportional'=>false ],
                [ 'id'=>'text_1005','type'=>'text','label'=>'Customer Name','x'=>5,'y'=>59,'width'=>90,'height'=>8,'fontSize'=>10,'bold'=>false,'align'=>'left','visible'=>true,'dataSource'=>'customer_full_name','customText'=>'','multiLine'=>false,'proportional'=>false ],
                [ 'id'=>'text_1006','type'=>'text','label'=>'Billing Address','x'=>5,'y'=>69,'width'=>90,'height'=>25,'fontSize'=>9,'bold'=>false,'align'=>'left','visible'=>true,'dataSource'=>'billing_address','customText'=>'','multiLine'=>true,'proportional'=>false ],
                [ 'id'=>'text_1007','type'=>'text','label'=>'Ship To','x'=>110,'y'=>50,'width'=>90,'height'=>7,'fontSize'=>9,'bold'=>true,'align'=>'left','visible'=>true,'dataSource'=>'custom','customText'=>'SHIP TO:','multiLine'=>false,'proportional'=>false ],
                [ 'id'=>'text_1008','type'=>'text','label'=>'Shipping Address','x'=>110,'y'=>59,'width'=>90,'height'=>25,'fontSize'=>9,'bold'=>false,'align'=>'left','visible'=>true,'dataSource'=>'shipping_address','customText'=>'','multiLine'=>true,'proportional'=>false ],
                [ 'id'=>'text_1009','type'=>'text','label'=>'Payment Method','x'=>5,'y'=>240,'width'=>100,'height'=>7,'fontSize'=>9,'bold'=>false,'align'=>'left','visible'=>true,'dataSource'=>'payment_method','customText'=>'','multiLine'=>false,'proportional'=>false ],
                [ 'id'=>'text_1010','type'=>'text','label'=>'Order Total','x'=>110,'y'=>240,'width'=>90,'height'=>9,'fontSize'=>11,'bold'=>true,'align'=>'right','visible'=>true,'dataSource'=>'order_total','customText'=>'','multiLine'=>false,'proportional'=>false ],
            ],
        ],
        'return'   => [
            'name'        => __( 'Return Label', 'scanvault-label-designer' ),
            'label_type'  => 'return',
            'label_width' => 100,
            'label_height'=> 100,
            'layout'      => [
                [ 'id'=>'text_1000','type'=>'text','label'=>'Return To','x'=>5,'y'=>5,'width'=>90,'height'=>7,'fontSize'=>9,'bold'=>true,'align'=>'center','visible'=>true,'dataSource'=>'custom','customText'=>'RETURN TO:','multiLine'=>false,'proportional'=>false ],
                [ 'id'=>'text_1001','type'=>'text','label'=>'Shop','x'=>5,'y'=>14,'width'=>90,'height'=>8,'fontSize'=>10,'bold'=>true,'align'=>'center','visible'=>true,'dataSource'=>'site_url','customText'=>'','multiLine'=>false,'proportional'=>false ],
                [ 'id'=>'text_1002','type'=>'text','label'=>'Customer','x'=>5,'y'=>32,'width'=>90,'height'=>7,'fontSize'=>9,'bold'=>false,'align'=>'left','visible'=>true,'dataSource'=>'customer_full_name','customText'=>'','multiLine'=>false,'proportional'=>false ],
                [ 'id'=>'text_1003','type'=>'text','label'=>'Order #','x'=>5,'y'=>41,'width'=>90,'height'=>7,'fontSize'=>9,'bold'=>false,'align'=>'left','visible'=>true,'dataSource'=>'order_number','customText'=>'','multiLine'=>false,'proportional'=>false ],
                [ 'id'=>'qr_1004','type'=>'qr','label'=>'QR','x'=>35,'y'=>55,'width'=>30,'height'=>30,'visible'=>true,'dataSource'=>'product_link','multiLine'=>false,'proportional'=>false ],
                [ 'id'=>'text_1005','type'=>'text','label'=>'Reason','x'=>5,'y'=>90,'width'=>90,'height'=>6,'fontSize'=>7,'bold'=>false,'align'=>'center','visible'=>true,'dataSource'=>'custom','customText'=>'Reason:','multiLine'=>false,'proportional'=>false ],
            ],
        ],
    ];
}

/**
 * Returns the TCPDF font that best matches the site's WordPress locale.
 * Falls back to dejavusans (full Unicode) for all non-CJK locales.
 */
function svld_get_default_font(): string {
    $locale = get_locale();

    $exact_map = [
        'zh_CN' => 'cid0cs',
        'zh_TW' => 'cid0ct',
        'zh_HK' => 'cid0ct',
        'ja'    => 'cid0jp',
        'ja_JP' => 'cid0jp',
        'ko'    => 'cid0kr',
        'ko_KR' => 'cid0kr',
    ];

    if ( isset( $exact_map[ $locale ] ) ) {
        return $exact_map[ $locale ];
    }

    $lang = substr( $locale, 0, 2 );
    $lang_map = [
        'zh' => 'cid0cs',
        'ja' => 'cid0jp',
        'ko' => 'cid0kr',
    ];

    return $lang_map[ $lang ] ?? 'dejavusans';
}

/**
 * Returns the configured label font (falls back to locale-detected default).
 */
function svld_get_label_font(): string {
    return get_option( 'svld_label_font', svld_get_default_font() );
}

/**
 * Returns the default label layout — 4 elements with position and style defaults.
 */
function svld_default_layout(): array {
    return [
        [
            'id'         => 'text_1000',
            'type'       => 'text',
            'label'      => 'Product Name',
            'x'          => 5,
            'y'          => 4,
            'width'      => 90,
            'height'     => 12,
            'fontSize'   => 10,
            'bold'       => true,
            'align'      => 'center',
            'visible'    => true,
            'dataSource' => 'product_name',
            'customText' => '',
            'multiLine'  => false,
            'proportional' => false,
        ],
        [
            'id'         => 'text_1001',
            'type'       => 'text',
            'label'      => 'Product Price',
            'x'          => 5,
            'y'          => 17,
            'width'      => 55,
            'height'     => 8,
            'fontSize'   => 9,
            'bold'       => true,
            'align'      => 'center',
            'visible'    => true,
            'dataSource' => 'product_price',
            'customText' => '',
            'multiLine'  => false,
            'proportional' => false,
        ],
        [
            'id'        => 'barcode_1002',
            'type'      => 'barcode',
            'label'     => 'Barcode',
            'x'         => 5,
            'y'         => 27,
            'width'     => 58,
            'height'    => 17,
            'visible'   => true,
            'showText'  => true,
            'dataSource' => 'product_id',
            'multiLine' => false,
            'proportional' => false,
        ],
        [
            'id'        => 'qr_1003',
            'type'      => 'qr',
            'label'     => 'QR Code',
            'x'         => 67,
            'y'         => 17,
            'width'     => 28,
            'height'    => 28,
            'visible'   => true,
            'dataSource' => 'product_link',
            'multiLine' => false,
            'proportional' => false,
        ],
    ];
}
