<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

class Ticket extends Model implements HasMedia
{
    use InteractsWithMedia;

    protected $guarded = [];

    public function department()
    {
        return $this->belongsTo(Department::class);
    }

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

    public function replies()
    {
        return $this->hasMany(Reply::class)->latest();
    }

    public static function generateTrackCode()
    {
        do {
            $code = rand(10000000, 99999999);
        } while (static::where('track_id', $code)->exists());

        return $code;
    }

    public function isReplied()
    {
        if (!$this->replies()->where('is_private', false)->get()->isEmpty()) {
            return true;
        }
        return false;
    }

    public function isRead()
    {
        if ($this->status == 'read') {
            return true;
        }
        return false;
    }

    public function isUnread()
    {
        if ($this->status == 'unread') {
            return true;
        }
        return false;
    }

    public function isClosed()
    {
        if ($this->closed_at) {
            return true;
        }
        return false;
    }

    public static function countAll()
    {
        if (auth()->user()->isAdmin()) {
            return static::count();
        } elseif (auth()->user()->isStaff()) {
            return static::whereIn('department_id', auth()->user()->department()->pluck('id')->toArray())->count();
        }
        return false;
    }

    public static function countUnread()
    {
        if (auth()->user()->isAdmin()) {
            return static::where('status', 'unread')->whereNull('closed_at')->count();
        } elseif (auth()->user()->isStaff()) {
            return static::whereIn('department_id', auth()->user()->department()->pluck('id')->toArray())->where('status', 'unread')->count();
        }
        return false;
    }

    public static function countRead()
    {
        return static::where('status', 'read')->whereNull('closed_at')->count();
    }

    public static function countReplied()
    {
        return static::where('status', 'replied')->whereNull('closed_at')->count();
    }

    public static function countClosed()
    {
        return static::whereNotNull('closed_at')->count();
    }

    public function reports()
    {
        return $this->hasMany(Report::class);
    }
}
