<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('attendance_logs', function (Blueprint $table) {
            if (!Schema::hasColumn('attendance_logs', 'student_id')) {
                $table->foreignId('student_id')->constrained('students');
            }
            if (!Schema::hasColumn('attendance_logs', 'device_id')) {
                $table->foreignId('device_id')->constrained('devices');
            }
            if (!Schema::hasColumn('attendance_logs', 'type')) {
                $table->enum('type', ['in','out']);
            }
            if (!Schema::hasColumn('attendance_logs', 'occurred_at')) {
                $table->dateTime('occurred_at');
            }
            if (!Schema::hasColumn('attendance_logs', 'received_at')) {
                $table->dateTime('received_at')->nullable();
            }
            if (!Schema::hasColumn('attendance_logs', 'status')) {
                $table->string('status')->default('sent');
            }
            if (!Schema::hasColumn('attendance_logs', 'meta')) {
                $table->json('meta')->nullable();
            }
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('attendance_logs', function (Blueprint $table) {
            if (Schema::hasColumn('attendance_logs', 'meta')) { $table->dropColumn('meta'); }
            if (Schema::hasColumn('attendance_logs', 'status')) { $table->dropColumn('status'); }
            if (Schema::hasColumn('attendance_logs', 'received_at')) { $table->dropColumn('received_at'); }
            if (Schema::hasColumn('attendance_logs', 'occurred_at')) { $table->dropColumn('occurred_at'); }
            if (Schema::hasColumn('attendance_logs', 'type')) { $table->dropColumn('type'); }
            if (Schema::hasColumn('attendance_logs', 'device_id')) { $table->dropConstrainedForeignId('device_id'); }
            if (Schema::hasColumn('attendance_logs', 'student_id')) { $table->dropConstrainedForeignId('student_id'); }
        });
    }
};
