<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;

    protected $table = 'products';
    // ถ้าใช้ primary key ชื่อ id อยู่แล้ว ไม่ต้องกำหนดก็ได้
    // protected $primaryKey = 'id';
    // public $incrementing = true;

    protected $fillable = [
        'name','model','log_receive_method','product_type','description','image',
        'Customer_ID','Agency_ID','CusIns_ID','CusUdp_ID','DtmIns','DtmUpd',
    ];

    // ให้ Eloquent รู้ว่าคอลัมน์เวลาชื่ออะไร
    const CREATED_AT = 'DtmIns';
    const UPDATED_AT = 'DtmUpd';

    // แปลงวันที่เป็น Carbon อัตโนมัติ
    protected $casts = [
        'DtmIns' => 'datetime',
        'DtmUpd' => 'datetime',
    ];

    /**
     * เติมค่าบังคับก่อน create หาก caller ไม่ได้ส่งมา
     */
    protected static function booted()
    {
        static::creating(function (Product $product) {
            $cid = session('Customer_ID')
                ?? session('customer_id')
                ?? optional(auth()->user())->Customer_ID;

            $aid = session('selected_agency_id')
                ?? optional(auth()->user())->Agency_ID;

            if (empty($product->Customer_ID)) $product->Customer_ID = $cid;
            if (empty($product->CusIns_ID))   $product->CusIns_ID   = $cid;
            if (empty($product->CusUdp_ID))   $product->CusUdp_ID   = $cid;
            if (empty($product->Agency_ID) && !empty($aid)) $product->Agency_ID = $aid;

            if (empty($product->DtmIns)) $product->DtmIns = now();
            if (empty($product->DtmUpd)) $product->DtmUpd = now();
        });
    }

    /* ---------------- Relationships ---------------- */

    // ผู้สร้างสินค้า (ตาราง customers, คีย์ Customer_ID)
    public function user()
    {
        return $this->belongsTo(Customer::class, 'Customer_ID', 'Customer_ID');
    }

    public function agency()
    {
        return $this->belongsTo(Agency::class, 'Agency_ID', 'Agency_ID');
    }

    public function assessments()
    {
        // ระบุ foreign key ให้ชัด (ปกติคือ product_id)
        return $this->hasMany(Assessment::class, 'product_id', 'id');
    }

    /* ---------------- Accessors (labels) ---------------- */

    public function getProductTypeLabelAttribute()
    {
        return match ($this->product_type) {
            'hw_sw_log_server' => 'Hardware + Software Log Server',
            'sw_log_server'    => 'Software Log Server',
            default            => $this->product_type,
        };
    }

    public function getLogReceiveMethodLabelAttribute()
    {
        return match ($this->log_receive_method) {
            'syslog_udp'  => 'syslog UDP',
            'syslog_tcp'  => 'syslog TCP',
            'syslog_both' => 'syslog UDP และ syslog TCP',
            'other'       => 'อื่นๆ',
            default       => $this->log_receive_method,
        };
    }
}
