<?php

namespace App\Models;

use CodeIgniter\Model;

class StockTransferLineModel extends Model
{
    protected $table         = 'stock_transfer_lines';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = false;
    protected $allowedFields = [
        'stock_transfer_id', 'product_id', 'quantity', 'notes', 'sort_order', 'created_at',
    ];

    public function getForTransfer(int $transferId): array
    {
        return $this->select('stock_transfer_lines.*, products.name AS product_name, products.sku')
            ->join('products', 'products.id = stock_transfer_lines.product_id', 'left')
            ->where('stock_transfer_id', $transferId)
            ->orderBy('sort_order', 'ASC')
            ->orderBy('id', 'ASC')
            ->findAll();
    }

    public function replaceLines(int $transferId, array $lines): void
    {
        $this->where('stock_transfer_id', $transferId)->delete();

        $sort = 0;
        foreach ($lines as $line) {
            $productId = (int) ($line['product_id'] ?? 0);
            $qty       = (float) ($line['quantity'] ?? 0);
            if ($productId <= 0 || $qty <= 0) {
                continue;
            }

            $this->insert([
                'stock_transfer_id' => $transferId,
                'product_id'        => $productId,
                'quantity'          => $qty,
                'notes'             => trim($line['notes'] ?? '') ?: null,
                'sort_order'        => $sort++,
                'created_at'        => date('Y-m-d H:i:s'),
            ]);
        }
    }
}
