<?php

namespace App\Models;

use CodeIgniter\Model;

class ProductInModel extends Model
{
    protected $table = 'product_in';
    protected $primaryKey = 'id';
    protected $allowedFields = [
        'kode', 'item_id', 'barcode', 'supplier_id', 'id_gudang', 'qty', 'tanggal_masuk', 'created_by'
    ];
    protected $useTimestamps = false;

    // Ambil semua data dengan join ke item, supplier, gudang
    public function getJoinAll()
{
    return $this->db->table('product_in')
        ->select('product_in.*, items.nama as item_name, items.harga, suppliers.nama as nama_supplier, gudang.nama as nama_gudang, users.username as user_name')
        ->join('items', 'items.id = product_in.item_id', 'left')
        ->join('suppliers', 'suppliers.id = product_in.supplier_id', 'left')
        ->join('gudang', 'gudang.id = product_in.id_gudang', 'left')
        ->join('users', 'users.id = product_in.created_by', 'left')
        ->orderBy('product_in.tanggal_masuk', 'DESC')
        ->get()
        ->getResultArray();
}


    // Ambil data berdasarkan ID
    public function getById($id)
    {
        return $this->where('id', $id)->first();
    }

    // Tambah data dengan kode otomatis
    public function insertWithCode($data)
    {
        $date = date('dmY');
        $prefix = 'INV-' . $date . '-';
        $latest = $this->where('DATE(tanggal_masuk)', date('Y-m-d'))
                       ->orderBy('id', 'DESC')->first();
        $lastNumber = $latest ? (int) substr($latest['kode'], -3) : 0;
        $data['kode'] = $prefix . str_pad($lastNumber + 1, 3, '0', STR_PAD_LEFT);
        return $this->insert($data);
    }



    // Ambil satu data stok masuk untuk detail view
    public function getJoinById($id)
    {
        return $this->db->table($this->table . ' sm')
            ->select('sm.*, i.nama as nama, i.harga, s.nama as supplier, s.email, g.nama as gudang')
            ->join('items i', 'i.id = sm.item_id', 'left')
            ->join('suppliers s', 's.id = sm.supplier_id', 'left')
            ->join('gudang g', 'g.id = sm.id_gudang', 'left')
            ->where('sm.id', $id)
            ->get()
            ->getRowArray();
    }
}
