<?php
namespace App\Models;

use CodeIgniter\Model;

class ProductModel extends Model
{
    protected $table = 'products';
    protected $primaryKey = 'id';
    protected $allowedFields = ['category_id', 'name', 'image', 'created_at'];

    public function insertProductWithVariants($productData, $variants)
    {
        $db = \Config\Database::connect();
        $db->transStart(); // start transaction

        $productId = $this->insert($productData);

        if($variants && $productId){
            foreach($variants as $v){
                $db->table('product_variants')->insert([
                    'product_id' => $productId,
                    'sku_name'   => $v['sku_name'],
                    'unit'       => $v['unit'],
                    'price'      => $v['price'],
                    'offer_price'=> $v['offer_price'],
                    'quantity'   => $v['quantity']
                ]);
            }
        }

        $db->transComplete();
        return $productId;
    }
}
