<?php

namespace iwbvel\classes\services\product_update\variation_handlers;

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

use iwbvel\classes\repositories\History;
use iwbvel\classes\services\product_update\Variation_Update_Handler;

class Default_Attributes_Handler extends Variation_Update_Handler
{
    private $is_processing;

    public function is_processing()
    {
        return $this->is_processing;
    }

    public function update($product_ids, $update_data)
    {
        if (empty($update_data['value']['attributes'])) {
            return false;
        }

        foreach ($product_ids as $product_id) {
            $product = wc_get_product(intval($product_id));
            if (!($product instanceof \WC_Product_Variable)) {
                continue;
            }

            $prev_value['attributes'] = $product->get_default_attributes();
            $product->set_default_attributes($update_data['value']['attributes']);
            $product->save();

            if (!empty($update_data['history_id'])) {
                $history_repository = History::get_instance();
                $result = $history_repository->save_history_item([
                    'history_id' => intval($update_data['history_id']),
                    'historiable_id' => intval($product->get_id()),
                    'name' => 'default_variation',
                    'sub_name' => '',
                    'type' => 'variation',
                    'action' => 'default_attributes',
                    'prev_value' =>  $prev_value,
                    'new_value' => $update_data['value'],
                    'prev_total_count' => 1,
                    'new_total_count' => 1,
                ]);

                if (!$result) {
                    return false;
                }
            }
        }

        return true;
    }
}
