<?php

namespace app\models;

use Yii;
use yii\db\ActiveRecord;

/**
 * Model for lms_mas_assessment
 *
 * @property int    $id
 * @property int    $course_id
 * @property string $assessment_name
 * @property string $filename
 * @property string $instruction
 * @property int    $number_of_question
 * @property string $pass_percentage
 * @property int    $mark_per_question
 * @property string $created_datetime
 * @property int    $created_by
 * @property string $update_date_time
 * @property int    $updated_by
 * @property string $isActive
 *
 * @property Course $course
 */
class MasAssessment extends ActiveRecord
{
    /** Virtual file upload property */
    public $instructionFile = null;

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

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

    public function rules(): array
    {
        return [
            [['course_id', 'assessment_name', 'instruction'], 'required'],
            [['course_id', 'number_of_question', 'mark_per_question', 'created_by', 'updated_by'], 'integer'],
            [['number_of_question', 'mark_per_question'], 'integer', 'min' => 0],
            [['pass_percentage'], 'number', 'min' => 0, 'max' => 100],
            [['assessment_name'], 'string', 'max' => 64],
            [['filename', 'instruction'], 'string'],
            [['isActive'], 'in', 'range' => ['Y', 'N']],
            [['isActive', 'filename', 'number_of_question', 'mark_per_question', 'pass_percentage'], 'safe'],

            [['instructionFile'], 'file', 'skipOnEmpty' => true,
                'extensions' => 'pdf',
                'maxSize'    => 10 * 1024 * 1024,
                'tooBig'     => 'PDF must be smaller than 10 MB.',
                'wrongExtension' => 'Only PDF files are allowed.',
            ],
        ];
    }

    public function attributeLabels(): array
    {
        return [
            'id'                 => 'ID',
            'course_id'          => 'Course',
            'assessment_name'    => 'Assessment Name',
            'filename'           => 'Instruction File',
            'instruction'        => 'Instructions',
            'number_of_question' => 'Number of Questions',
            'pass_percentage'    => 'Pass Percentage (%)',
            'mark_per_question'  => 'Mark per Question',
            'created_datetime'   => 'Created On',
            'created_by'         => 'Created By',
            'update_date_time'   => 'Updated At',
            'updated_by'         => 'Updated By',
            'isActive'           => 'Status',
            'instructionFile'    => 'Upload Instruction PDF',
        ];
    }

    public function uploadFile(): bool
    {
        $file = $this->instructionFile;
        if ($file === null || !($file instanceof \yii\web\UploadedFile)) {
            return true;
        }

        $dir = Yii::getAlias(self::UPLOAD_PATH);
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }

        $filename = 'instr_' . $this->id . '_' . time() . '.' . $file->extension;
        $path     = $dir . $filename;

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

        // Delete old file
        if ($this->filename) {
            $old = $dir . $this->filename;
            if (is_file($old)) {
                @unlink($old);
            }
        }

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

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

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