<?php

namespace App\Modules\Bookings;

use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\ValidationModel;
use App\Modules\Clients\Client;
use App\Modules\Clients\Customer;
use App\Modules\Clients\Site;
use App\Modules\Clients\SiteUser;
use App\Models\User;
use App\Modules\Bookings\Task;
use App\Modules\Bookings\Comment;
use Carbon\Carbon;


class Project extends ValidationModel
{
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'description', 'status_id', 'assigned_to', 'budget', 'expenses', 'estimated_duration', 'single_invoice', 'client_id', 'client_type', 'site_id', 'site_user_id', 'planning', 'invoiced', 'paid', 'completed', 'completed_at', 'created_by', 'invoice_number'];

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'projects';

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];

    /**
     * Array of validation rules.
     *
     * @var  array
     */
    protected static $rules = [
        'name'        => 'required',
        'client_id'   => 'required',
        'client_type' => 'required|in:client,customer',
    ];

    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    public static function boot()
    {
        parent::boot();

        // Set up morphMap for polymorphic relationships
        \Illuminate\Database\Eloquent\Relations\Relation::morphMap([
            'client' => Client::class,
            'customer' => Customer::class,
        ]);

        // When a transaction is created we want to
        // update the created_by field
        static::creating(function ($model) {
            if (! $model->created_by) {
                $model->created_by = Auth::user()->id;
            }
            if (! $model->updated_by) {
                $model->updated_by = Auth::user()->id;
            }
        });

        // When a transaction gets updated we want to know who
        // updated it
        static::updating(function ($model) {
            $model->updated_by = Auth::user()->id;
            // junaid said comment this if sttement out 20.2.17
            // if (! $model->isDirty('invoiced')) {
            //     $model->invoiced = $model->invoice_number ? 1 : 0;
            // }
        });

        // Any time we save the project we check to see if the completed attribute has changed
        // and update the timestamp
        static::saving(function ($model) {
            if ($model->isDirty('completed') && $model->completed == 1) {
                $model->completed_at = date('Y-m-d H:i:s');
            }
        });
    }

    /**
     * Get the client (polymorphic relationship).
     * This can be either a Client or Customer model.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphTo
     */
    public function client()
    {
        return $this->morphTo('client', 'client_type', 'client_id');
    }

    /**
     * Returns the site model.
     *
     * @return App\Modules\Clients\Site
     */
    public function site()
    {
        return $this->belongsTo(Site::class, 'site_id');
    }

    /**
     * Returns the site user model.
     *
     * @return App\Modules\Clients\SiteUser
     */
    public function site_user()
    {
        return $this->belongsTo(SiteUser::class, 'site_user_id');
    }

    /**
     * Retrieves all the tasks associated with this project.
     *
     * @return App\Modules\Bookings\Task
     */
    public function tasks()
    {
        return $this->hasMany(Task::class, 'project_id');
    }

    /**
     * Returns the user who this project is assigned to.
     *
     * @return \User
     */
    public function assigned_to()
    {
        return $this->belongsTo(User::class, 'assigned_to');
    }

    /**
     * Returns the user who this project is assigned to.
     *
     * @return \User
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'assigned_to');
    }

    /**
     * Retrict the results to a given overdue period. Default 28 days.
     *
     * @return Query
     */
    public function scopeOverdue($query, $days = 28)
    {
        return $query->where('created_at', '<', Carbon::now()->subDays($days)->toDateTimeString());
    }

    /**
     * Returns all the comments for a particular task.
     *
     * @return App\Modules\Bookings\Comment
     */
    public function comments()
    {
        return $this->hasMany(Comment::class, 'related_id')->where('related_type', '=', 'project');
    }
}
