<?php

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
    {
        // For MySQL, we need to modify the ENUM type to rename pos_manager to branch_manager and add branch_cashier
        if (DB::getDriverName() === 'mysql') {
            // First, update existing pos_manager users to branch_manager
            DB::statement("UPDATE `users` SET `role` = 'branch_manager' WHERE `role` = 'pos_manager'");
            
            // Then modify the ENUM to remove pos_manager and add branch_cashier
            DB::statement("ALTER TABLE `users` MODIFY COLUMN `role` ENUM('admin', 'manager', 'staff', 'pos_staff', 'branch_manager', 'pos_kitchen_staff', 'restaurant_owner', 'branch_cashier') DEFAULT 'staff'");
        } else {
            // For other databases, change to string
            // Update existing pos_manager users to branch_manager
            DB::table('users')->where('role', 'pos_manager')->update(['role' => 'branch_manager']);
            
            Schema::table('users', function (Blueprint $table) {
                $table->string('role', 50)->default('staff')->change();
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        if (DB::getDriverName() === 'mysql') {
            // Revert branch_manager back to pos_manager
            DB::statement("UPDATE `users` SET `role` = 'pos_manager' WHERE `role` = 'branch_manager'");
            
            // Remove branch_cashier and restore pos_manager
            DB::statement("ALTER TABLE `users` MODIFY COLUMN `role` ENUM('admin', 'manager', 'staff', 'pos_staff', 'pos_manager', 'restaurant_owner', 'branch_manager') DEFAULT 'staff'");
        } else {
            // Revert branch_manager back to pos_manager
            DB::table('users')->where('role', 'branch_manager')->update(['role' => 'pos_manager']);
            
            Schema::table('users', function (Blueprint $table) {
                $table->enum('role', ['admin', 'manager', 'staff', 'pos_staff', 'pos_manager', 'restaurant_owner', 'branch_manager'])->default('staff')->change();
            });
        }
    }
};
