<?php
/**
 * Plugin Name: Brand-A-Bean
 * Plugin URI: https://calutech.com/brand-a-bean.html
 * Description: Coffee dropshipping with your logo for private label. Upload your logo to automatically put it on all the coffee products.
 * Version: 1.0.5
 * Requires at least: 6.7
 * Tested up to: 6.9
 * Requires PHP: 8.0
 * Author: Calutech Inc
 * Author URI: https://calutech.com
 * Text Domain: brand-a-bean
 * WC requires at least: 7.9
 * WC tested up to: 10.4
 * Requires Plugins: woocommerce
 * License: GPLv3
 * License URI: https://www.gnu.org/licenses/gpl-3.0.html
 */
if (!defined('ABSPATH')) {
    exit;
}

class Brandabean_Logo_Overlay {
// set up the plugin and wp navigation menu
function brandabean_include_file($file) {
        $file_path = plugin_dir_path(__FILE__) . $file;

        if (file_exists($file_path)) {
            include_once $file_path;
        } else {
            echo '<div class="error"><p>Error: An internal error occurred. Please contact support.</p></div>';
        }
    }

    function brandabean_how_this_works_callback() {
        $this->brandabean_include_file('how.php');
    }

    function brandabean_send_logo_callback() {
        $this->brandabean_include_file('send.php');
    }

    function brandabean_trademarks_callback() {
        $this->brandabean_include_file('info.php');
    }

    function brandabean_add_products_callback() {
        $this->brandabean_include_file('products.php');
    }
    
    public function brandabean_create_plugin_menu() {
        add_menu_page('Brand-A-Bean', 'Brand-A-Bean', 'manage_options', 'brandabean-coffee-dropship_menu', array($this, 'brandabean_plugin_settings_page'), 'dashicons-coffee', 56);
        add_submenu_page('brandabean-coffee-dropship_menu', 'How This Works', 'How This Works', 'manage_options', 'coffee-dropship-how-this-works', array($this, 'brandabean_how_this_works_callback'));
        add_submenu_page('brandabean-coffee-dropship_menu', 'Send Your Logo', 'Send Your Logo', 'manage_options', 'coffee-dropship-send-logo', array($this, 'brandabean_send_logo_callback'));
        add_submenu_page('brandabean-coffee-dropship_menu', 'Trademarks', 'Trademarks', 'manage_options', 'coffee-dropship-trademarks', array($this, 'brandabean_trademarks_callback'));
        add_submenu_page('brandabean-coffee-dropship_menu', 'Manage Products', 'Manage Products', 'manage_options', 'coffee-dropship-products', array($this, 'brandabean_add_products_callback'));
    }
    private $image_dir;
    private $reset_dir;
    public function __construct() {
        $this->image_dir = plugin_dir_path(__FILE__) . 'img/';
        $this->reset_dir = plugin_dir_path(__FILE__) . 'img/reset/';
        add_action('admin_menu', array($this, 'brandabean_create_plugin_menu'));
        add_action('admin_post_brandabean_process_logo_upload', array($this, 'brandabean_process_logo_upload'));
        add_action('admin_post_brandabean_reset_images', array($this, 'brandabean_reset_images'));
    }
    
    public function brandabean_plugin_settings_page() {
        $adm_url = admin_url( 'admin.php?page=' );
        $plu_url = plugin_dir_url(__FILE__);
        // set up the graphical user interface buttons for ease of navigation inside
        ?>
        <div class="wrap">
            <img src="<?php echo esc_url($plu_url) . 'static-images/dlogowide.png'; ?>" alt="Logo" style="max-width:100%; height:auto;"><br>
            <a href="<?php echo esc_url($adm_url) . 'coffee-dropship-trademarks'; ?>">
            <img src="<?php echo esc_url($plu_url) . 'static-images/button1.png'; ?>" alt="Read Me" style="max-width:100%; height:auto;"></a>
            <a href="<?php echo esc_url($adm_url) . 'coffee-dropship-how-this-works'; ?>">
            <img src="<?php echo esc_url($plu_url) . 'static-images/button4.png'; ?>" alt="How This Works" style="max-width:100%; height:auto;"></a>
            <img src="<?php echo esc_url($plu_url) . 'static-images/button2a.png'; ?>" alt="Logo Upload" style="max-width:100%; height:auto;">
            <a href="<?php echo esc_url($adm_url) . 'coffee-dropship-send-logo'; ?>">
            <img src="<?php echo esc_url($plu_url) . 'static-images/button3.png'; ?>" alt="Logo Send" style="max-width:100%; height:auto;"></a>
            <a href="<?php echo esc_url($adm_url) . 'coffee-dropship-products'; ?>">
            <img src="<?php echo esc_url($plu_url) . 'static-images/button5.png'; ?>" alt="Manage Products" style="max-width:100%; height:auto;"></a>
            
            <h1>Upload Your Logo - Automatically placed on every coffee bag.</h1>
            <p>Example: Your logo will be on products like this:<br><img align="left" src="<?php echo esc_url($plu_url) . 'static-images/sample1.png'; ?>" alt="Logo Placement" style="max-width:100%; height:auto;"></p>
            <ol><li>Select the Browse button and choose the .jpg or .png image file to upload. WHITE BACKGROUND recommended.</li>
                <li>Select the <strong>Upload Logo</strong> button and wait for the images to complete.</li>
                <li>If you are unhappy with the result you can scroll down and Reset the images to start over.</li>
                <li>Recommended logo canvas size 1083 pixels wide x 876 pixels height. Need square or round? Scroll down for Tips.</li>
                <li>Avoid excessive whitespace around your logo image (the more whitespace, the smaller your logo).</li>
                <li>Scroll down for tips to get the perfect look and learn about sizing your images.</li></ol>
            <h3>Important: Do not upload a full label here, this is for your logo on our free label images only. Upgrade coming soon for full labels.</h3>
            <?php
            if (isset($_GET['success']) && $_GET['success'] == 1): 
                $random = wp_rand(10, 99); // Append a random number to bypass cache in case they just uploaded a new logo
            ?>
            <div class="updated notice">
            <h2>Your coffee bag images have been saved to this plugin with your logo - not live yet.
            <br>Below are 3 image previews of your logo.  If you are happy with how your logo looks, you are almost done.
            <br>If you need to replace logo/image, scroll down to image reset to erase your logo and upload a new image.
            <br>The Next Step, if not done already, is to select the <b>SEND YOUR LOGO FOR ORDERS</b> button.</h2>
            <br><br>
            <img src="<?php echo esc_url($plu_url) . 'img/best-coffee-brand-image13.jpg?v=' . esc_attr($random); ?>" alt="Your Single Cups Product" style="max-width:25%; height:auto;">
            <img src="<?php echo esc_url($plu_url) . 'img/best-coffee-brand-image5.jpg?v=' . esc_attr($random); ?>" alt="Your Cold Brew Product" style="max-width:25%; height:auto;">
            <img src="<?php echo esc_url($plu_url) . 'img/best-coffee-brand-image8.jpg?v=' . esc_attr($random); ?>" alt="Your Coffee Product" style="max-width:25%; height:auto;">
            </div>
            <?php endif;
               
            if (extension_loaded('gd')) {
            // GD is available for image processing
            echo 'Good news, your server supports image processing, you should have no issues with the upload';
                } else {
                // GD is not available, display message
                    echo "The GD library may be missing from your system, which processes images. If logo does not appear on images start a support request for guidance.";
                }
                ?>
            <form action="admin-post.php" method="post" enctype="multipart/form-data">
                <?php wp_nonce_field('brandabean_process_logo_upload', 'brandabean_process_logo_nonce'); ?>
                <input type="hidden" name="action" value="brandabean_process_logo_upload">
                <input type="file" name="logo_file" accept="image/*" required>
                <input type="submit" value="Upload Logo"> <-- Already Uploaded logo?  Scroll down to reset before uploading again.
            </form>
            <img src="<?php echo esc_url($plu_url) . 'static-images/reset.png'; ?>" alt="Reset Images" style="max-width:100%; height:auto;">
            <h2>Reset Images To Update or Replace Your Logo</h2>
            <h3>This will erase your logo from every product image in this plugin.  Do the reset if you are changing your logo.</h3>
            <div><p>A Reset removes your logo if you need to start over or want to update your logo.<br>If you have already uploaded
            a logo image and upload another without doing a reset your newer image will be on top of your older image.<br>  Doing a reset removes
            any uploaded logo so you can replace or start over.</p></div>
            
            <form action="admin-post.php" method="post">
                <?php wp_nonce_field('brandabean_reset_images', 'brandabean_reset_images_nonce'); ?>
                <input type="hidden" name="action" value="brandabean_reset_images">
                <input type="submit" value="Reset to Default Product Images" onclick="return confirm('Are you sure you want to reset all product images in this plugin? Only do this if you are uploading a new logo image.');">
            </form>

            <?php if (isset($_GET['success']) && $_GET['success'] == 2): ?>
            <div class="updated notice"><h2>Reset Complete. Please proceed to upload your new logo or image.</h2>
                <br><br><img src="<?php echo esc_url($plu_url) . 'img/best-coffee-brand-image9.jpg' ?>" alt="Your Reset Product" style="max-width:10%; height:auto;">
                </div>
            <?php endif; ?>
        </div>
        <hr><hr>
        <?php 
        // Show design tips
        include_once (plugin_dir_path(__FILE__) . 'incs/tips.php');
        $tips_displayed = false; // Initialize a variable
        wp_create_nonce('tip');
        if (isset($_POST['brandabean_tips'])) {
            if (!isset($_POST['tip']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['tip'])))) {
        brandabean_display_tips();
        $tips_displayed = true; // Set the variable to true after displaying tips
    }
}
?>

<button id="brandabean-tips">Show Me Tips and Tricks For Logo Image Uploads</button>

<?php
brandabean_display_tips(); // Include the tips div
    }
// functions to process logo or image upload size and placement

    public function brandabean_process_logo_upload() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized');
        }

        if (!isset($_FILES['logo_file'])) {
            wp_die('No file uploaded.');
        }
        
        // Verify Nonce or stop upload
        if (!isset($_POST['brandabean_process_logo_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['brandabean_process_logo_nonce'])), 'brandabean_process_logo_upload')) {
            echo '<p style="color: red;">Security check failed on upload.</p>';
            return;
        }

        $file = sanitize_mime_type($_FILES['logo_file']);
        $file_type = wp_check_filetype($file['name']);

        if (!in_array($file_type['type'], array('image/jpeg', 'image/png'))) {
            wp_die('Invalid file type. Must be .jpg or .png');
        }

        $uploaded_file = wp_handle_upload($file, array('test_form' => false));
        if (isset($uploaded_file['error'])) {
            wp_die('Upload error: ' . esc_html($uploaded_file['error']));
        }

        $logo_path = $uploaded_file['file'];
        $this->brandabean_apply_logo_to_images($logo_path);
        
        wp_safe_redirect(admin_url('admin.php?page=brandabean-coffee-dropship_menu&success=1'));
        exit;
    }

    private function brandabean_apply_logo_to_images($logo_path) {
        $product_images = array();
        for ($i = 1; $i <= 14; $i++) {
            $product_images[] = "best-coffee-brand-image$i.jpg";
        }

        foreach ($product_images as $image_name) {
            $product_image_path = $this->image_dir . $image_name;
            if (file_exists($product_image_path)) {
                $this->brandabean_overlay_logo($product_image_path, $logo_path);
                gc_collect_cycles(); // Free up memory after processing each image
            }
        }
    }
    //get the image size
    private function brandabean_overlay_logo($product_image_path, $logo_path) {
    $product_image_info = getimagesize($product_image_path);
    $logo_image_info = getimagesize($logo_path);

    if ($product_image_info['mime'] == 'image/jpeg') {
        $product_image = @imagecreatefromjpeg($product_image_path);
    } elseif ($product_image_info['mime'] == 'image/png') {
        $product_image = @imagecreatefrompng($product_image_path);
    } else {
        wp_die('Unsupported product image type: ' . esc_html($product_image_info['mime']));
        return;
    }

    if (!$product_image) {
        wp_die('Failed to create product image from: ' . esc_html($product_image_path));
        return;
    }

    if ($logo_image_info['mime'] == 'image/jpeg') {
        $logo_image = @imagecreatefromjpeg($logo_path);
    } elseif ($logo_image_info['mime'] == 'image/png') {
        $logo_image = @imagecreatefrompng($logo_path);
    } else {
        wp_die('Unsupported logo image type: ' . esc_html($logo_image_info['mime']));
        imagedestroy($product_image);
        return;
    }

    if (!$logo_image) {
        wp_die('Failed to create logo image from: ' . esc_html($logo_path));
        imagedestroy($product_image);
        return;
    }

        // Resize logo
        $resized_logo = imagescale($logo_image, 260, 210);

        // Apply transparency if png had it
        imagealphablending($resized_logo, true);
        imagesavealpha($resized_logo, true);

        // Positioning
        $x = 275;
        $y = 263;

        imagecopy($product_image, $resized_logo, $x, $y, 0, 0, 260, 210);
        if ($product_image_info['mime'] === 'image/png') {
        imagepng($product_image, $product_image_path);
        } else {
        imagejpeg($product_image, $product_image_path, 100);
        }
        // all done - perform garbage collection
        imagedestroy($product_image);
        imagedestroy($resized_logo);
        
    }
    //function to start over with logo image overlay reset
    public function brandabean_reset_images() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized');
        }
        
        // Verify Nonce or stop reset images post
        if (!isset($_POST['brandabean_reset_images_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['brandabean_reset_images_nonce'])), 'brandabean_reset_images')) {
            echo '<p style="color: red;">Security check failed at reset.</p>';
            return;
        }

        $product_images = array();
        for ($i = 1; $i <= 14; $i++) {
            $product_images[] = "best-coffee-brand-image$i.jpg";
        }

        foreach ($product_images as $image_name) {
            $reset_image_path = $this->reset_dir . $image_name;
            $target_image_path = $this->image_dir . $image_name;
            if (file_exists($reset_image_path)) {
                copy($reset_image_path, $target_image_path);
            }
        }

        wp_safe_redirect(admin_url('admin.php?page=brandabean-coffee-dropship_menu&success=2'));
        exit;
    }
}

new Brandabean_Logo_Overlay();

//enqueue scripts
function brandabean_assets($hook) {
    $plugin_url = plugin_dir_url(__FILE__);

    // Define allowed hooks with notes
    $allowed_hooks = array(
        'toplevel_page_brandabean-coffee-dropship_menu',
        'brand-a-bean_page_coffee-dropship-send-logo',
        'brand-a-bean_page_coffee-dropship-products',
    );

    // Check if we're on a known page
    if (!in_array($hook, $allowed_hooks)) {
        return; // Exit early if not a relevant page
    }

    // Enqueue jQuery just in case wp did not already
    wp_enqueue_script('jquery');

    // Enqueue brandabean.js only on pages where it is used
    if (
        $hook === 'toplevel_page_brandabean-coffee-dropship_menu' ||
        $hook === 'brand-a-bean_page_coffee-dropship-send-logo'
    ) {
        wp_enqueue_script(
            'brandabean-admin-js',
            $plugin_url . 'js/brandabean.js',
            array('jquery'),
            '1.0.0',
            true
        );
    }

    // Enqueue brandabean-publish.js only on the products page
    if ($hook === 'brand-a-bean_page_coffee-dropship-products') {
        wp_enqueue_script(
            'brandabean-admin-publish',
            $plugin_url . 'js/brandabean-publish.js',
            array('jquery'),
            '1.0.0',
            true
        );
    }
}
add_action('admin_enqueue_scripts', 'brandabean_assets');
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
        );
    }
});
?>