<?php

namespace App\Models;

use App\Models\BaseModel;

class ExamDraft extends BaseModel
{
    protected $table = 'exam_drafts';

    // ✅ CI: useTimestamps = true (created_at/updated_at)
    public $timestamps = true;

    protected $fillable = [
        'teacher_id',
        'class_section_id',
        'semester',
        'school_year',
        'exam_type',
        'draft_title',
        'description',
        'teacher_file',
        'teacher_filename',
        'status',
        'admin_id',
        'admin_comments',
        'reviewed_at',
        'final_file',
        'final_filename',
        'version',
        'previous_draft_id',
        'is_legacy',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'teacher_id'        => 'integer',
        'class_section_id'  => 'integer',
        'admin_id'          => 'integer',
        'is_legacy'         => 'boolean',

        'version'           => 'integer',
        'previous_draft_id' => 'integer',

        'reviewed_at'       => 'datetime',
    ];

    /**
     * CI had updateOnlyChanged=false (force updates even if nothing changed).
     * In Laravel, you can force a save by calling:
     *   $model->touch();   // updates updated_at only
     *   or
     *   $model->save(['timestamps' => true]); // normal save
     *
     * If you want a helper:
     */
    public function forceSave(array $attributes = []): bool
    {
        if (!empty($attributes)) {
            $this->fill($attributes);
        }

        // Force updated_at refresh even if no attributes changed
        $this->updated_at = now();

        return $this->save();
    }

    /* Optional relationships */
    public function teacher()
    {
        return $this->belongsTo(User::class, 'teacher_id');
    }

    public function admin()
    {
        return $this->belongsTo(User::class, 'admin_id');
    }

    public function classSection()
    {
        return $this->belongsTo(ClassSection::class, 'class_section_id');
    }

    public function previousDraft()
    {
        return $this->belongsTo(self::class, 'previous_draft_id');
    }
}