<?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
    {
        // Main surat_tugas table
        Schema::create('surat_tugas', function (Blueprint $table) {
            $table->id();
            $table->foreignId('company_id')->constrained()->onDelete('cascade');

            // Nomor ST (optional)
            $table->string('no_st', 100)->nullable();

            // Periode
            $table->date('tanggal_mulai');
            $table->date('tanggal_selesai');

            // Lokasi - bisa dari locations table atau custom
            $table->foreignId('location_id')->nullable()->constrained()->onDelete('set null');

            // Lokasi custom (jika tidak memilih dari dropdown)
            $table->string('custom_location_name')->nullable();
            $table->decimal('custom_latitude', 10, 8)->nullable();
            $table->decimal('custom_longitude', 11, 8)->nullable();
            $table->text('custom_address')->nullable();

            // Keterangan
            $table->text('keterangan')->nullable();

            // Status
            $table->boolean('is_active')->default(true);

            // Audit
            $table->foreignId('created_by')->nullable()->constrained('users')->onDelete('set null');

            $table->timestamps();

            // Indexes
            $table->index(['company_id', 'tanggal_mulai', 'tanggal_selesai']);
            $table->index(['company_id', 'is_active']);
        });

        // Pivot table for assigning multiple users to one ST
        Schema::create('surat_tugas_user', function (Blueprint $table) {
            $table->id();
            $table->foreignId('surat_tugas_id')->constrained('surat_tugas')->onDelete('cascade');
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->timestamps();

            // Unique constraint - user tidak bisa diassign 2x ke ST yang sama
            $table->unique(['surat_tugas_id', 'user_id']);

            // Index untuk query by user
            $table->index('user_id');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('surat_tugas_user');
        Schema::dropIfExists('surat_tugas');
    }
};
