<?php /** @noinspection ALL */

namespace App;

use App\Opt\CompanyTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class Company extends Model
{
    use SoftDeletes;

    protected $fillable =
        [
            'name',
            'user_id',
            'company_status_id',
            'business_logo',
            'date_of_incorporation' ,
            'legal_status' ,
            'nature_of_business' ,
            'location_in_other_countries' ,
            'postal_address' ,
            'physical_address' ,
            'company_phone_number' ,
            'business_document' ,
            'sender_id_document' ,
            'contact_person' ,
            'contact_person_designation' ,
            'contact_person_phone' ,
            'contact_person_email',
            'contact_person_id',
            'mobile_money_number',
            'client_type',
            'contract_status',
            'paid_initial_debit',
            'business_banner'
        ];

    public function users(){

        return $this->belongsTo(User::class,'user_id');

    }

    public function trial()
    {
        return $this->hasOne(CompanyTrialMode::class);
    }

    public function putToTrialMode(array $data)
    {
        $array['company_id'] = $this->id;
        $array['trial'] = true;
        CompanyTrialMode::query()->updateOrCreate($array);
    }


    public function email()
    {
        return $this->belongsTo(CompanyEmail::class);
    }

    public function directors()
    {
        return $this->hasMany(CompanyDirector::class);
    }

    public function company_status()
    {
        return $this->belongsTo(CompanyStatus::class);
    }


    public function company_statuses()
    {
        return $this->belongsTo(CompanyStatus::class);
    }

    public function status()
    {
        return $this->has(CompanyStatus::class);
    }


    public function canPost()
    {
        $default = false;
        $now = Carbon::parse(now());
        $trial  = $this->trial()->where('trial',1)->first(); // if the user is on trial mode
        $daily  = $this->users->posts()->whereDate('created_at',$now)->first();   //if the user has made a daily post on free account
        $expiry = $this->users->social_subscription()->where('is_paid',1)->first();   //if the user has paid

        if($trial && !$daily)    //if the user is on trial account hasn't done any post yet
            $default  = true;

        if($trial && Carbon::parse($trial->created_at)->addDays(7) > now())   //if the user is on trial and trial period has not expired
            $default  = true;

        if(!empty($expiry) && Carbon::parse($expiry->expires_on) > now()) //if the person has made a monthly payment and the payment has not expired yet
            $default  = true;

        return $default;
    }
}
