<?php

namespace app\models;

use yii\db\ActiveRecord;

/**
 * Model for lms_tenant
 *
 * @property int    $id
 * @property string $tenant_name
 * @property string $tenant_phone
 * @property string $tenant_email
 * @property string $tenant_addess
 * @property string $tenant_logo
 * @property string $tenant_logo_name
 * @property string $tenant_notes
 * @property string $isActive
 * @property int    $created_by
 * @property string $created_date_time
 * @property int    $updated_by
 * @property string $updated_date_time
 *
 * @property User   $createdBy
 * @property User   $updatedBy
 */
class Tenant extends ActiveRecord
{
    /** Virtual attribute — holds the uploaded file instance */
    public $logoFile = null;

    const UPLOAD_PATH  = '@webroot/uploads/tenants/';
    const UPLOAD_URL   = '@web/uploads/tenants/';

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

    public function rules(): array
    {
        return [
            [['tenant_name'],           'required'],
            [['tenant_phone', 'tenant_email', 'tenant_addess', 'tenant_notes'], 'safe'],
            [['tenant_name'],            'string', 'max' => 255],
            [['tenant_phone'],           'string', 'max' => 100],
            [['tenant_email'],           'string', 'max' => 100],
            [['tenant_email'],           'email'],
            [['tenant_logo'],            'string', 'max' => 100],
            [['tenant_logo_name'],       'string', 'max' => 255],
            [['isActive'],               'in', 'range' => ['Y', 'N']],
            [['created_by', 'updated_by'], 'integer'],
            [['logoFile'],               'file',
                'skipOnEmpty'  => true,
                'extensions'   => 'png,jpg,jpeg,gif,svg,webp',
                'maxSize'      => 2 * 1024 * 1024,
                'tooBig'       => 'Logo must be smaller than 2 MB.',
                'wrongExtension' => 'Only PNG, JPG, GIF, SVG and WEBP files are allowed.',
            ],
        ];
    }

    public function attributeLabels(): array
    {
        return [
            'id'                  => 'ID',
            'tenant_name'         => 'Tenant Name',
            'tenant_phone'        => 'Phone',
            'tenant_email'        => 'Email',
            'tenant_addess'       => 'Address',
            'tenant_logo'         => 'Logo',
            'tenant_logo_name'    => 'Logo Display Name',
            'tenant_notes'        => 'Notes',
            'isActive'            => 'Status',
            'created_by'          => 'Created By',
            'created_date_time'   => 'Created At',
            'updated_by'          => 'Updated By',
            'updated_date_time'   => 'Updated At',
            'logoFile'            => 'Upload Logo',
        ];
    }

    /**
     * Uploads the logo file and updates tenant_logo / tenant_logo_name.
     * Returns true if no file was submitted (skipped) or upload succeeded.
     */
    public function uploadLogo(): bool
    {
        if ($this->logoFile === null) {
            return true;
        }

        $filename = 'tenant_' . $this->id . '_' . time() . '.' . $this->logoFile->extension;
        $path     = \Yii::getAlias(self::UPLOAD_PATH) . $filename;

        if (!$this->logoFile->saveAs($path)) {
            $this->addError('logoFile', 'Failed to save the uploaded file.');
            return false;
        }

        // Remove old logo file if it exists and differs
        if ($this->tenant_logo && $this->tenant_logo !== $filename) {
            $old = \Yii::getAlias(self::UPLOAD_PATH) . $this->tenant_logo;
            if (is_file($old)) {
                @unlink($old);
            }
        }

        $this->tenant_logo      = $filename;
        $this->tenant_logo_name = $this->logoFile->baseName . '.' . $this->logoFile->extension;

        return true;
    }

    /** Returns the public URL to the logo, or null if none. */
    public function getLogoUrl(): ?string
    {
        if (!$this->tenant_logo) {
            return null;
        }
        return \Yii::getAlias(self::UPLOAD_URL) . $this->tenant_logo;
    }

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

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