<?php

declare(strict_types=1);

namespace common\models;

use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;

/**
 * CustomerPlan ActiveRecord — links a customer to a plan with subscription tracking.
 *
 * @property int         $id
 * @property int         $customer_id
 * @property int         $plan_id
 * @property string      $start_date
 * @property string|null $end_date
 * @property string      $status  active|expired|cancelled
 * @property int         $created_at
 * @property int         $updated_at
 *
 * @property Customer    $customer
 * @property Plan        $plan
 * @property Invoice[]   $invoices
 */
class CustomerPlan extends ActiveRecord
{
    public const STATUS_ACTIVE    = 'active';
    public const STATUS_EXPIRED   = 'expired';
    public const STATUS_CANCELLED = 'cancelled';

    public static function tableName(): string
    {
        return '{{%customer_plans}}';
    }

    public function behaviors(): array
    {
        return [
            TimestampBehavior::class,
        ];
    }

    public function rules(): array
    {
        return [
            [['customer_id', 'plan_id', 'start_date'], 'required'],
            [['customer_id', 'plan_id'], 'integer'],
            [['start_date', 'end_date'], 'date', 'format' => 'php:Y-m-d'],
            [['status'], 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_EXPIRED, self::STATUS_CANCELLED]],
            [['status'], 'default', 'value' => self::STATUS_ACTIVE],
            [['customer_id'], 'exist', 'targetClass' => Customer::class, 'targetAttribute' => ['customer_id' => 'id']],
            [['plan_id'], 'exist', 'targetClass' => Plan::class, 'targetAttribute' => ['plan_id' => 'id']],
        ];
    }

    public function attributeLabels(): array
    {
        return [
            'id'          => 'ID',
            'customer_id' => 'Customer',
            'plan_id'     => 'Plan',
            'start_date'  => 'Start Date',
            'end_date'    => 'End Date',
            'status'      => 'Status',
            'created_at'  => 'Created At',
        ];
    }

    public function getCustomer(): \yii\db\ActiveQuery
    {
        return $this->hasOne(Customer::class, ['id' => 'customer_id']);
    }

    public function getPlan(): \yii\db\ActiveQuery
    {
        return $this->hasOne(Plan::class, ['id' => 'plan_id']);
    }

    public function getInvoices(): \yii\db\ActiveQuery
    {
        return $this->hasMany(Invoice::class, ['customer_plan_id' => 'id']);
    }

    public function isExpired(): bool
    {
        if ($this->end_date === null) {
            return false;
        }
        return strtotime($this->end_date) < time();
    }
}
