<?php

namespace Mehrab\OrderService\Models;

use Carbon\Carbon;
use Hekmatinasser\Verta\Verta;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\URL;
use Mamad\Transaction\Models\Transaction;
use Mehrab\Comment\Models\CommentService;
use Mehrab\Media\Models\Media;
use Mehrab\Media\Services\MediaFileService;
use Mehrab\Payment\Models\Payment;
use Mehrab\Region\Models\Region;
use Mehrab\Service\Models\Service;
use Mehrab\User\Models\User;

class OrderService extends Model
{
    use HasFactory;

    const DONE = 'done';
    const DONE_AND_WAITING_FEEDBACK_FOR_EXPERT = 'done and waiting feedback for expert';
    const DOING = 'doing';
    const CANCELED = 'canceled';
    const PENDING_OPERATOR = 'operator';
    const PENDING_TEAM_LEADER = 'team_leader';
    const PENDING_EXPERT = 'expert';
    const ACCEPT_EXPERT = 'accept_expert';
    const CHECK_FACTOR = 'check_factor';
    const SUSPENDED = 'Suspended'; //تعلیق کار : یعنی درخواست لغو فعال داره
    const WAITING_PAYMENT = 'waiting payment'; //فاکتور صادر شده و منتظر پرداخت مشتری

    public static $status = [
        self::DONE,
        self::CANCELED,
        self::PENDING_EXPERT,
        self::PENDING_OPERATOR,
        self::PENDING_TEAM_LEADER,
        self::SUSPENDED,
        self::ACCEPT_EXPERT,
        self::WAITING_PAYMENT,
        self::CHECK_FACTOR,
        self::DOING
    ];

    protected $table = 'orderservices';

    protected $casts = [
        'reports' => 'json',
        'answers' => 'json',
        'meta' => 'json',
        'time_todo' => 'datetime',
    ];

    protected $fillable = [
        'code',
        'meta',
        'answers',
        'time_todo',
        'status',
        'reports',
        'user_id',
        'service_id',
        'region_id',
        'media_id',
        'operator_id',
        'expert_id',
        'team_leader_id',
        'price'
    ];

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

    public function service()
    {
        return $this->belongsTo(Service::class, 'service_id');
    }
    public function transaction()
    {
        return $this->morphMany(Transaction::class,"transactionable");
    }
    public function region()
    {
        return $this->belongsTo(Region::class, 'region_id')->with('city');
    }

    public function media()
    {
        return $this->belongsTo(Media::class, 'media_id');
    }

    public function operator()
    {
        return $this->belongsTo(User::class, 'operator_id');
    }

    public function team_leader()
    {
        return $this->belongsTo(User::class, 'team_leader_id');
    }

    public function expert()
    {
        return $this->belongsTo(User::class, 'expert_id');
    }

    public function cancel_order()
    {
        return $this->hasMany(CancelOrdersService::class, 'orderServices_id');
    }

    public function getCreatedAtAttribute()
    {
        return verta($this->attributes['created_at'])->format('H:i Y-n-j');
    }

    public function getTimeTodoAttribute()
    {
        return verta($this->attributes['time_todo'])->format('H:i Y-n-j');
    }

    public function scopeTimeAccess24HourAgo($query)
    {
        $query->where('time_todo', '<', Carbon::now()->addHour('24'));
    }

    public function getCheckInQueueTeamLeader()
    {
        return Carbon::now()->addHour('24')->greaterThan($this->attributes['time_todo']);
    }

    public function scopeTimeAccess24HourLater($query)
    {
        $query->where('time_todo', '>', Carbon::now()->addHour('-24'));
    }

    public function getTimeToDoStatus()
    {
        return Carbon::now()->addHour('-24')->greaterThan($this->attributes['time_todo']) &&
        $this->status != self::DOING &&
        $this->status != self::DONE &&
        $this->status != self::DONE_AND_WAITING_FEEDBACK_FOR_EXPERT &&
        $this->status != self::WAITING_PAYMENT &&
        $this->status != self::CHECK_FACTOR
            ? 'expired' : null;
    }

    public function payments()
    {
        return $this->morphMany(Payment::class, 'paymentable');
    }

    public function service_comment()
    {
        return $this->hasMany(CommentService::class, 'order_id');
    }

    public function downloadLink()
    {
        return URL::temporarySignedRoute('media.download.order', now()->addDays(15), ['media' => $this->media, 'order' => $this]);
    }


    public function checkboxAnswers()
    {
        $checkbox = [];
        foreach ($this->answers as $key => $ans) {
            if (is_array($ans)) {
                $checkbox[$key] = $ans;
            }
        }
        return $checkbox;
    }

    public function radioAnswers()
    {
        $radio = [];
        foreach ($this->answers as $key => $ans) {
            if (!is_array($ans)) {
                $radio[$key] = $ans;
            }
        }
        return $radio;
    }

    public function check_access()
    {
        if ($this->operator()->exists()) {
            if ($this->operator->id == auth()->id()) {
                return true;
            }
        }
        if ($this->expert()->exists()) {
            if ($this->expert->id == auth()->id()) {
                return true;
            }
        }
        if ($this->team_leader()->exists()) {
            if ($this->team_leader->id == auth()->id()) {
                return true;
            }
        }

        return false;
    }

    public function getPrice()
    {
        return $this->price == null || $this->price == 0 ? 'توافقی' : $this->price;
    }

    public function getStatusForShowUsers()
    {
        $status = $this->status;
        switch ($status) {
            case self::DONE_AND_WAITING_FEEDBACK_FOR_EXPERT:
            case self::DONE :
                return '<span class="done">اتمام</span>';
            case self::WAITING_PAYMENT :
                return '<span class="payment">در انتظار پرداخت</span>';
            case self::SUSPENDED :
                return '<span class="suspended">تعلیق</span>';
            case self::CANCELED :
                return '<span class="cancel">لغو شده</span>';
            default :
                return '<span class="done">ثبت شده</span>';
        }
    }

    public function getCanCashPayment()
    {
        $seller_percent = $this->expert->percent;
        $expert_Share = ($this->price / 100) * $seller_percent;
        $site_Share = ($this->price) - $expert_Share;
        //todo set min expert account wallet config
        if (($this->expert->amount - $site_Share) <= -20000) {
            return false;
        }
        return true;
    }

    public function getCanUserCancelOrder()
    {
        if (in_array($this->status, [self::PENDING_OPERATOR,self::PENDING_TEAM_LEADER,self::PENDING_EXPERT,self::ACCEPT_EXPERT]))return true;

        return false;
    }

    public function scopeCanUserCancelOrder($query){
        return $query->whereIn('status',[self::PENDING_OPERATOR,self::PENDING_TEAM_LEADER,self::PENDING_EXPERT,self::ACCEPT_EXPERT]);
    }


}
