<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Paper extends Model
{
    protected $table = 'papers';
    protected $primaryKey = 'paper_id';
    public $incrementing = false;
    protected $keyType = 'string';
    public $timestamps = true;

    const CREATED_AT = 'created_at';
    const UPDATED_AT = 'updated_at';

    protected $fillable = [
        'paper_id',
        'student_id',
        'teacher_id',
        'paper_name',
        'paper_type',
        'diagnostic_chapter_id', // 摸底的章节ID（章节摸底时记录）
        'explanation_kp_codes', // 学案讲解的知识点列表（最多2个）
        'total_questions',
        'total_score',
        'status',
        'difficulty_category',
        'completed_at',
        'analysis_id', // AI分析记录ID
        'exam_pdf_url', // 试卷PDF URL
        'grading_pdf_url', // 判卷PDF URL
        'all_pdf_url', // 【新增】统一PDF URL（包含试卷和判卷）
    ];

    protected $casts = [
        'paper_id' => 'string',
        'student_id' => 'string',
        'teacher_id' => 'string',
        'total_questions' => 'integer',
        'total_score' => 'float',
        'status' => 'string',
        'difficulty_category' => 'string',
        'paper_type' => 'integer',
        'diagnostic_chapter_id' => 'integer',
        'explanation_kp_codes' => 'array', // JSON 自动转数组
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'completed_at' => 'datetime',
        'exam_pdf_url' => 'string',
        'grading_pdf_url' => 'string',
        'all_pdf_url' => 'string',
    ];

    /**
     * 获取试卷的题目列表
     */
    public function questions()
    {
        return $this->hasMany(PaperQuestion::class, 'paper_id', 'paper_id');
    }

    /**
     * 获取试卷创建者
     */
    public function createdByUser()
    {
        return $this->belongsTo(User::class, 'created_by', 'user_id');
    }

    /**
     * 获取关联的学生
     */
    public function student()
    {
        return $this->belongsTo(Student::class, 'student_id', 'student_id');
    }

    /**
     * 获取关联的教师
     */
    public function teacher()
    {
        return $this->belongsTo(Teacher::class, 'teacher_id', 'teacher_id');
    }
}
