<?php

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

return new class extends Migration {
    public function up(): void
    {
        // Attendance Logs
        if (!Schema::hasTable('attendance_logs')) {
            Schema::create('attendance_logs', function (Blueprint $table) {
                $table->id();
                $table->foreignId('employee_id')->constrained('employees')->onDelete('cascade');
                $table->date('date');
                $table->time('check_in')->nullable();
                $table->time('check_out')->nullable();
                $table->enum('status', ['present', 'late', 'absent', 'on_leave', 'half_day'])->default('present');
                $table->text('notes')->nullable();
                $table->timestamps();

                $table->unique(['employee_id', 'date']);
            });
        }

        // Payrolls (Monthly Salary Records)
        if (!Schema::hasTable('payrolls')) {
            Schema::create('payrolls', function (Blueprint $table) {
                $table->id();
                $table->foreignId('employee_id')->constrained('employees')->onDelete('cascade');
                $table->string('period_month'); // Format: YYYY-MM
                $table->decimal('basic_salary', 12, 2)->default(0);
                $table->decimal('total_allowances', 12, 2)->default(0);
                $table->decimal('total_deductions', 12, 2)->default(0);
                $table->decimal('net_salary', 12, 2)->default(0);
                $table->enum('status', ['draft', 'approved', 'paid'])->default('draft');
                $table->date('payment_date')->nullable();
                $table->foreignId('treasury_id')->nullable()->constrained('treasuries')->nullOnDelete();
                $table->timestamps();

                $table->unique(['employee_id', 'period_month']);
            });
        }

        // Payroll Items (Allowances, Deductions, Bonuses, Penalties)
        if (!Schema::hasTable('payroll_items')) {
            Schema::create('payroll_items', function (Blueprint $table) {
                $table->id();
                $table->foreignId('payroll_id')->constrained('payrolls')->onDelete('cascade');
                $table->enum('type', ['allowance', 'deduction', 'bonus', 'penalty']);
                $table->string('description');
                $table->decimal('amount', 12, 2);
                $table->timestamps();
            });
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('payroll_items');
        Schema::dropIfExists('payrolls');
        Schema::dropIfExists('attendance_logs');
    }
};
