<?php
if ( ! defined( 'ABSPATH' ) ) exit;

use Anbarak\Tables;

/**
 * Save product row
 */
function anbarak_product_save()
{
    try {

        check_ajax_referer('anbarak-ajax-nonce', 'security');

        anbarak_require_ajax_admin_access();

        global $wpdb;
        $product_id  = isset($_POST['pid']) ? (int) sanitize_text_field(wp_unslash($_POST['pid'])) : 0;
        $price       = anbarak_sanitize_price(isset($_POST['price']) ? sanitize_text_field(wp_unslash($_POST['price'])) : '');
        $sale_price  = anbarak_sanitize_price(isset($_POST['sale_price']) ? sanitize_text_field(wp_unslash($_POST['sale_price'])) : '');
        $stockChange       = isset($_POST['stock_change']) ? (int) sanitize_text_field(wp_unslash($_POST['stock_change'])) : 0;
        $backorders  = isset($_POST['backorders']) ? sanitize_text_field(wp_unslash($_POST['backorders'])) : '';
        $online_sell = isset($_POST['online_sell']) ? sanitize_text_field(wp_unslash($_POST['online_sell'])) : null;
        $sku = isset($_POST['sku']) ? sanitize_text_field(wp_unslash($_POST['sku'])) : '';


        if (!$product_id) return;

        $product = wc_get_product($product_id);

        if (isset($sku)) {
            if ($product->is_type('variation')) {
                $productParent = wc_get_product($product->get_parent_id());
                if ($sku != $productParent->get_sku()) {
                    $product->set_sku($sku);
                } else {
                    $product->set_sku(null);
                }
            } else {
                $product->set_sku($sku);
            }
        }

        $weight = isset($_POST['weight']) ? sanitize_text_field(wp_unslash($_POST['weight'])) : null;
        if ($weight !== null) {
            $product->set_weight($weight);
        }

        $product->set_regular_price($price ?? '');
        $product->set_price($price ?? '');

        if ($sale_price) {
            $product->set_sale_price($sale_price);
        } else {
            $product->set_sale_price('');
        }

        if (isset($backorders)) {
            $product->set_backorders($backorders);
        }

        if (null !== $online_sell) {
            if ('0' == $online_sell) {
                $product->update_meta_data('_anbarak_no_online_sell', 'yes');
            } else {
                $product->delete_meta_data('_anbarak_no_online_sell');
            }
        }

        if ($stockChange != 0) {
            $current_stock = $product->get_stock_quantity();
            $new_stock = $current_stock + $stockChange;
            
            if ($new_stock < 0 && 'no' === $backorders) {
                throw new Exception(__('Stock cannot be negative when backorders are disabled', 'anbarak'));
            }
            
            $product->set_stock_quantity($new_stock);
            
            if ($new_stock > 0) {
                $product->set_stock_status('instock');
            } elseif ($new_stock <= 0 && 'no' === $backorders) {
                $product->set_stock_status('outofstock');
            } else {
                $product->set_stock_status($new_stock > 0 ? 'instock' : 'onbackorder');
            }
        }

        $product->save();

        $final_stock_qty = $product->get_stock_quantity();
        
        $posted_buy_price = isset($_POST['buy_price']) ? sanitize_text_field(wp_unslash($_POST['buy_price'])) : '';
        if ('' !== $posted_buy_price) {
            $buy_price = anbarak_sanitize_price(isset($_POST['buy_price']) ? sanitize_text_field(wp_unslash($_POST['buy_price'])) : '');
            $purchase_tag_id = anbarak_get_purchase_tag_id();
            $expenses_table = $wpdb->prefix . Tables::EXPENSES;
            
            $total_price = $final_stock_qty * $buy_price;

            // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Custom table name is fixed from $wpdb->prefix and Tables.
            $existing = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM {$expenses_table}
                 WHERE product_id = %d
                   AND tag_id = %d
                   AND deleted_at IS NULL
                 LIMIT 1",
                $product_id,
                $purchase_tag_id
            ));
            // phpcs:enable

            if ($existing) {
                $wpdb->update(
                    $expenses_table,
                    [
                        'price' => $total_price,
                        'qty' => $final_stock_qty,
                        'consumed_qty' => $final_stock_qty,
                        'timestamp' => time()
                    ],
                    ['id' => $existing],
                    ['%f', '%d', '%d', '%d'],
                    ['%d']
                );
            } else {
                $wpdb->insert(
                    $expenses_table,
                    [
                        'product_id'   => $product_id,
                        'price'        => $total_price,
                        'qty'          => $final_stock_qty,
                        'consumed_qty' => $final_stock_qty,
                        'tag_id'       => $purchase_tag_id,
                        'notes'        => sprintf(/* translators: 1: product ID, 2: total cost */ __('Manual buy price set for product #%1$d. Total cost: %2$s', 'anbarak'), $product_id, $total_price),
                        'timestamp'    => time(),
                    ]
                );
            }
        }

        wp_send_json([
            'qty' => $final_stock_qty !== null ? (int)$final_stock_qty : 0,
            'stock_change_applied' => $stockChange,
            'total_expense_price' => isset($buy_price) ? ($final_stock_qty * $buy_price) : null
        ]);
    } catch (Exception $e) {
        wp_send_json_error($e->getMessage(), 400);
    }
}
add_action('wp_ajax_anbarak_product_save', 'anbarak_product_save');
