<?php

namespace app\models;

use Yii;
use yii\db\ActiveRecord;

/**
 * Model for lms_course
 *
 * @property int    $id
 * @property int    $tenant_id
 * @property string $course_name
 * @property string $leads_by
 * @property string $start_date
 * @property string $end_date
 * @property string $notes
 * @property string $course_banners
 * @property string $isActive
 * @property string $banner_one
 * @property string $banner_two
 * @property int    $created_by
 * @property string $created_date_time
 * @property int    $updated_by
 * @property string $updated_date_time
 *
 * @property Tenant $tenant
 * @property User   $createdBy
 * @property User   $updatedBy
 */
class Course extends ActiveRecord
{
    /** Virtual file upload properties */
    public $courseBannersFile = null;
    public $bannerOneFile     = null;
    public $bannerTwoFile     = null;

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

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

    public function rules(): array
    {
        return [
            [['tenant_id', 'course_name'],   'required'],
            [['tenant_id', 'created_by', 'updated_by'], 'integer'],
            [['course_name', 'leads_by'],    'string', 'max' => 255],
            [['course_banners'],             'string', 'max' => 200],
            [['banner_one', 'banner_two'],   'string', 'max' => 256],
            [['notes'],                      'string'],
            [['start_date', 'end_date'],     'date', 'format' => 'php:Y-m-d'],
            [['end_date'],                   'compare', 'compareAttribute' => 'start_date',
                'operator' => '>=', 'type' => 'date',
                'message'  => 'End date must be on or after start date.',
                'skipOnEmpty' => true,
            ],
            [['isActive'],                   'in', 'range' => ['Y', 'N']],
            [['leads_by', 'notes', 'start_date', 'end_date', 'isActive'], 'safe'],

            [['courseBannersFile'], 'file', 'skipOnEmpty' => true,
                'extensions' => 'png,jpg,jpeg,gif,webp', 'maxSize' => 5 * 1024 * 1024,
                'tooBig' => 'File must be smaller than 5 MB.',
                'wrongExtension' => 'Only PNG, JPG, GIF and WEBP allowed.',
            ],
            [['bannerOneFile'], 'file', 'skipOnEmpty' => true,
                'extensions' => 'png,jpg,jpeg,gif,webp', 'maxSize' => 5 * 1024 * 1024,
                'tooBig' => 'File must be smaller than 5 MB.',
                'wrongExtension' => 'Only PNG, JPG, GIF and WEBP allowed.',
            ],
            [['bannerTwoFile'], 'file', 'skipOnEmpty' => true,
                'extensions' => 'png,jpg,jpeg,gif,webp', 'maxSize' => 5 * 1024 * 1024,
                'tooBig' => 'File must be smaller than 5 MB.',
                'wrongExtension' => 'Only PNG, JPG, GIF and WEBP allowed.',
            ],
        ];
    }

    public function attributeLabels(): array
    {
        return [
            'id'                 => 'ID',
            'tenant_id'          => 'Tenant',
            'course_name'        => 'Course Name',
            'leads_by'           => 'Leads By',
            'start_date'         => 'Start Date',
            'end_date'           => 'End Date',
            'notes'              => 'Notes',
            'course_banners'     => 'Course Banner',
            'isActive'           => 'Status',
            'banner_one'         => 'Banner 1',
            'banner_two'         => 'Banner 2',
            'created_by'         => 'Created By',
            'created_date_time'  => 'Created On',
            'updated_by'         => 'Updated By',
            'updated_date_time'  => 'Updated At',
            'courseBannersFile'  => 'Course Banner Image',
            'bannerOneFile'      => 'Banner 1 Image',
            'bannerTwoFile'      => 'Banner 2 Image',
        ];
    }

    /**
     * Upload a single file, delete old file if replaced.
     * $attribute   = DB column name (stores filename)
     * $fileAttr    = virtual property holding UploadedFile
     * $prefix      = filename prefix
     */
    public function uploadFile(string $attribute, string $fileAttr, string $prefix): bool
    {
        $file = $this->$fileAttr;
        if ($file === null || !($file instanceof \yii\web\UploadedFile)) {
            return true;
        }

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

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

        // Delete old file
        if ($this->$attribute) {
            $old = Yii::getAlias(self::UPLOAD_PATH) . $this->$attribute;
            if (is_file($old)) {
                @unlink($old);
            }
        }

        $this->$attribute = $filename;
        return true;
    }

    public function getFileUrl(string $attribute): ?string
    {
        if (!$this->$attribute) {
            return null;
        }
        return Yii::getAlias(self::UPLOAD_URL) . $this->$attribute;
    }

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

    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']);
    }
}
