<?php

/**
 * The admin order specific functionality of the plugin.
 *
 * @link       https://wpconfiguratorbuilder.com/
 * @since      1.0.0
 *
 * @package    wcb-configurator-builder
 * @subpackage wcb-configurator-builder/admin
 */

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

/**
 * The admin order specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    wcb-configurator-builder
 * @subpackage wcb-configurator-builder/admin
 * @author     WPCB <support@wpconfiguratorbuilder.com>
 */
class WPCB_Admin_Order {

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string $plugin_name       The name of this plugin.
	 * @param      string $version    The version of this plugin.
	 */
	public function __construct() {
		// Add custom order action button
		add_action( 'woocommerce_admin_order_item_headers', array( $this, 'action_woocommerce_admin_order_item_headers' ), 10, 1 );
		add_action( 'woocommerce_admin_order_item_values', array( $this, 'action_woocommerce_admin_order_item_values' ), 10, 3 );

		add_action( 'admin_init', array( $this, 'generate_order_zip_file' ), 999 );
	}

	/**
	 * Registers the WooCommerce order table column
	 *
	 * @since    1.0.0
	 */
	public function action_woocommerce_admin_order_item_headers( $order ) {
		// Set the column name
		$column_name = __( 'WCB actions', 'wcb-configurator-builder' );
		echo '<th>' . esc_attr( $column_name ) . '</th>';
	}

	/**
	 * Displays the table column button
	 *
	 * @since    1.0.0
	 */
	public function action_woocommerce_admin_order_item_values( $product, $item, $item_id ) {
		if ( ! $item || ! method_exists( $item, 'is_type' ) ) {
			return;
		}
		if ( ! $item->is_type('line_item') ) { 
			return;
		}

		$value = $item->get_meta( '_wpcb_product_image' );
		if ( ! empty( $value ) ) {
			$id = sanitize_key( $_GET['id'] );
			echo '<td><a href="' . esc_url( admin_url( 'admin.php?page=wc-orders&action=edit&id='. $id . '&item=' . $item_id ) ) . '" target="_blank" class="button">' . esc_attr__( 'Get print files', 'wcb-configurator-builder' ) . '</a></td>';
		} else {
			echo '<td></td>';
		}
	}

	/**
	 * Handles the table column button action
	 *
	 * @since    1.0.0
	 */
	public function generate_order_zip_file( $order_item ) {
		if ( ! is_admin() || defined( 'DOING_AUTOSAVE' ) ) {
			return;
		}
		if ( ! isset( $_GET['item'] ) || ! isset( $_GET['id'] ) ) {
			return;
		}
		if ( ! isset( $_GET['page'] ) || 'wc-orders' !== $_GET['page'] ) {
			return;
		}

		$order_id = sanitize_key( $_GET['id'] );
		$order_item_id = sanitize_key( $_GET['item'] );

		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			return;
		}

		foreach ( $order->get_items() as $item_id => $order_item ) {
			if ( $order_item_id == $item_id ) {
				break;
			}
		}

		$file_links = wpcb_get_order_item_file_urls( $order_item );

		$product = $order_item->get_product();
		$value = $order_item->get_meta( '_wpcb_product_image' );
		$value_ext = explode('.', $value);
		$file_links[] = [
			'name' => $product->get_title() . '.' . $value_ext[ count( $value_ext ) - 1 ],
			'url' => $value
		];

		$save_path = wpcb_get_configuration_save_dir();
		$zip_dir = trailingslashit( $save_path['path'] ) . $product->get_title() . '.zip';
		$zipfile = new ZipArchive();
		if ( $zipfile->open( $zip_dir, ZIPARCHIVE::CREATE ) !== true ) {
			return false;
		}

		foreach ( $file_links as $index => $link ) {
			$file_path = str_replace( $save_path['url'], $save_path['path'], $link['url'] );
			$zipfile->addFile( $file_path, $link['name'] );
		}
		$zipfile->close();

		$dir_name = basename( $zip_dir );
		header('Content-type: application/zip');  
		header('Content-Disposition: attachment; filename="' . $dir_name . '"');  
		readfile($zip_dir); // auto download
		unlink($zip_dir);
		exit; // cleanup
	}
}
