<?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
    {
        // 1. KEMBALIKAN ATURAN NOT NULL MENJADI NULLABLE (Sesuai db_pos_bangunan)
        // Di Laravel 11, ->change() bisa langsung digunakan tanpa doctrine/dbal
        Schema::table('banners', function (Blueprint $table) {
            $table->string('bg_color', 50)->nullable()->default('from-blue-600 to-indigo-800')->comment('Warna Gradient Fallback')->change();
            $table->enum('link_type', ['product', 'category', 'global'])->nullable()->default('global')->comment('Aksi Klik Banner')->change();
            $table->integer('sequence')->nullable()->default(0)->comment('Urutan Slide Banner')->change();
        });

        Schema::table('branch_accounts', function (Blueprint $table) {
            $table->boolean('is_active')->nullable()->default(true)->change();
        });

        Schema::table('canvas_loadings', function (Blueprint $table) {
            $table->enum('status', ['pending', 'approved', 'active', 'unloaded', 'settled', 'void'])->nullable()->default('approved')->change();
        });

        Schema::table('canvas_loading_items', function (Blueprint $table) {
            $table->double('qty_returned')->nullable()->default(0)->change();
            $table->double('qty_sold')->nullable()->default(0)->change();
        });

        Schema::table('products', function (Blueprint $table) {
            $table->decimal('average_cost', 15, 2)->nullable()->default(0)->change();
        });

        Schema::table('product_prices', function (Blueprint $table) {
            $table->decimal('price_l3', 15, 2)->nullable()->default(0)->change();
            $table->decimal('price_l4', 15, 2)->nullable()->default(0)->change();
        });

        // 2. KEMBALIKAN KOMENTAR KOLOM YANG HILANG
        Schema::table('sales_programs', function (Blueprint $table) {
            $table->longText('target_customer_types')->nullable()->comment('Array JSON ID Tipe Outlet')->change();
        });

        Schema::table('stock_write_off_items', function (Blueprint $table) {
            $table->unsignedBigInteger('reference_id')->nullable()->comment('ID dari sales_return_items jika ada')->change();
        });

        // 3. KEMBALIKAN SEMUA FOREIGN KEY (Menggunakan Raw SQL agar 100% presisi dan eksekusi lebih cepat)
        DB::unprepared("
            --
            -- Constraints for dumped tables
            --

            --
            -- Constraints for table `accounting_settings`
            --
            ALTER TABLE `accounting_settings`
            ADD CONSTRAINT `accounting_settings_account_id_foreign` FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`) ON DELETE SET NULL;

            --
            -- Constraints for table `branch_accounts`
            --
            ALTER TABLE `branch_accounts`
            ADD CONSTRAINT `fk_account_map` FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`) ON DELETE CASCADE,
            ADD CONSTRAINT `fk_branch_map` FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `branch_product`
            --
            ALTER TABLE `branch_product`
            ADD CONSTRAINT `branch_product_branch_id_foreign` FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`) ON DELETE CASCADE,
            ADD CONSTRAINT `branch_product_product_id_foreign` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `canvas_loadings`
            --
            ALTER TABLE `canvas_loadings`
            ADD CONSTRAINT `fk_canvas_loadings_salesman_id` FOREIGN KEY (`salesman_id`) REFERENCES `salesmen` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `canvas_loading_items`
            --
            ALTER TABLE `canvas_loading_items`
            ADD CONSTRAINT `fk_cli_loading_id` FOREIGN KEY (`canvas_loading_id`) REFERENCES `canvas_loadings` (`id`) ON DELETE CASCADE,
            ADD CONSTRAINT `fk_cli_product_id` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE RESTRICT;

            --
            -- Constraints for table `canvas_stocks`
            --
            ALTER TABLE `canvas_stocks`
            ADD CONSTRAINT `fk_canvas_stocks_branch_id` FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`) ON DELETE RESTRICT,
            ADD CONSTRAINT `fk_canvas_stocks_product_id` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE RESTRICT,
            ADD CONSTRAINT `fk_canvas_stocks_salesman_id` FOREIGN KEY (`salesman_id`) REFERENCES `salesmen` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `cash_mutations`
            --
            ALTER TABLE `cash_mutations`
            ADD CONSTRAINT `cash_mutations_branch_id_foreign` FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`),
            ADD CONSTRAINT `cash_mutations_from_account_id_foreign` FOREIGN KEY (`from_account_id`) REFERENCES `accounts` (`id`),
            ADD CONSTRAINT `cash_mutations_to_account_id_foreign` FOREIGN KEY (`to_account_id`) REFERENCES `accounts` (`id`),
            ADD CONSTRAINT `cash_mutations_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);

            --
            -- Constraints for table `cities`
            --
            ALTER TABLE `cities`
            ADD CONSTRAINT `cities_province_id_foreign` FOREIGN KEY (`province_id`) REFERENCES `provinces` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `customers`
            --
            ALTER TABLE `customers`
            ADD CONSTRAINT `customers_branch_id_foreign` FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`) ON DELETE SET NULL,
            ADD CONSTRAINT `customers_district_id_foreign` FOREIGN KEY (`district_id`) REFERENCES `districts` (`id`) ON DELETE SET NULL,
            ADD CONSTRAINT `customers_salesman_id_foreign` FOREIGN KEY (`salesman_id`) REFERENCES `salesmen` (`id`) ON DELETE SET NULL,
            ADD CONSTRAINT `fk_customer_type` FOREIGN KEY (`customer_type_id`) REFERENCES `customer_types` (`id`) ON DELETE SET NULL;

            --
            -- Constraints for table `daily_shifts`
            --
            ALTER TABLE `daily_shifts`
            ADD CONSTRAINT `daily_shifts_branch_id_foreign` FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`),
            ADD CONSTRAINT `daily_shifts_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);

            --
            -- Constraints for table `debt_payments`
            --
            ALTER TABLE `debt_payments`
            ADD CONSTRAINT `debt_payments_branch_id_foreign` FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`),
            ADD CONSTRAINT `debt_payments_purchase_id_foreign` FOREIGN KEY (`purchase_id`) REFERENCES `purchases` (`id`) ON DELETE CASCADE,
            ADD CONSTRAINT `debt_payments_sale_id_foreign` FOREIGN KEY (`sale_id`) REFERENCES `sales` (`id`) ON DELETE CASCADE,
            ADD CONSTRAINT `debt_payments_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);

            --
            -- Constraints for table `delivery_zones`
            --
            ALTER TABLE `delivery_zones`
            ADD CONSTRAINT `delivery_zones_branch_id_foreign` FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `districts`
            --
            ALTER TABLE `districts`
            ADD CONSTRAINT `districts_city_id_foreign` FOREIGN KEY (`city_id`) REFERENCES `cities` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `driver_assignments`
            --
            ALTER TABLE `driver_assignments`
            ADD CONSTRAINT `fk_driver_armada` FOREIGN KEY (`armada_id`) REFERENCES `armadas` (`id`) ON DELETE CASCADE,
            ADD CONSTRAINT `fk_driver_branch` FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`),
            ADD CONSTRAINT `fk_driver_user` FOREIGN KEY (`driver_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `expenses`
            --
            ALTER TABLE `expenses`
            ADD CONSTRAINT `expenses_branch_id_foreign` FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`) ON DELETE CASCADE,
            ADD CONSTRAINT `expenses_expense_category_id_foreign` FOREIGN KEY (`expense_category_id`) REFERENCES `expense_categories` (`id`) ON DELETE SET NULL,
            ADD CONSTRAINT `expenses_fund_account_id_foreign` FOREIGN KEY (`fund_account_id`) REFERENCES `accounts` (`id`) ON DELETE SET NULL,
            ADD CONSTRAINT `expenses_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);

            --
            -- Constraints for table `expense_categories`
            --
            ALTER TABLE `expense_categories`
            ADD CONSTRAINT `expense_categories_account_id_foreign` FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`) ON DELETE SET NULL;

            --
            -- Constraints for table `hold_carts`
            --
            ALTER TABLE `hold_carts`
            ADD CONSTRAINT `hold_carts_branch_id_foreign` FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`) ON DELETE CASCADE,
            ADD CONSTRAINT `hold_carts_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `journal_entries`
            --
            ALTER TABLE `journal_entries`
            ADD CONSTRAINT `journal_entries_branch_id_foreign` FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`) ON DELETE CASCADE,
            ADD CONSTRAINT `journal_entries_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);

            --
            -- Constraints for table `journal_items`
            --
            ALTER TABLE `journal_items`
            ADD CONSTRAINT `journal_items_account_id_foreign` FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`),
            ADD CONSTRAINT `journal_items_journal_entry_id_foreign` FOREIGN KEY (`journal_entry_id`) REFERENCES `journal_entries` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `market_intelligences`
            --
            ALTER TABLE `market_intelligences`
            ADD CONSTRAINT `fk_intel_brand_id` FOREIGN KEY (`competitor_brand_id`) REFERENCES `competitor_brands` (`id`) ON DELETE RESTRICT,
            ADD CONSTRAINT `fk_intel_visit_id` FOREIGN KEY (`salesman_visit_id`) REFERENCES `salesman_visits` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `master_journey_plans`
            --
            ALTER TABLE `master_journey_plans`
            ADD CONSTRAINT `mjp_customer_id_foreign` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE,
            ADD CONSTRAINT `mjp_salesman_id_foreign` FOREIGN KEY (`salesman_id`) REFERENCES `salesmen` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `model_has_permissions`
            --
            ALTER TABLE `model_has_permissions`
            ADD CONSTRAINT `model_has_permissions_permission_id_foreign` FOREIGN KEY (`permission_id`) REFERENCES `permissions` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `model_has_roles`
            --
            ALTER TABLE `model_has_roles`
            ADD CONSTRAINT `model_has_roles_role_id_foreign` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `monthly_stock_balances`
            --
            ALTER TABLE `monthly_stock_balances`
            ADD CONSTRAINT `monthly_stock_balances_branch_id_foreign` FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`) ON DELETE CASCADE,
            ADD CONSTRAINT `monthly_stock_balances_product_id_foreign` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE,
            ADD CONSTRAINT `monthly_stock_balances_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);

            --
            -- Constraints for table `point_histories`
            --
            ALTER TABLE `point_histories`
            ADD CONSTRAINT `point_histories_customer_id_foreign` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE,
            ADD CONSTRAINT `point_histories_sale_id_foreign` FOREIGN KEY (`sale_id`) REFERENCES `sales` (`id`) ON DELETE SET NULL;

            --
            -- Constraints for table `purchase_receipts`
            --
            ALTER TABLE `purchase_receipts`
            ADD CONSTRAINT `purchase_receipts_branch_id_foreign` FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`) ON DELETE CASCADE,
            ADD CONSTRAINT `purchase_receipts_purchase_id_foreign` FOREIGN KEY (`purchase_id`) REFERENCES `purchases` (`id`) ON DELETE CASCADE,
            ADD CONSTRAINT `purchase_receipts_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `purchase_receipt_items`
            --
            ALTER TABLE `purchase_receipt_items`
            ADD CONSTRAINT `purchase_receipt_items_product_id_foreign` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE,
            ADD CONSTRAINT `purchase_receipt_items_purchase_receipt_id_foreign` FOREIGN KEY (`purchase_receipt_id`) REFERENCES `purchase_receipts` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `purchase_return_items`
            --
            ALTER TABLE `purchase_return_items`
            ADD CONSTRAINT `purchase_return_items_purchase_return_id_foreign` FOREIGN KEY (`purchase_return_id`) REFERENCES `purchase_returns` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `role_has_permissions`
            --
            ALTER TABLE `role_has_permissions`
            ADD CONSTRAINT `role_has_permissions_permission_id_foreign` FOREIGN KEY (`permission_id`) REFERENCES `permissions` (`id`) ON DELETE CASCADE,
            ADD CONSTRAINT `role_has_permissions_role_id_foreign` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `sales`
            --
            ALTER TABLE `sales`
            ADD CONSTRAINT `fk_sales_helper` FOREIGN KEY (`helper_id`) REFERENCES `users` (`id`) ON DELETE SET NULL;

            --
            -- Constraints for table `salesman_targets`
            --
            ALTER TABLE `salesman_targets`
            ADD CONSTRAINT `fk_st_branch_id` FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`) ON DELETE RESTRICT,
            ADD CONSTRAINT `fk_st_salesman_id` FOREIGN KEY (`salesman_id`) REFERENCES `salesmen` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `salesman_target_items`
            --
            ALTER TABLE `salesman_target_items`
            ADD CONSTRAINT `fk_sti_header_id` FOREIGN KEY (`target_id`) REFERENCES `salesman_targets` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `salesman_visits`
            --
            ALTER TABLE `salesman_visits`
            ADD CONSTRAINT `fk_visits_no_order_reason_id` FOREIGN KEY (`no_order_reason_id`) REFERENCES `no_order_reasons` (`id`) ON DELETE RESTRICT,
            ADD CONSTRAINT `salesman_visits_customer_id_foreign` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE RESTRICT,
            ADD CONSTRAINT `salesman_visits_salesman_id_foreign` FOREIGN KEY (`salesman_id`) REFERENCES `salesmen` (`id`) ON DELETE RESTRICT;

            --
            -- Constraints for table `salesmen`
            --
            ALTER TABLE `salesmen`
            ADD CONSTRAINT `fk_salesman_supervisor` FOREIGN KEY (`supervisor_id`) REFERENCES `users` (`id`) ON DELETE SET NULL,
            ADD CONSTRAINT `salesmen_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `sales_orders`
            --
            ALTER TABLE `sales_orders`
            ADD CONSTRAINT `fk_sales_orders_salesman_id` FOREIGN KEY (`salesman_id`) REFERENCES `salesmen` (`id`) ON DELETE SET NULL,
            ADD CONSTRAINT `sales_orders_applied_program_id_foreign` FOREIGN KEY (`applied_program_id`) REFERENCES `sales_programs` (`id`) ON DELETE SET NULL,
            ADD CONSTRAINT `sales_orders_branch_id_foreign` FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`),
            ADD CONSTRAINT `sales_orders_customer_id_foreign` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`),
            ADD CONSTRAINT `sales_orders_fulfillment_branch_id_foreign` FOREIGN KEY (`fulfillment_branch_id`) REFERENCES `branches` (`id`),
            ADD CONSTRAINT `sales_orders_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);

            --
            -- Constraints for table `sales_order_items`
            --
            ALTER TABLE `sales_order_items`
            ADD CONSTRAINT `sales_order_items_applied_program_id_foreign` FOREIGN KEY (`applied_program_id`) REFERENCES `sales_programs` (`id`) ON DELETE SET NULL,
            ADD CONSTRAINT `sales_order_items_product_id_foreign` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`),
            ADD CONSTRAINT `sales_order_items_sales_order_id_foreign` FOREIGN KEY (`sales_order_id`) REFERENCES `sales_orders` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `sales_programs`
            --
            ALTER TABLE `sales_programs`
            ADD CONSTRAINT `sales_programs_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE SET NULL,
            ADD CONSTRAINT `sales_programs_free_product_id_foreign` FOREIGN KEY (`free_product_id`) REFERENCES `products` (`id`) ON DELETE SET NULL,
            ADD CONSTRAINT `sales_programs_product_id_foreign` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE SET NULL;

            --
            -- Constraints for table `sales_program_tiers`
            --
            ALTER TABLE `sales_program_tiers`
            ADD CONSTRAINT `sales_program_tiers_bonus_product_id_foreign` FOREIGN KEY (`bonus_product_id`) REFERENCES `products` (`id`) ON DELETE SET NULL,
            ADD CONSTRAINT `sales_program_tiers_sales_program_id_foreign` FOREIGN KEY (`sales_program_id`) REFERENCES `sales_programs` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `sales_returns`
            --
            ALTER TABLE `sales_returns`
            ADD CONSTRAINT `fk_sr_branch_id` FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`) ON DELETE RESTRICT,
            ADD CONSTRAINT `fk_sr_customer_id` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE RESTRICT,
            ADD CONSTRAINT `fk_sr_invoice_id` FOREIGN KEY (`sales_invoice_id`) REFERENCES `sales_invoices` (`id`) ON DELETE SET NULL;

            --
            -- Constraints for table `sales_return_items`
            --
            ALTER TABLE `sales_return_items`
            ADD CONSTRAINT `fk_sri_product_id` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE RESTRICT,
            ADD CONSTRAINT `fk_sri_return_id` FOREIGN KEY (`sales_return_id`) REFERENCES `sales_returns` (`id`) ON DELETE CASCADE;

            --
            -- Constraints for table `stock_adjustments`
            --
            ALTER TABLE `stock_adjustments`
            ADD CONSTRAINT `fk_adj_branch_id` FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`) ON DELETE RESTRICT,
            ADD CONSTRAINT `fk_adj_user_id` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`);

            --
            -- Constraints for table `stock_adjustment_items`
            --
            ALTER TABLE `stock_adjustment_items`
            ADD CONSTRAINT `fk_adji_header_id` FOREIGN KEY (`stock_adjustment_id`) REFERENCES `stock_adjustments` (`id`) ON DELETE CASCADE,
            ADD CONSTRAINT `fk_adji_product_id` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE RESTRICT;

            --
            -- Constraints for table `stock_write_offs`
            --
            ALTER TABLE `stock_write_offs`
            ADD CONSTRAINT `fk_wo_branch_id` FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`) ON DELETE RESTRICT,
            ADD CONSTRAINT `fk_wo_user_id` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`);

            --
            -- Constraints for table `stock_write_off_items`
            --
            ALTER TABLE `stock_write_off_items`
            ADD CONSTRAINT `fk_woi_header_id` FOREIGN KEY (`stock_write_off_id`) REFERENCES `stock_write_offs` (`id`) ON DELETE CASCADE,
            ADD CONSTRAINT `fk_woi_product_id` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE RESTRICT;
            COMMIT;
        ");
        
        // 4. (Opsional) Mengembalikan urutan kolom (jika wajib sama persis susunannya)
        DB::statement('ALTER TABLE products MODIFY buy_price DECIMAL(15,2) NOT NULL DEFAULT "0.00" AFTER updated_at');
        DB::statement('ALTER TABLE products MODIFY average_cost DECIMAL(15,2) NULL DEFAULT "0.00" AFTER buy_price');
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Script untuk menghapus kembali foreign key jika di-rollback
        // Schema::dropColumns atau drop foreign key bisa ditulis di sini jika diperlukan.
    }
};