<?php
namespace App\Models;

use CodeIgniter\Model;

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

    public function getProductWithVariants($id)
    {
        $db = \Config\Database::connect();
        $builder = $db->table('products p');
        $builder->select('p.id, p.name, p.image, pv.id as variant_id, pv.unit, pv.price, pv.offer_price, pv.quantity');
        $builder->join('product_variants pv','pv.product_id = p.id','left');
        $builder->where('p.id', $id);
        $query = $builder->get()->getResultArray();

        if(empty($query)) return null;

        $product = [
            'info' => [
                'id' => $query[0]['id'],
                'name' => $query[0]['name'],
                'image' => $query[0]['image']
            ],
            'variants' => []
        ];

        foreach($query as $row){
            if($row['variant_id']){
                $product['variants'][] = [
                    'variant_id' => $row['variant_id'],
                    'unit' => $row['unit'],
                    'price' => $row['price'],
                    'offer_price' => $row['offer_price'],
                    'quantity' => $row['quantity']
                ];
            }
        }

        return $product;
    }
    
    
}
