<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ExamSeatPlan extends Model
{
    use HasFactory;

    protected $table = 'exam_seat_plans';
    
    protected $fillable = [
        'exam_id',
        'exam_routine_id',
        'class_id',
        'room_number',
        'building',
        'seat_number',
        'student_id',
        'student_roll',
        'row_number',
        'column_number',
        'status'
    ];

    protected $casts = [
        'status' => 'boolean'
    ];

    public function exam()
    {
        return $this->belongsTo(Exam::class);
    }

    public function routine()
    {
        return $this->belongsTo(ExamRoutine::class, 'exam_routine_id');
    }

    public function class()
    {
        return $this->belongsTo(Classes::class, 'class_id');
    }

    public function student()
    {
        return $this->belongsTo(Student::class);
    }

    // Generate seat plan for a room
    public static function generateSeatPlan($examId, $routineId, $roomNumber, $building, $rows, $columns, $studentIds)
    {
        $seatNumber = 1;
        $seatPlans = [];

        for ($row = 1; $row <= $rows; $row++) {
            for ($col = 1; $col <= $columns; $col++) {
                if ($seatNumber <= count($studentIds)) {
                    $seatPlans[] = [
                        'exam_id' => $examId,
                        'exam_routine_id' => $routineId,
                        'room_number' => $roomNumber,
                        'building' => $building,
                        'seat_number' => $seatNumber,
                        'student_id' => $studentIds[$seatNumber - 1],
                        'row_number' => $row,
                        'column_number' => $col,
                        'created_at' => now(),
                        'updated_at' => now()
                    ];
                }
                $seatNumber++;
            }
        }

        return self::insert($seatPlans);
    }
}