<?php

namespace app\models;

use Yii;
use yii\db\ActiveRecord;
use yii\web\UploadedFile;

/**
 * Profile model
 *
 * @property int $id
 * @property int $user_id
 * @property string|null $photo
 * ...
 */
class Profile extends ActiveRecord
{
    /** @var UploadedFile|null */
    public $photoFile;
    public $passportFile;
    public $diplomaFile;
    public $snilsFile;

    public static function tableName()
    {
        return '{{%profile}}';
    }

    public function rules()
    {
        return [
            [['user_id'], 'required'],
            [['user_id','work_experience'], 'integer'],
            [['birth_date','passport_issue_date'], 'safe'],
            [['additional_info','passport_issued_by','registration_address','health_status'], 'string'],
            [['photo','diploma_file','snils_file','passport_series','passport_number','diploma_series','diploma_number','snils','workplace','position','education_institution','specialty','citizenship','marital_status','education_level','email','phone','status'], 'string', 'max' => 255],

            // файловые правила
            [['photoFile'], 'file', 'skipOnEmpty' => true, 'extensions' => 'jpg,jpeg,pdf', 'maxSize' => 10 * 1024 * 1024],
            [['passportFile','diplomaFile'], 'file', 'skipOnEmpty' => true, 'extensions' => 'jpg,jpeg,pdf', 'maxSize' => 20 * 1024 * 1024],
            [['snilsFile'], 'file', 'skipOnEmpty' => true, 'extensions' => 'jpg,jpeg,pdf', 'maxSize' => 10 * 1024 * 1024],
        ];
    }

    public function attributeLabels()
    {
        return [
            'photoFile' => 'Фото (jpg, jpeg, pdf, до 10Мб)',
            'passportFile' => 'Скан паспорта (до 20Мб)',
            'diplomaFile' => 'Скан диплома (до 20Мб)',
            'snilsFile' => 'Скан СНИЛС (до 10Мб)',
        ];
    }

    public function getUser()
    {
        return $this->hasOne(User::class, ['id' => 'user_id']);
    }

    /**
     * Сохранение загруженных файлов в web/uploads/{user_id}/ и обновление полей модели
     */
    public function saveFiles()
    {
        $basePathAlias = '@app/web/uploads';
        $userDir = $basePathAlias . '/' . $this->user_id;
        if (!is_dir($userDir)) {
            mkdir($userDir, 0755, true);
        }

        $saved = [];

        if ($this->photoFile instanceof UploadedFile) {
            $name = 'photo_' . time() . '.' . $this->photoFile->extension;
            $path = "$userDir/$name";
            if ($this->photoFile->saveAs($path)) {
                $this->photo = "uploads/{$this->user_id}/$name";
                $saved[] = ['file' => $name, 'path' => $this->photo];
            }
        }

        if ($this->passportFile instanceof UploadedFile) {
            $name = 'passport_' . time() . '.' . $this->passportFile->extension;
            $path = "$userDir/$name";
            if ($this->passportFile->saveAs($path)) {
                $this->passport_file = "uploads/{$this->user_id}/$name";
                // сохраняем метаданные в таблице files (опционально)
            }
        }

        if ($this->diplomaFile instanceof UploadedFile) {
            $name = 'diploma_' . time() . '.' . $this->diplomaFile->extension;
            $path = "$userDir/$name";
            if ($this->diplomaFile->saveAs($path)) {
                $this->diploma_file = "uploads/{$this->user_id}/$name";
            }
        }

        if ($this->snilsFile instanceof UploadedFile) {
            $name = 'snils_' . time() . '.' . $this->snilsFile->extension;
            $path = "$userDir/$name";
            if ($this->snilsFile->saveAs($path)) {
                $this->snils_file = "uploads/{$this->user_id}/$name";
            }
        }

        return $saved;
    }
}
