<?php

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class MDSPBE_Atum_Stock_Manager {

    function __construct() {
        add_filter( 'mdspbe_transalated_strings', [ $this, 'transalated_strings' ] );
        add_action( 'mdspbe_before_bulk_actions', [ $this, 'add_supplier_hidden_field' ] );
        add_action( 'mdspbe_bulk_actions', [ $this, 'bulk_actions' ] );
        add_action( 'mdspbe_add_product_filter', [ $this, 'add_product_filter' ] );
        add_filter( 'mdspbe_product_filter_args', [ $this, 'product_filter_args'] );
        add_filter( 'mdspbe_product_query_args', [ $this, 'product_query_args' ], 9999 );
        add_filter( 'mdspbe_filter_product_query', [ $this, 'filter_product_query' ], 9999 );
        add_filter( 'mdspbe_product_attributes', [ $this, 'product_attributes' ] );
        add_filter( 'mdspbe_get_product_function_name', [ $this, 'get_product_function_name' ] );
    }


    public function transalated_strings( $translated_strings ) {

        $atum_translated_strings = [
            'purchaseOrder' => __( 'Purchase order',  'mds-product-bulk-editor-for-woocommerce' ),
            'createPurchaseOrder' => __( 'Create purchase order',  'mds-product-bulk-editor-for-woocommerce' ),
            'addToPurchaseOrder' => __( 'Add to purchase order',  'mds-product-bulk-editor-for-woocommerce' ),
            'description' => __( 'Description',  'mds-product-bulk-editor-for-woocommerce' ),
            'expectedDate' => __( 'Expected date',  'mds-product-bulk-editor-for-woocommerce' ),
            'description' => __( 'Description',  'mds-product-bulk-editor-for-woocommerce' ),
            'poCreatedSuccesfully' => __( 'Purchase order created successfully',  'mds-product-bulk-editor-for-woocommerce' ),
            'poUpdatedSuccesfully' => __( 'Purchase order updated successfully',  'mds-product-bulk-editor-for-woocommerce' ),
            'viewPurchaseOrder' => __( 'View purchase order',  'mds-product-bulk-editor-for-woocommerce' ),
            'errorCreatingPO' => __( 'Error creating purchase order',  'mds-product-bulk-editor-for-woocommerce' ),
            'noProductSelected' => __( 'No product selected',  'mds-product-bulk-editor-for-woocommerce' ),
            'poStatus' => __( 'Status',  'mds-product-bulk-editor-for-woocommerce' ),
            'pending' => __( 'Pending',  'mds-product-bulk-editor-for-woocommerce' ),
            'ordered' => __( 'Ordered',  'mds-product-bulk-editor-for-woocommerce' ),
            'onthewayin' => __( 'On the way in',  'mds-product-bulk-editor-for-woocommerce' ),
            'receiving' => __( 'Receiving',  'mds-product-bulk-editor-for-woocommerce' ),
            'received' => __( 'Received',  'mds-product-bulk-editor-for-woocommerce' ),
            'multipleSuppliers' => __( 'Multiple suppliers',  'mds-product-bulk-editor-for-woocommerce' ),
        ];

        $translated_strings = array_merge( $translated_strings, $atum_translated_strings );
        return $translated_strings;
    }


    // This is used to create single or multisupplier purchase orders
    public function add_supplier_hidden_field() {
        $supplier_id = isset( $_GET['supplier_id'] ) ? sanitize_text_field( wp_unslash( $_GET['supplier_id'] ) ) : '';
        if ( $supplier_id ) {
            ?>
            <input type="hidden" id="atum_supplier_id" value="<?php echo esc_attr( $supplier_id ) ?>">
            <?php
        }
    }


    public function bulk_actions() {
        ?>
            <option value="atum-create-po"><?php esc_html_e( 'Create purchase order', 'mds-product-bulk-editor-for-woocommerce' ) ?></option>
            <option value="atum-update-po"><?php esc_html_e( 'Add to purchase order', 'mds-product-bulk-editor-for-woocommerce' ) ?></option>
        <?php
    }


    public function add_product_filter( $args) {
        ?>
        <div class="form-floating">
            <select class="form-select" name="supplier_id" id="atum-supplier" title="<?php esc_html_e( 'Supplier', 'mds-product-bulk-editor-for-woocommerce' ) ?>">
                <option value=""><?php esc_html_e( 'All', 'mds-product-bulk-editor-for-woocommerce' ) ?></option>
                <?php 
                    $suppliers = mdspbe_atum_list_suppliers( false, false );
                    foreach ( $suppliers as $supplier_id => $supplier_name ) {
                        ?><option value="<?php echo esc_attr( $supplier_id ) ?>" <?php echo selected( $supplier_id, $args['supplier_id'], false ) ?>><?php echo esc_html( $supplier_name ) ?></option><?php
                    }
                ?>
            </select>
            <label for="atum-supplier"><?php esc_html_e( 'Supplier', 'mds-product-bulk-editor-for-woocommerce' ) ?></label>
        </div>
        <?php
    }


    public function product_filter_args( $args ) {

        $supplier_id = isset( $_GET['supplier_id'] ) ? sanitize_text_field( wp_unslash( $_GET['supplier_id'] ) ) : '';
        $args['supplier_id'] = $supplier_id;

        if ( $supplier_id ) {
            // Because supplier_id is stored in a custom table, we need an extra query to fetch the products that belongs to this supplier
            $product_ids = $this->wc_get_product_ids_by_supplier( $supplier_id, ['limit' => $args['limit'], 'page' => $args['page'] ?? 1] );
            $args['include'] = $product_ids;
        }

        return $args;
    }


    public function product_query_args( $query_args ) {
        // Return IDs instead of Objects so we can get the ATUM object instead of the WC one
        $query_args['return'] = 'ids';

        return $query_args;
    }


    protected function wc_get_product_ids_by_supplier( $supplier_id, $extra_args = [] ) {
        global $wpdb;

        $product_ids = $wpdb->get_col(
            $wpdb->prepare(
                "SELECT product_id
                FROM {$wpdb->prefix}atum_product_data
                WHERE supplier_id = %d",
                $supplier_id
            )
        );

        return $product_ids;
    }


    public function filter_product_query( $products_ids ) {
        $atum_products = array_map( [Atum\Inc\Helpers::class, 'get_atum_product'], $products_ids );
        return $atum_products;
    }


    public function product_attributes( $attributes ) {

        $atum_attributes = [];
        foreach ( $attributes as $key => $attribute ) {
            
            if ( $key === 'regular_price' ) {

                $atum_attributes['purchase_price'] = [
                    'id' => 'purchase_price',
                    'name' => __( 'Purchase price', 'mds-product-bulk-editor-for-woocommerce' ),
                    'description' => __( 'The amount you paid to acquire or produce the product, often used for cost tracking and profit margin calculations', 'mds-product-bulk-editor-for-woocommerce' ),
                    'allow_edit' => true,
                    'get' => 'get_purchase_price',
                    'set' => 'set_purchase_price',
                    'type' => 'input_number',
                    'step' => '0.01',
                    'required' => false,
                    'allowed_types' => ['simple', 'variation'],
                    'style' => ['min-width' => '100px'],
                    'sanitize' => 'mdspbe_floatval',
                ];
            }
            
            $atum_attributes[$key] = $attribute;

            if ( $key === 'global_unique_id' ) {

                $atum_attributes['supplier_id'] = [
                    'id' => 'supplier_id',
                    'name' => __( 'Supplier', 'mds-product-bulk-editor-for-woocommerce' ),
                    'description' => __( 'The vendor or source from which the product is obtained, useful for managing supply chain and purchase orders', 'mds-product-bulk-editor-for-woocommerce' ),
                    'allow_edit' => true,
                    'get' => 'get_supplier_id',
                    'set' => 'set_supplier_id',
                    'accept_empty_value' => false,
                    'type' => 'select',
                    'required' => false,
                    'options' => 'mdspbe_atum_list_suppliers',
                    'allowed_types' => ['simple', 'variation'],
                    'sanitize' => 'mdspbe_absint',
                    'purchaseOrderKeep' => true,
                ];

                $atum_attributes['supplier_sku'] = [
                    'id' => 'supplier_sku',
                    'name' => __( 'Supplier SKU', 'mds-product-bulk-editor-for-woocommerce' ),
                    'description' => __( 'The stock keeping unit assigned by the supplier, which may differ from your own internal SKU', 'mds-product-bulk-editor-for-woocommerce' ),
                    'allow_edit' => true,
                    'get' => 'get_supplier_sku',
                    'set' => 'set_supplier_sku',
                    'accept_empty_value' => false,
                    'type' => 'input_text',
                    'required' => false,
                    'allowed_types' => ['simple', 'variation'],
                    'sanitize' => 'sanitize_text_field',
                ];

            } elseif ( $key === 'stock_quantity' ) {

                $atum_attributes['inbound_stock'] = [
                    'id' => 'inbound_stock',
                    'name' => __( 'Inbound stock', 'mds-product-bulk-editor-for-woocommerce' ),
                    'description' => __( 'The quantity of products currently on purchase orders or expected from suppliers but not yet received into inventory', 'mds-product-bulk-editor-for-woocommerce' ),
                    'allow_edit' => false,
                    'get' => 'get_inbound_stock',
                    'allowed_types' => ['simple', 'variation'],
                    'purchaseOrderKeep' => true,
                ];

            } 
        }

        return $atum_attributes;
    }


    public function get_product_function_name() {
        return 'mdspbe_atum_get_product';
    }

}

new MDSPBE_Atum_Stock_Manager();

