<?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
    {
        // Drop old tables
        Schema::dropIfExists('device_logs');
        Schema::dropIfExists('manual_punches');
        Schema::dropIfExists('attendance_logs');

        // Create unified punches table
        Schema::create('punches', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('company_id')->nullable(); // users.id of role_id=2
            $table->unsignedBigInteger('superadmin_id')->nullable();
            $table->foreignId('employee_id')->constrained()->onDelete('cascade');
            $table->dateTime('punch_time');
            $table->string('punch_type')->default('Machine'); // Machine, Manual, Other
            $table->string('device')->nullable(); // Web, Mobile, or Biometric device ID
            $table->text('remark')->nullable();
            $table->enum('status', ['In', 'Out', 'Unknown'])->default('Unknown');
            $table->timestamps();
        });

        // Create daily attendances table
        Schema::create('attendances', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('company_id')->nullable(); // users.id of role_id=2
            $table->foreignId('employee_id')->constrained()->onDelete('cascade');
            $table->date('attendance_date');
            $table->unsignedBigInteger('shift_id')->nullable();
            $table->dateTime('first_in')->nullable();
            $table->dateTime('last_out')->nullable();
            $table->decimal('total_working_hours', 8, 2)->default(0);
            $table->string('status')->default('Absent'); // Present, Absent, Half-Day, Late
            $table->timestamps();
            
            $table->unique(['employee_id', 'attendance_date']); // Only one attendance record per employee per day
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('attendances');
        Schema::dropIfExists('punches');
    }
};
