<?php

namespace ZenoChatbot\Model;

use ZenoChatbot\Framework\Database\Model;

/**
 * Customer Model
 *
 * Represents chat customers (both WordPress users and guests)
 */
class Customer extends Model
{
    /**
     * Table name
     */
    protected $table = 'zenochatbot_customers';

    /**
     * Primary key
     */
    protected $primaryKey = 'id';

    /**
     * Fillable attributes
     */
    protected $fillable = [
        'name',
        'email',
        'user_id'
    ];

    /**
     * Attributes that should be cast
     */
    protected $casts = [
        'id'         => 'int',
        'user_id'    => 'int',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];


    /**
     * Get the WordPress user associated with this customer
     * Application-side relationship
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get conversations for this customer
     * Application-side relationship
     */
    public function conversations()
    {
        return $this->hasMany(Conversation::class, 'customer_id');
    }

    /**
     * Get customer by user ID
     *
     * @param int $user_id
     * @return Customer|null
     */
    public static function findByUserId($user_id)
    {
        return static::where('user_id', $user_id)->first();
    }

    /**
     * Create customer from WordPress user
     *
     * @param int $user_id
     * @return Customer
     */
    public static function createFromUser($user_id)
    {
        $user = get_userdata($user_id);

        return static::create([
            'name' => $user->display_name ?: $user->user_login,
            'email' => $user->user_email,
            'user_id' => $user_id
        ]);
    }

    /**
     * Get or create customer for authenticated user
     *
     * @param int $user_id
     * @return Customer
     */
    public static function getOrCreateForUser($user_id)
    {
        $customer = static::findByUserId($user_id);

        if (!$customer) {
            $customer = static::createFromUser($user_id);
        }

        return $customer;
    }

    /**
     * Get active conversation for this customer
     */
    public function activeConversation()
    {
        return $this->conversations()
                   ->where('ended_at', null)
                   ->orderBy('started_at', 'desc')
                   ->first();
    }
}
