<?php

namespace app\manager\model;

use think\Model;

class AgentCode extends Model
{
    protected $name = 'cursor_agent_codes';
    
    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    // 设置字段类型
    protected $type = [
        'price' => 'float',
        'commission' => 'float',
        'parent_commission' => 'float',
        'settle_time' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    // 定义卡类型配置
    public static $cardTypes = [
        1 => ['days' => 1, 'name' => '1天卡'],
        5 => ['days' => 5, 'name' => '5天卡'],
        30 => ['days' => 30, 'name' => '30天卡'],
        90 => ['days' => 90, 'name' => '三个月卡'],
        180 => ['days' => 180, 'name' => '六个月卡'],
        365 => ['days' => 365, 'name' => '一年卡'],
    ];

    // 获取所有卡类型
    public static function getCardTypes()
    {
        return self::$cardTypes;
    }

    // 获取卡类型名称
    public static function getCardTypeName($days)
    {
        return isset(self::$cardTypes[$days]) ? self::$cardTypes[$days]['name'] : "{$days}天卡";
    }

    // 获取所属代理商
    public function agent()
    {
        return $this->belongsTo('app\manager\model\Agent', 'agent_id');
    }

    // 获取激活码信息
    public function code()
    {
        return $this->belongsTo('app\manager\model\ActivationCode', 'code_id');
    }

    // 结算佣金
    public function settle()
    {
        if ($this->status == 1) {
            return false;
        }

        // 开启事务
        $this->startTrans();
        try {
            // 更新代理商余额
            $this->agent->updateBalance($this->commission);

            // 如果有上级佣金，更新上级代理商余额
            if ($this->parent_commission > 0 && $this->agent->parent) {
                $this->agent->parent->updateBalance($this->parent_commission);
            }

            // 更新结算状态
            $this->status = 1;
            $this->settle_time = date('Y-m-d H:i:s');
            $this->save();

            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->rollback();
            return false;
        }
    }
} 