<?php

/**
 * @since 2.0.0
 * @package B1_Accounting
 * @subpackage B1_Accounting/includes
 * @author Site.pro <apskaita@site.pro>
 * @link https://www.site.pro
 */
class B1_Accounting_Shop_Item
{

    public static function set_null_reference_id_product()
    {
        global $wpdb;
        $postsTable = "{$wpdb->prefix}posts";
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $wpdb->query(
            $wpdb->prepare(
                "UPDATE %i SET `b1_reference_id` = NULL WHERE `post_type` = %s OR `post_type` = %s",
                $postsTable, 'product','product_variation')
        );
    }

    public static function get_items_sku()
    {
        global $wpdb;
        $postsMetaTableName = "{$wpdb->prefix}postmeta";
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM %i WHERE `meta_key` = %s",
            $postsMetaTableName,'_sku'));

    }

    /**
     * @param int $b1_item_id
     * @param string $code
     * @param null $quantity
     * @param string $price
     * @param null $name
     */
    public static function update_data_using_b1_item_id($b1_item_id, $code, $quantity = null, $price = null, $name = null)
    {
        /**
         * Filter whether a shop item is allowed to be updated from B1 Accounting.
         *
         * Return false to prevent the item from being updated.
         *
         * @since 2.2.69
         *
         * @param bool   $allowed    Whether the item update is allowed. Default true.
         * @param int    $b1_item_id The B1 item ID.
         * @param string $code       The product SKU / code.
         */
        if ( ! apply_filters( 'b1_accounting_allow_item_update', true, $b1_item_id, $code ) ) {
            return;
        }

        $id = wc_get_product_id_by_sku($code);
        if ($id) {
            global $wpdb;
            $postsTableName = "{$wpdb->prefix}posts";
            $postsMetaTableName = "{$wpdb->prefix}postmeta";
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $wpdb->query(
                $wpdb->prepare(
                    "UPDATE %i p
       LEFT JOIN %i pm ON pm.post_id = p.ID
       SET `b1_reference_id` = %d
       WHERE `meta_key` = %s AND `meta_value` = %s",
                    $postsTableName, $postsMetaTableName, $b1_item_id, '_sku', $code)
            );

            if (!is_null($quantity )){
                if ($quantity >= 1) {
                    update_post_meta($id, '_stock', $quantity);
                    update_post_meta($id, '_stock_status', 'instock');
                } else if ($quantity == 0) {
                    // Don't change status if item in backorder
                    $currentStockStatus = get_post_meta($id, '_stock_status', true);
                    if($currentStockStatus != 'onbackorder') {
                        update_post_meta($id, '_stock', $quantity);
                        update_post_meta($id, '_stock_status', 'outofstock');
                    }

                    $product = wc_get_product($id);
                    if($product->backorders_allowed()) { // if allow backorders
                        update_post_meta($id, '_stock', $quantity);
                        update_post_meta($id, '_stock_status', 'onbackorder');
                    }
                }
            }

            if ($price) {
                update_post_meta($id, '_price', (float)$price);
                update_post_meta($id, '_regular_price', (float)$price);
            }
            if ($name) {
                wp_update_post([
                    'ID' => $id,
                    'post_title' => $name,
                ]);
            }
        }
    }

    /**
     * @param string $itemId
     * @param int $b1_item_id
     */
    public static function update_code_using_item_id($b1_item_id, $itemId)
    {
        global $wpdb;
        $postsTableName = "{$wpdb->prefix}posts";
        $postsMetaTableName = "{$wpdb->prefix}postmeta";
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $wpdb->query(
            $wpdb->prepare(
                "UPDATE %i p
        LEFT JOIN %i pm ON pm.post_id = p.ID
        SET b1_reference_id = %d
        WHERE p.id = %d or pm.post_id = %d",
                $postsTableName, $postsMetaTableName, $b1_item_id, (integer)$itemId, (integer)$itemId)
        );
    }

    /**
     * @param int $quantity
     * @param int $b1_item_id
     */
    public static function update_quantity_using_b1_item_id($quantity, $b1_item_id)
    {
        /**
         * Filter whether a shop item is allowed to be updated from B1 Accounting.
         *
         * Return false to prevent the item from being updated.
         *
         * @since 2.2.69
         *
         * @param bool   $allowed    Whether the item update is allowed. Default true.
         * @param int    $b1_item_id The B1 item ID.
         * @param string $code       The product SKU / code. Empty when updating by B1 item ID only.
         */
        if ( ! apply_filters( 'b1_accounting_allow_item_update', true, $b1_item_id, '' ) ) {
            return;
        }

        global $wpdb;
        $postsTableName = "{$wpdb->prefix}posts";
        $postsMetaTableName = "{$wpdb->prefix}postmeta";

        if (is_null($quantity)) $quantity = 0;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $wpdb->get_results(
            $wpdb->prepare(
                "UPDATE %i 
        LEFT JOIN %i ON post_id = ID
        SET `meta_value` = %d
        WHERE `meta_key` = %s AND `b1_reference_id` = %d",
                $postsMetaTableName, $postsTableName, $quantity, '_stock', $b1_item_id)
        );
    }

    /**
     * @param int $post_id
     *
     * @return int
     */
    public static function get_b1_item_id($post_id)
    {
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $data = $wpdb->get_var(
            $wpdb->prepare("SELECT b1_product_id FROM {$wpdb->prefix}b1_item_links WHERE `shop_product_id` = %d", $post_id)
        );
        if ($data === null) {
            return 0;
        } else {
            return intval($data);
        }
    }

    public static function get_product_reference_id($product_id)
    {
        global $wpdb;
        $postsTableName = "{$wpdb->prefix}posts";
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        return $wpdb->get_var(
            $wpdb->prepare("SELECT b1_reference_id FROM %i WHERE `ID` = %d", $postsTableName, $product_id)
        );
    }

    public static function get_variation_reference_id($variationId)
    {
        global $wpdb;
        $postsTableName = "{$wpdb->prefix}posts";
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        return $wpdb->get_var(
            $wpdb->prepare("SELECT b1_reference_id FROM %i WHERE `ID` = %d", $postsTableName, $variationId)
        );
    }

    public static function fetch_all_items($iteration)
    {
        global $wpdb;
        $postsTableName = "{$wpdb->prefix}posts";
        $postsMetaTableName = "{$wpdb->prefix}postmeta";
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        return $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * 
                FROM %i p
                LEFT JOIN %i pm ON pm.post_id = p.ID
                WHERE b1_reference_id IS NULL AND `meta_key` = %s AND `meta_value` is not null AND `meta_value` != '' LIMIT %d ",
                $postsTableName, $postsMetaTableName, '_sku', $iteration)
        );
    }

    public static function fetch_all_items_without_sku()
    {
        global $wpdb;
        $postsTableName = "{$wpdb->prefix}posts";
        $postsMetaTableName = "{$wpdb->prefix}postmeta";
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        return $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * 
                FROM %i p
                WHERE b1_reference_id IS NULL and (`post_type` = %s OR `post_type` = %s)
                AND p.ID not in (SELECT p1.ID 
                FROM %i p1
                LEFT JOIN %i pm ON pm.post_id = p1.ID
                WHERE p1.b1_reference_id IS NULL AND pm.`meta_key` = %s AND pm.`meta_value` is not null AND pm.`meta_value` != '')",
                $postsTableName, $postsTableName, $postsMetaTableName, 'product','product_variation','_sku')
        );
    }

    public static function get_data_by_sql($sql, $itemId)
    {
        if (isset($sql) && !empty($sql)) {
            global $wpdb;
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            return $wpdb->get_var($wpdb->prepare($sql, $itemId));
        } else {
            return false;
        }
    }

}
