<?php

namespace App\Modules\User\Services;

use App\Consts\SysConsts;
use App\Modules\Subscribe\Models\Order;
use App\Modules\User\Models\UserMonthOrder;

/**
 * 包年包月用户
 * 
 * @property bool $is_monthly 是否包月用户
 * @property bool $is_annually 是否包年用户
 */
class AnnuallyMonthlyUser
{
    protected $is_monthly;
    protected $is_annually;
    private $uid;

    public function __construct(int $uid = 0)
    {
        if ($uid) {
            $this->uid = $uid;
        } else {
            $user = app()->make('user');
            $this->uid = $user->id;
        }
    }

    public function __get($property_name)
    {
        if (isset($this->$property_name)) {
            return $this->$property_name;
        } else {
            if ($property_name == "is_annually") {
                $this->setAnnuallyUser();
                return $this->is_annually;
            } else if ($property_name == "is_monthly") {
                $this->setMonthlyUser();
                return $this->is_monthly;
            }
        }
    }

    /**
     * 设置用户包年属性
     */
    private function setAnnuallyUser()
    {
        $year_order = Order::where('uid', $this->uid)->where('status', 'PAID')->where('order_type', 'YEAR')->orderBy('id', 'desc')->first();
        if ($year_order && strtotime($year_order->created_at) > (time() - SysConsts::ONE_YEAR_DAYS * SysConsts::ONE_DAY_SECONDS)) {
            $this->is_annually = true;
        } else {
            $this->is_annually = false;
        }
    }

    /**
     * 设置用户包月属性
     */
    private function setMonthlyUser()
    {
        $month_order = UserMonthOrder::where('uid', $this->uid)->where('type', 'MONTH')->orderBy('id', 'desc')->first();
        if ($month_order && strtotime($month_order->created_at) > (time() - SysConsts::ONE_YEAR_DAYS * SysConsts::ONE_DAY_SECONDS)) {
            $this->is_monthly = true;
        } else {
            $this->is_monthly = false;
        }
    }
}
