<?php

declare(strict_types=1);

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('suppliers', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->string('phone')->nullable();
            $table->string('email')->nullable();
            $table->text('address')->nullable();
            $table->string('contact_person')->nullable();
            $table->timestamps();
        });

        Schema::create('stock_transactions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('outlet_id')->constrained('outlets')->onDelete('cascade');
            $table->foreignId('user_id')->constrained('users')->onDelete('cascade');
            $table->foreignId('supplier_id')->nullable()->constrained('suppliers')->onDelete('set null');
            $table->string('item_type'); // 'Ingredient' or 'Product'
            $table->unsignedBigInteger('item_id');
            $table->decimal('qty', 12, 4);
            $table->string('type'); // 'add' or 'set'
            $table->text('notes')->nullable();
            $table->timestamps();
        });

        // Insert Supplier Manager menu item
        DB::table('menus')->insert([
            'group_name' => 'CafePOS Management',
            'title' => 'Supplier Manager',
            'href' => '/admin/suppliers',
            'icon' => 'Truck',
            'roles' => null,
            'permissions' => json_encode(['inventory.manage']),
            'sort_order' => 6,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        // Shift menu order of Outlets, Reports, Settings, etc., to make room
        DB::table('menus')->where('sort_order', '>=', 6)
            ->where('title', '!=', 'Supplier Manager')
            ->increment('sort_order');
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('stock_transactions');
        Schema::dropIfExists('suppliers');

        // Delete menu item
        DB::table('menus')->where('href', '/admin/suppliers')->delete();

        // Restore sort orders
        DB::table('menus')->where('sort_order', '>', 6)->decrement('sort_order');
    }
};
