<?php

namespace SoftminalB2B\Models;

if (!defined('ABSPATH')) {
    exit;
}

/**
 * A buyer's saved order template (FEATURES F1 — reorder).
 *
 * Items are a JSON snapshot of lines the buyer curated in the bulk order form:
 * `[{product_id, variation_id, quantity}, ...]`. A list is always read and
 * written whole, so the lines live in one JSON column rather than a child
 * table. No price is stored — reorder re-prices live through the Resolver.
 *
 * @property int|null $id
 * @property int      $user_id
 * @property int|null $company_id NULL = personal; set = shared with that company
 * @property string   $name
 * @property array    $items
 */
class PurchaseList extends Model
{
    protected $table = 'purchase_lists';
    protected $timestamps = true;

    protected $fillable = [
        'user_id',
        'company_id',
        'name',
        'items',
    ];

    protected $casts = [
        'items' => 'json',
    ];

    /**
     * Normalise raw client lines to the stored shape: positive integers only,
     * de-duplicated by product+variation (last quantity wins), invalid lines
     * dropped. Keeps junk out of the table regardless of what the request sent.
     *
     * @param mixed $raw
     * @return array<int, array{product_id:int, variation_id:int, quantity:int}>
     */
    public static function normalizeItems($raw): array
    {
        if (!is_array($raw)) {
            return [];
        }

        $byKey = [];

        foreach ($raw as $line) {
            if (!is_array($line)) {
                continue;
            }

            $productId   = isset($line['product_id']) ? absint($line['product_id']) : 0;
            $variationId = isset($line['variation_id']) ? absint($line['variation_id']) : 0;
            $quantity    = isset($line['quantity']) ? absint($line['quantity']) : 0;

            if ($productId <= 0 || $quantity <= 0) {
                continue;
            }

            $byKey[$productId . ':' . $variationId] = [
                'product_id'   => $productId,
                'variation_id' => $variationId,
                'quantity'     => $quantity,
            ];
        }

        return array_values($byKey);
    }
}
