<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Store extends Model
{
    use HasFactory;

    protected $table = 'm_stores';

    protected $fillable = [
        'code',
        'store_type',
        'document_type',
        'name',
        'address',
        'pic',
        'pic_phone',
        'pic_email',
        'description',
        'bom_di',
        'bom_to',
        'status',
        'inactive_date',
        'delete_flag',
        'created_at',
        'created_by',
        'updated_at',
        'updated_by',
        'version',
    ];

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function modificator()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    public function ShipmentDeliverys()
    {
        return $this->hasMany(ShipmentDelivery::class, 'store_id');
    }

    public function targetSisaMalam()
    {
        return $this->hasMany(TargetSisaMalam::class, 'store_id');
    }

    public function stockOpnames()
    {
        return $this->hasMany(StockOpname::class, 'store_id');
    }

    public function itemRequests()
    {
        return $this->hasMany(ItemRequest::class, 'store_id');
    }

    public function forecasts()
    {
        return $this->hasMany(Forecast::class, 'store_id');
    }

    // Many-to-many relationship with raw materials
    public function rawMaterials()
    {
        return $this->belongsToMany(RawMaterial::class, 'm_store_raw_materials', 'store_id', 'raw_material_id')
            ->withPivot(['is_active', 'min_stock', 'max_stock', 'reorder_point', 'notes', 'delete_flag'])
            ->withTimestamps()
            ->wherePivot('delete_flag', 0);
    }

    // Get active raw materials for this store
    public function activeRawMaterials()
    {
        return $this->rawMaterials()->wherePivot('is_active', true);
    }

    // Direct relationship to store raw materials mapping
    public function storeRawMaterials()
    {
        return $this->hasMany(StoreRawMaterial::class, 'store_id');
    }

    /**
     * Many-to-many relationship with users
     * Store can be assigned to multiple users
     */
    public function users()
    {
        return $this->belongsToMany(User::class, 'users_stores', 'store_id', 'user_id')
            ->withTimestamps()
            ->withPivot(['created_by', 'updated_by']);
    }

    protected static function boot()
    {
        parent::boot();

        // Code is now manually entered by user (freetext, unique)
        // Auto-generate logic removed
    }
}
