<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\User;
use App\Models\Reply;
use App\Models\Department;


class Ticket extends Model
{
    protected $fillable = ['user_id', 'department_id', 'subject', 'message'];


    /**
     *
     * Ticket belongs to the user
     * @return App\Models\User
     *
     */
    public  function user()
    {
        return $this->belongsTo(User::class);
    }


    /**
     *
     * Ticket has many replies
     * @return App\Models\Reply
     *
     */
    public function replies()
    {
        return $this->hasMany(Reply::class);
    }



    /**
     *
     * Ticket belongs to the department
     * @return App\Models\Department
     *
     */
    public function department()
    {
        return $this->belongsTo(Department::class);
    }


    /**
     *
     * Get the department name
     * @return App\Models\Department
     * 
     *
     */
    public function getDepartment(  )
    {   
        $department =  $this->attributes['department_id'];

        if( $department ) {
            return $this->department->name;
        } else {
            return 'No department.';
        }
    }

    /**
     *
     * Format the subject
     * @return string
     *
     */
    public function FormatSubject(  )
    {   
        $value =  $this->attributes['subject'];
        return str_replace(' ', '-', $value);
    }


    /**
     *
     * Reformat the subject
     * @param $subject
     * @return string
     *
     */
    public static function reformatTicket( $subject )
    {   
        return str_replace('-', ' ', $subject);
    }



    /**
     *
     * Get the assigned user
     * @return App\Models\User
     *
     */
    public function getAssignedStaff()
    {
        $assigned_to = $this->attributes['assigned_to'];

        if( $assigned_to == 0) {
            return 'Not assigned yet.';
        } else {
            $user = User::find($assigned_to);

            if( $user ) {
                return $user->fullName() ;
            }
        }
    }

    /**
     *
     * Get the assigned user
     * @return App\Models\User
     *
     */
    public function getSolvedBy()
    {
        $solved_by = $this->attributes['solved_by'];

        if( $solved_by == 0) {
            return 'Not solved yet.';
        } else {
            $user = User::find($solved_by);

            if( $user ) {
                return $user->fullName();
            }
        }
    }


}
