<?php

namespace App\Listeners\Ecommerce\Category;

use Illuminate\Support\Facades\DB;

class UpdateCategoryProductsPriceByTax
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(object $event): void
    {
        $category = $event->category;

        // Since category could have millions of products, we chunk queries for memory efficiency
        $category->products()->chunkById(20, function ($products) {
            $products->each(function ($product) {
                // Remember, product prict_amount must be calculated by highest related category tax,
                // there is chance updated category may not have the biggest tax,
                // so we have check all products related categories
                $cost = $product->cost_amount;
                $tax = DB::table('categories')
                    ->whereIntegerInRaw('id', $product->categories()->pluck('id'))
                    ->select(DB::raw('MAX(tax_percentage::integer) as tax'))
                    ->pluck('tax')[0];

                $product->update(['price_amount' => round_up(($cost / (100 - $tax)) * 100)]);
            });
        });
    }
}
