<?php

namespace App\Models;

use App\Models\Pop;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class NewLineRequest extends Model
{
    use HasFactory;

    public function pop()
    {
        return $this->belongsTo(Pop::class, 'pop_id');
    }

    public function package()
    {
        return $this->belongsTo(Packages::class, 'package_id');
    }

    public function subPackage()
    {
        return $this->belongsTo(SubPackage::class, 'sub_package_id');
    }

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

    public function remarksList()
    {
        return $this->hasMany(NewLineRequestRemarks::class, 'new_line_request_id');
    }

    public function ClientSource()
    {
        return $this->belongsTo(ClientSource::class, 'source_id');
    }

    public function marketingStatus()
    {
        return $this->belongsTo(MarketingDone::class, 'marketing_status_id');
    }

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

    public function smartDevices()
    {
        return $this->hasMany(NewLineRequestSmartDevice::class, 'new_line_request_id');
    }

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

    public function cancelReasons()
    {
        return $this->hasMany(NewLineRequestMarketinCancelReason::class, 'new_line_request_id');
    }
    public function surveyCancelReason()
    {
        return $this->hasMany(NewLineRequestSurveyCancelReason::class, 'new_line_request_id');
    }

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

    public function lineManager()
    {
        return $this->belongsTo(\App\Models\Employee::class, 'line_manager_id');
    }

    public function client()
    {
        return $this->belongsTo(Client::class, 'client_id');
    }

    public function newLineToken()
    {
        return $this->hasOne(Token::class, 'clientId', 'client_id')->where('tokenCategory', 2)->where('tokenCode', 58);
    }

    public function marketingEmployee()
    {
        return $this->belongsTo(\App\Models\Employee::class, 'marketing_user_id');
    }

    public function editLogs()
    {
        return $this->hasMany(LogHistory::class, 'log_id', 'id')
            ->where('log_type', 'new_line_request_update');
    }

    // Add this separate relation for eager loading latest only
    public function latestEditLog()
    {
        return $this->hasOne(LogHistory::class, 'log_id', 'id')
            ->where('log_type', 'new_line_request_update')
            ->latestOfMany('id');
    }

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