<?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
    {
        // Mematikan konstrain kunci asing sementara agar tidak error urutan pembuatan tabel
        Schema::disableForeignKeyConstraints();

        // 1. Tabel accounting_periods
        Schema::create('accounting_periods', function (Blueprint $table) {
            $table->id();
            $table->integer('period_month');
            $table->integer('period_year');
            $table->enum('status', ['open', 'closed'])->default('open');
            $table->unsignedBigInteger('closed_by')->nullable();
            $table->timestamp('closed_at')->nullable();
            $table->timestamps();
        });

        // 2. Tabel accounting_settings
        Schema::create('accounting_settings', function (Blueprint $table) {
            $table->id();
            $table->string('setting_key');
            $table->unsignedBigInteger('account_id')->nullable();
            $table->timestamps();
        });

        // 3. Tabel accounts
        Schema::create('accounts', function (Blueprint $table) {
            $table->id();
            $table->string('code', 20)->unique();
            $table->string('name');
            $table->enum('group', ['asset','liability','equity','revenue','expense']);
            $table->string('category', 50)->nullable();
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        // 4. Tabel app_settings
        Schema::create('app_settings', function (Blueprint $table) {
            $table->id();
            $table->string('brand_name')->default('RISKI JAYA POS');
            $table->boolean('is_online_store_open')->default(true);
            $table->string('brand_logo')->nullable();
            $table->string('primary_color')->default('Blue');
            $table->string('admin_whatsapp')->nullable();
            $table->text('whatsapp_format')->nullable();
            $table->timestamps();
        });

        // 5. Tabel armadas
        Schema::create('armadas', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('license_plate')->unique();
            $table->unsignedBigInteger('branch_id')->nullable();
            $table->timestamps();
        });

        // 6. Tabel banners
        Schema::create('banners', function (Blueprint $table) {
            $table->id();
            $table->string('title')->comment('Judul Utama Banner');
            $table->string('subtitle')->nullable()->comment('Deskripsi Pendek Banner');
            $table->string('image_path')->nullable()->comment('File Gambar Banner jika ada');
            $table->string('bg_color', 50)->default('from-blue-600 to-indigo-800')->comment('Warna Gradient Fallback');
            $table->enum('link_type', ['product','category','global'])->default('global')->comment('Aksi Klik Banner');
            $table->integer('link_id')->nullable()->comment('Target ID Produk atau Kategori');
            $table->integer('sequence')->default(0)->comment('Urutan Slide Banner');
            $table->boolean('is_active')->default(true)->comment('Status Aktif');
            $table->timestamps();
        });

        // 7. Tabel branches
        Schema::create('branches', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('code', 10)->nullable()->comment('Singkatan: PB, EL, TG');
            $table->text('address')->nullable();
            $table->decimal('latitude', 10, 8)->nullable();
            $table->decimal('longitude', 11, 8)->nullable();
            $table->integer('max_delivery_radius')->default(15);
            $table->integer('max_delivery_radius_km')->default(15);
            $table->boolean('is_online_active')->default(true);
            $table->string('credit_price_system')->default('sama_dengan_tunai');
            $table->decimal('credit_markup_value', 8, 2)->default(0.00);
            $table->string('phone')->nullable();
            $table->timestamps();
        });

        // 8. Tabel branch_accounts
        Schema::create('branch_accounts', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('branch_id');
            $table->unsignedBigInteger('account_id');
            $table->enum('type', ['kas_kecil','kas_besar','bank_utama','bank_operasional','rk_pusat','rk_cabang']);
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        // 9. Tabel branch_product
        Schema::create('branch_product', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('branch_id');
            $table->unsignedBigInteger('product_id');
        });

        // 10. Tabel cache
        Schema::create('cache', function (Blueprint $table) {
            $table->string('key')->primary();
            $table->mediumText('value');
            $table->integer('expiration');
        });

        // 11. Tabel cache_locks
        Schema::create('cache_locks', function (Blueprint $table) {
            $table->string('key')->primary();
            $table->string('owner');
            $table->integer('expiration');
        });

        // 12. Tabel canvas_loadings
        Schema::create('canvas_loadings', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('branch_id')->nullable();
            $table->unsignedBigInteger('salesman_id');
            $table->date('date');
            $table->enum('status', ['pending','approved','active','unloaded','settled','void'])->default('approved');
            $table->unsignedBigInteger('created_by');
            $table->timestamps();
        });

        // 13. Tabel canvas_loading_items
        Schema::create('canvas_loading_items', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('canvas_loading_id');
            $table->unsignedBigInteger('product_id');
            $table->double('quantity');
            $table->double('qty_returned')->default(0);
            $table->double('qty_sold')->default(0);
            $table->string('unit', 50)->nullable();
            $table->timestamps();
        });

        // 14. Tabel canvas_stocks
        Schema::create('canvas_stocks', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('branch_id');
            $table->unsignedBigInteger('salesman_id');
            $table->unsignedBigInteger('product_id');
            $table->double('quantity')->default(0);
            $table->timestamps();
        });

        // 15. Tabel cash_mutations
        Schema::create('cash_mutations', function (Blueprint $table) {
            $table->id();
            $table->date('mutation_date');
            $table->unsignedBigInteger('from_account_id')->nullable();
            $table->unsignedBigInteger('to_account_id');
            $table->decimal('amount', 15, 2);
            $table->string('type');
            $table->string('note')->nullable();
            $table->unsignedBigInteger('branch_id');
            $table->unsignedBigInteger('user_id');
            $table->timestamps();
        });

        // 16. Tabel categories
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('image_path')->nullable();
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        // 17. Tabel cities
        Schema::create('cities', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('province_id');
            $table->string('name');
            $table->timestamps();
        });

        // 18. Tabel competitor_brands
        Schema::create('competitor_brands', function (Blueprint $table) {
            $table->id();
            $table->string('brand_name', 100)->unique()->comment('Nama Brand Pesaing');
            $table->boolean('is_active')->default(true)->comment('Status Aktif Dropdown');
            $table->text('competitor_promo_found')->nullable();
            $table->timestamps();
        });

        // 19. Tabel customers
        Schema::create('customers', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('no_ktp', 20)->nullable();
            $table->string('ktp_photo_path')->nullable();
            $table->string('phone')->nullable();
            $table->string('password')->nullable();
            $table->integer('loyalty_points')->default(0);
            $table->integer('due_days')->default(0)->comment('0 = Cash Only, >0 = Jumlah Hari Kredit');
            $table->boolean('is_pkp')->default(false);
            $table->enum('default_tax_method', ['non','include','exclude'])->default('include');
            $table->string('npwp', 30)->nullable();
            $table->text('address')->nullable();
            $table->string('benchmark')->nullable();
            $table->string('customer_code')->nullable()->unique();
            $table->unsignedBigInteger('district_id')->nullable();
            $table->unsignedBigInteger('branch_id')->nullable();
            $table->boolean('is_active')->default(true);
            $table->unsignedBigInteger('salesman_id')->nullable();
            $table->decimal('latitude', 10, 8)->nullable();
            $table->decimal('longitude', 11, 8)->nullable();
            $table->decimal('credit_limit', 15, 2)->default(0.00);
            $table->boolean('credit_limit_active')->default(true);
            $table->boolean('multiple_invoice_hold_active')->default(true);
            $table->decimal('deposit_balance', 15, 2)->default(0.00)->nullable();
            $table->enum('price_level', ['1','2','3','4'])->default('1');
            $table->unsignedBigInteger('customer_type_id')->nullable();
            $table->string('owner_name')->nullable();
            $table->enum('registration_status', ['pending','approved','rejected'])->default('approved');
            $table->date('join_date')->nullable();
            $table->timestamps();
        });

        // 20. Tabel customer_types
        Schema::create('customer_types', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });

        // 21. Tabel daily_shifts
        Schema::create('daily_shifts', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('branch_id');
            $table->decimal('opening_cash', 15, 2);
            $table->decimal('actual_closing_cash', 15, 2)->nullable();
            $table->dateTime('closed_at')->nullable();
            $table->date('date');
            $table->timestamps();
        });

        // 22. Tabel debt_payments
        Schema::create('debt_payments', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('sale_id')->nullable();
            $table->unsignedBigInteger('branch_id');
            $table->unsignedBigInteger('purchase_id')->nullable();
            $table->decimal('amount', 15, 2);
            $table->unsignedBigInteger('account_id')->nullable();
            $table->string('payment_method')->default('cash');
            $table->string('payment_type', 50)->default('cash');
            $table->string('giro_number', 100)->nullable();
            $table->date('giro_due_date')->nullable();
            $table->enum('giro_status', ['pending','cleared','rejected'])->nullable();
            $table->string('proof_image_path')->nullable();
            $table->enum('payment_status', ['completed','pending','cancelled'])->default('completed');
            $table->date('payment_date')->nullable();
            $table->text('note')->nullable();
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('visit_id')->nullable();
            $table->timestamps();
        });

        // 23. Tabel delivery_logs
        Schema::create('delivery_logs', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('sale_id')->nullable();
            $table->unsignedBigInteger('sales_order_id')->nullable();
            $table->unsignedBigInteger('driver_id')->nullable();
            $table->string('status');
            $table->text('reason')->nullable();
            $table->decimal('latitude', 10, 8)->nullable();
            $table->decimal('longitude', 11, 8)->nullable();
            $table->timestamps();
        });

        // 24. Tabel delivery_zones
        Schema::create('delivery_zones', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('branch_id');
            $table->string('zone_name');
            $table->decimal('max_radius_km', 8, 2);
            $table->decimal('shipping_fee', 15, 2);
            $table->decimal('min_order_value', 15, 2)->default(0.00);
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        // 25. Tabel districts
        Schema::create('districts', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('city_id');
            $table->string('name');
            $table->timestamps();
        });

        // 26. Tabel driver_assignments
        Schema::create('driver_assignments', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('driver_id')->comment('Merujuk ke users dengan role driver');
            $table->unsignedBigInteger('armada_id')->comment('Merujuk ke tabel armadas');
            $table->unsignedBigInteger('branch_id');
            $table->boolean('is_active')->default(true);
            $table->text('notes')->nullable();
            $table->timestamps();
        });

        // 27. Tabel expenses
        Schema::create('expenses', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('branch_id');
            $table->string('name');
            $table->decimal('amount', 15, 2);
            $table->string('fund_source')->nullable();
            $table->unsignedBigInteger('fund_account_id')->nullable();
            $table->date('expense_date');
            $table->text('note')->nullable();
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('expense_category_id')->nullable();
            $table->timestamps();
        });

        // 28. Tabel expense_categories
        Schema::create('expense_categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->unsignedBigInteger('account_id')->nullable();
            $table->string('image_path')->nullable();
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        // 29. Tabel failed_jobs
        Schema::create('failed_jobs', function (Blueprint $table) {
            $table->id();
            $table->string('uuid')->unique();
            $table->text('connection');
            $table->text('queue');
            $table->longText('payload');
            $table->longText('exception');
            $table->timestamp('failed_at')->useCurrent();
        });

        // 30. Tabel hold_carts
        Schema::create('hold_carts', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('branch_id');
            $table->unsignedBigInteger('user_id');
            $table->string('hold_name');
            $table->integer('customer_id')->nullable();
            $table->string('customer_name')->nullable();
            $table->longText('items_json');
            $table->timestamps();
        });

        // 31. Tabel interbranch_transfers
        Schema::create('interbranch_transfers', function (Blueprint $table) {
            $table->id();
            $table->string('transfer_number', 50)->unique();
            $table->unsignedBigInteger('from_branch_id');
            $table->unsignedBigInteger('to_branch_id')->default(0)->comment('0 = Pusat / Head Office');
            $table->decimal('amount', 15, 2);
            $table->enum('status', ['pending', 'completed', 'rejected'])->default('pending');
            $table->unsignedBigInteger('requested_by');
            $table->unsignedBigInteger('confirmed_by')->nullable();
            $table->text('note')->nullable();
            $table->date('transfer_date');
            $table->timestamps();
        });

        // 32. Tabel jobs
        Schema::create('jobs', function (Blueprint $table) {
            $table->id();
            $table->string('queue')->index();
            $table->longText('payload');
            $table->unsignedTinyInteger('attempts');
            $table->unsignedInteger('reserved_at')->nullable();
            $table->unsignedInteger('available_at');
            $table->unsignedInteger('created_at');
        });

        // 33. Tabel job_batches
        Schema::create('job_batches', function (Blueprint $table) {
            $table->string('id')->primary();
            $table->string('name');
            $table->integer('total_jobs');
            $table->integer('pending_jobs');
            $table->integer('failed_jobs');
            $table->longText('failed_job_ids');
            $table->mediumText('options')->nullable();
            $table->integer('cancelled_at')->nullable();
            $table->integer('created_at');
            $table->integer('finished_at')->nullable();
        });

        // 34. Tabel journal_entries
        Schema::create('journal_entries', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('branch_id');
            $table->date('entry_date');
            $table->text('description')->nullable();
            $table->string('reference')->nullable();
            $table->string('source_type')->nullable();
            $table->unsignedBigInteger('user_id');
            $table->timestamps();
        });

        // 35. Tabel journal_items
        Schema::create('journal_items', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('journal_entry_id');
            $table->unsignedBigInteger('account_id');
            $table->decimal('debit', 15, 2)->default(0.00);
            $table->decimal('credit', 15, 2)->default(0.00);
            $table->timestamps();
        });

        // 36. Tabel market_intelligences
        Schema::create('market_intelligences', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('salesman_visit_id')->comment('Relasi ke Sesi Kunjungan Aktif');
            $table->unsignedBigInteger('competitor_brand_id')->comment('Relasi ke Master Brand Pesaing');
            $table->decimal('share_of_shelf_percent', 5, 2)->default(0.00)->comment('Estimasi Persentase Ruang Pajang Etalase');
            $table->decimal('competitor_price_found', 15, 2)->default(0.00)->comment('Temuan Harga Jual Kompetitor');
            $table->text('competitor_promo_found')->nullable();
            $table->string('shelf_photo_path')->nullable()->comment('Foto Kompresi HP Bukti Etalase Toko');
            $table->text('market_insights_note')->nullable()->comment('Catatan Intelijen Tambahan dari Salesman');
            $table->timestamps();
        });

        // 37. Tabel master_journey_plans
        Schema::create('master_journey_plans', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('salesman_id');
            $table->unsignedBigInteger('customer_id');
            $table->tinyInteger('day_of_week')->comment('1=Senin s/d 6=Sabtu');
            $table->string('frequency_type', 50)->comment('weekly, biweekly_odd, biweekly_even, monthly');
            $table->tinyInteger('week_number')->nullable()->comment('Hanya diisi (1,2,3,4) jika tipe monthly');
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        // 38. Tabel model_has_permissions
        Schema::create('model_has_permissions', function (Blueprint $table) {
            $table->unsignedBigInteger('permission_id');
            $table->string('model_type');
            $table->unsignedBigInteger('model_id');
            $table->primary(['permission_id', 'model_id', 'model_type']);
            $table->index(['model_id', 'model_type']);
        });

        // 39. Tabel model_has_roles
        Schema::create('model_has_roles', function (Blueprint $table) {
            $table->unsignedBigInteger('role_id');
            $table->string('model_type');
            $table->unsignedBigInteger('model_id');
            $table->primary(['role_id', 'model_id', 'model_type']);
            $table->index(['model_id', 'model_type']);
        });

        // 40. Tabel monthly_stock_balances
        Schema::create('monthly_stock_balances', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('branch_id');
            $table->unsignedBigInteger('product_id');
            $table->date('period');
            $table->decimal('last_stock_qty', 15, 2);
            $table->unsignedBigInteger('user_id');
            $table->timestamps();
            $table->unique(['branch_id', 'product_id', 'period'], 'monthly_stock_balances_unique');
        });

        // 41. Tabel no_order_reasons
        Schema::create('no_order_reasons', function (Blueprint $table) {
            $table->id();
            $table->string('reason_name', 100);
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        // 42. Tabel otp_requests
        Schema::create('otp_requests', function (Blueprint $table) {
            $table->id();
            $table->string('phone_number')->index();
            $table->string('otp_code', 10);
            $table->timestamp('expires_at');
            $table->boolean('is_used')->default(false);
            $table->timestamps();
        });

        // 43. Tabel password_reset_tokens
        // PERBAIKAN: Mengubah email menjadi username
        Schema::create('password_reset_tokens', function (Blueprint $table) {
            $table->string('username')->primary(); 
            $table->string('token');
            $table->timestamp('created_at')->nullable();
        });

        // 44. Tabel permissions
        Schema::create('permissions', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('guard_name');
            $table->timestamps();
            $table->unique(['name', 'guard_name']);
        });

        // 45. Tabel personal_access_tokens
        Schema::create('personal_access_tokens', function (Blueprint $table) {
            $table->id();
            $table->string('tokenable_type');
            $table->unsignedBigInteger('tokenable_id');
            $table->text('name');
            $table->string('token', 64)->unique();
            $table->text('abilities')->nullable();
            $table->timestamp('last_used_at')->nullable();
            $table->timestamp('expires_at')->nullable();
            $table->timestamps();
            $table->index(['tokenable_type', 'tokenable_id']);
        });

        // 46. Tabel point_histories
        Schema::create('point_histories', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('customer_id');
            $table->unsignedBigInteger('sale_id')->nullable();
            $table->string('type');
            $table->integer('points');
            $table->decimal('transaction_amount', 15, 2)->default(0.00);
            $table->timestamps();
        });

        // 47. Tabel products
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('sku')->nullable();
            $table->unsignedBigInteger('category_id')->nullable();
            $table->string('name');
            $table->string('unit');
            $table->integer('price_reference_level')->default(1);
            $table->string('buy_unit')->nullable();
            $table->decimal('conversion_factor', 10, 2)->default(1.00);
            $table->string('unit_3_name')->nullable();
            $table->decimal('conversion_3_qty', 10, 2)->nullable();
            $table->string('unit_4_name')->nullable();
            $table->decimal('conversion_4_qty', 10, 2)->nullable();
            $table->string('image_path')->nullable();
            $table->decimal('stock_qty', 15, 4)->default(0.0000);
            $table->boolean('is_active')->default(true);
            $table->boolean('is_available_online')->default(true);
            $table->string('variant_group_id')->nullable()->index();
            $table->string('variant_name')->nullable();
            $table->decimal('buy_price', 15, 2)->default(0.00);
            $table->decimal('average_cost', 15, 2)->default(0.00);
            $table->timestamps();
        });

        // 48. Tabel product_prices
        Schema::create('product_prices', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('product_id');
            $table->string('level');
            $table->integer('unit_level')->default(1);
            $table->decimal('amount', 15, 2);
            $table->decimal('min_online_qty', 10, 2)->nullable();
            $table->decimal('amount_conversion', 15, 2)->nullable();
            $table->decimal('price_l3', 15, 2)->default(0.00);
            $table->decimal('price_l4', 15, 2)->default(0.00);
            $table->timestamps();
        });

        // 49. Tabel product_stocks
        Schema::create('product_stocks', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('product_id');
            $table->unsignedBigInteger('variant_id')->nullable();
            $table->unsignedBigInteger('branch_id');
            $table->decimal('quantity', 10, 2)->default(0.00);
            $table->decimal('reserved_qty', 10, 2)->default(0.00);
            $table->decimal('bs_quantity', 10, 2)->default(0.00);
            $table->timestamps();
        });

        // 50. Tabel provinces
        Schema::create('provinces', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });

        // 51. Tabel purchases
        Schema::create('purchases', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('branch_id');
            $table->unsignedBigInteger('supplier_id');
            $table->unsignedBigInteger('user_id');
            $table->string('invoice_number')->nullable();
            $table->string('po_number')->nullable();
            $table->date('po_date')->nullable();
            $table->string('receipt_number')->nullable();
            $table->date('receipt_date')->nullable();
            $table->enum('status', ['draft_po', 'received', 'invoiced', 'canceled'])->default('draft_po');
            $table->enum('receipt_status', ['none', 'partial', 'completed'])->default('none');
            $table->date('purchase_date');
            $table->enum('payment_status', ['paid', 'pending', 'partial'])->default('paid');
            $table->integer('term_days')->default(0);
            $table->boolean('is_initial_debt')->default(false);
            $table->date('due_date')->nullable();
            $table->decimal('subtotal', 15, 2);
            $table->string('tax_method')->default('non');
            $table->decimal('tax_amount', 15, 2)->default(0.00);
            $table->decimal('other_costs', 15, 2)->default(0.00);
            $table->enum('tax_type', ['non', 'include', 'exclude'])->default('non');
            $table->enum('payment_method', ['cash', 'credit'])->default('cash');
            $table->decimal('discount_amount', 15, 2)->default(0.00);
            $table->decimal('grand_total', 15, 2);
            $table->decimal('paid_amount', 15, 2)->default(0.00);
            $table->decimal('dp_amount', 15, 2)->default(0.00);
            $table->unsignedBigInteger('dp_account_id')->nullable();
            $table->text('notes')->nullable();
            $table->timestamps();
        });

        // 52. Tabel purchase_items
        Schema::create('purchase_items', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('purchase_id');
            $table->unsignedBigInteger('product_id');
            $table->integer('quantity');
            $table->decimal('qty_received', 15, 2)->default(0.00);
            $table->string('unit');
            $table->decimal('conversion_value', 10, 2)->default(1.00);
            $table->decimal('unit_price', 15, 2);
            $table->string('discount_string')->nullable();
            $table->decimal('discount_amount', 15, 2)->default(0.00);
            $table->decimal('total_price', 15, 2);
            $table->decimal('dpp_amount', 15, 2)->default(0.00);
            $table->decimal('tax_amount', 15, 2)->default(0.00);
            $table->boolean('is_bonus')->default(false);
            $table->timestamps();
        });

        // 53. Tabel purchase_receipts
        Schema::create('purchase_receipts', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('purchase_id');
            $table->unsignedBigInteger('branch_id');
            $table->unsignedBigInteger('user_id');
            $table->string('receipt_number', 50)->unique();
            $table->string('supplier_delivery_number', 100)->nullable();
            $table->date('receipt_date');
            $table->text('notes')->nullable();
            $table->timestamps();
        });

        // 54. Tabel purchase_receipt_items
        Schema::create('purchase_receipt_items', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('purchase_receipt_id');
            $table->unsignedBigInteger('product_id');
            $table->unsignedBigInteger('purchase_item_id')->nullable();
            $table->boolean('is_bonus')->default(false);
            $table->decimal('qty_received', 15, 2);
            $table->string('unit', 50);
            $table->decimal('conversion_value', 15, 2)->default(1.00);
            $table->timestamps();
        });

        // 55. Tabel purchase_returns
        Schema::create('purchase_returns', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('branch_id');
            $table->unsignedBigInteger('supplier_id');
            $table->unsignedBigInteger('purchase_id');
            $table->unsignedBigInteger('user_id');
            $table->string('return_number')->unique();
            $table->date('return_date');
            $table->enum('return_type', ['deduct_payable', 'cash_refund', 'replacement']);
            $table->unsignedBigInteger('refund_account_id')->nullable();
            $table->enum('refund_status', ['none', 'pending', 'received'])->default('none');
            $table->enum('replacement_status', ['none', 'pending', 'received'])->default('none');
            $table->decimal('total_amount', 15, 2)->default(0.00);
            $table->text('notes')->nullable();
            $table->timestamps();
        });

        // 56. Tabel purchase_return_items
        Schema::create('purchase_return_items', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('purchase_return_id');
            $table->unsignedBigInteger('purchase_item_id');
            $table->unsignedBigInteger('product_id');
            $table->decimal('quantity', 10, 2);
            $table->string('unit');
            $table->decimal('conversion_value', 10, 2)->default(1.00);
            $table->decimal('unit_price', 15, 2);
            $table->decimal('total_price', 15, 2);
            $table->timestamps();
        });

        // 57. Tabel roles
        Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('guard_name');
            $table->timestamps();
            $table->unique(['name', 'guard_name']);
        });

        // 58. Tabel role_has_permissions
        Schema::create('role_has_permissions', function (Blueprint $table) {
            $table->unsignedBigInteger('permission_id');
            $table->unsignedBigInteger('role_id');
            $table->primary(['permission_id', 'role_id']);
        });

        // 59. Tabel sales
        Schema::create('sales', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('sales_order_id')->nullable();
            $table->unsignedBigInteger('sales_invoice_id')->nullable();
            $table->unsignedBigInteger('branch_id');
            $table->unsignedBigInteger('user_id');
            $table->string('invoice_number')->unique();
            $table->decimal('subtotal', 15, 2);
            $table->decimal('discount_amount', 15, 2)->default(0.00);
            $table->decimal('tax_amount', 15, 2)->default(0.00);
            $table->decimal('grand_total', 15, 2);
            $table->decimal('paid_amount', 15, 2)->default(0.00);
            $table->string('payment_method')->default('cash');
            $table->integer('due_days')->default(0)->nullable();
            $table->string('payment_status')->default('paid');
            $table->boolean('is_online_order')->default(false);
            $table->decimal('delivery_lat', 10, 8)->nullable();
            $table->decimal('delivery_lng', 11, 8)->nullable();
            $table->decimal('shipping_fee', 15, 2)->default(0.00);
            $table->unsignedBigInteger('driver_id')->nullable();
            $table->unsignedBigInteger('helper_id')->nullable();
            $table->string('delivery_status')->default('pending');
            $table->integer('print_count')->default(0);
            $table->date('delivery_date')->nullable();
            $table->text('failed_reason')->nullable();
            $table->string('pod_photo')->nullable();
            $table->decimal('pod_lat', 10, 8)->nullable();
            $table->decimal('pod_lng', 11, 8)->nullable();
            $table->boolean('is_initial_debt')->default(false);
            $table->date('due_date')->nullable();
            $table->string('customer_name')->nullable();
            $table->text('shipping_address')->nullable();
            $table->unsignedBigInteger('customer_id')->nullable();
            $table->timestamps();
        });

        // 60. Tabel salesman_targets
        Schema::create('salesman_targets', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('salesman_id');
            $table->unsignedBigInteger('branch_id');
            $table->date('start_date');
            $table->date('end_date');
            $table->decimal('target_value_rp', 15, 2)->default(0.00);
            $table->enum('status', ['active', 'closed'])->default('active');
            $table->text('notes')->nullable();
            $table->unsignedBigInteger('created_by');
            $table->boolean('is_value_target')->default(false)->nullable();
            $table->boolean('is_quantity_target')->default(false)->nullable();
            $table->timestamps();
        });

        // 61. Tabel salesman_target_items
        Schema::create('salesman_target_items', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('target_id');
            $table->enum('target_type', ['product', 'category', 'all_product']);
            $table->unsignedBigInteger('reference_id');
            $table->decimal('target_qty', 15, 2);
            $table->string('unit', 50);
        });

        // 62. Tabel salesman_visits
        Schema::create('salesman_visits', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('salesman_id');
            $table->unsignedBigInteger('customer_id');
            $table->date('visit_date');
            $table->enum('visit_category', ['scheduled', 'extra_call']);
            $table->string('visit_status', 50)->default('pending');
            $table->boolean('is_out_of_radius')->default(false);
            $table->decimal('distance_meters', 8, 2)->unsigned()->default(0.00);
            $table->timestamp('verified_at')->nullable();
            $table->dateTime('check_in_time')->nullable();
            $table->decimal('check_in_lat', 10, 8)->nullable();
            $table->decimal('check_in_lng', 11, 8)->nullable();
            $table->dateTime('check_out_time')->nullable();
            $table->string('visit_result', 20)->default('pending');
            $table->unsignedBigInteger('no_order_reason_id')->nullable();
            $table->string('no_order_reason')->nullable();
            $table->string('photo_proof')->nullable();
            $table->string('competitor_photo')->nullable();
            $table->text('market_notes')->nullable();
            $table->string('check_out_lat', 50)->nullable();
            $table->string('check_out_lng', 50)->nullable();
            $table->timestamps();
        });

        // 63. Tabel salesmen
        Schema::create('salesmen', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('supervisor_id')->nullable();
            $table->string('code')->unique();
            $table->enum('salesman_type', ['TO', 'CANVAS'])->default('TO');
            $table->string('area_cakupan')->nullable();
            $table->decimal('last_latitude', 10, 8)->nullable();
            $table->decimal('last_longitude', 11, 8)->nullable();
            $table->timestamp('last_activity_at')->nullable();
            $table->timestamps();
        });

        // 64. Tabel sales_invoices
        Schema::create('sales_invoices', function (Blueprint $table) {
            $table->id();
            $table->string('invoice_number', 100)->unique();
            $table->unsignedBigInteger('branch_id');
            $table->unsignedBigInteger('customer_id');
            $table->string('customer_name');
            $table->decimal('subtotal', 15, 2)->default(0.00);
            $table->decimal('discount_amount', 15, 2)->default(0.00);
            $table->decimal('dpp', 15, 2)->default(0.00);
            $table->decimal('tax_amount', 15, 2)->default(0.00);
            $table->decimal('grand_total', 15, 2)->default(0.00);
            $table->decimal('total_cogs', 15, 2)->default(0.00);
            $table->enum('payment_status', ['unpaid', 'partial', 'paid'])->default('unpaid');
            $table->date('due_date')->nullable();
            $table->unsignedBigInteger('journal_id')->nullable();
            $table->unsignedBigInteger('created_by');
            $table->text('note')->nullable();
            $table->timestamps();
        });

        // 65. Tabel sales_orders
        Schema::create('sales_orders', function (Blueprint $table) {
            $table->id();
            $table->string('so_number')->unique();
            $table->unsignedBigInteger('branch_id');
            $table->unsignedBigInteger('fulfillment_branch_id')->nullable();
            $table->unsignedBigInteger('customer_id')->nullable();
            $table->unsignedBigInteger('user_id')->nullable();
            $table->unsignedBigInteger('salesman_id')->nullable();
            $table->string('customer_name');
            $table->string('customer_phone')->nullable();
            $table->text('shipping_address')->nullable();
            $table->decimal('delivery_lat', 10, 8)->nullable();
            $table->decimal('delivery_lng', 11, 8)->nullable();
            $table->decimal('subtotal', 15, 2);
            $table->decimal('shipping_fee', 15, 2)->default(0.00);
            $table->decimal('global_discount_nominal', 15, 2)->default(0.00);
            $table->unsignedBigInteger('applied_program_id')->nullable();
            $table->decimal('discount_amount', 15, 2)->default(0.00);
            $table->decimal('grand_total', 15, 2);
            $table->string('payment_method')->default('cash');
            $table->integer('due_days')->default(0)->nullable();
            $table->string('status', 50)->default('pending');
            $table->text('note')->nullable();
            $table->date('delivery_date')->nullable();
            $table->timestamps();
        });

        // 66. Tabel sales_order_items
        Schema::create('sales_order_items', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('sales_order_id');
            $table->unsignedBigInteger('product_id');
            $table->string('unit_name');
            $table->decimal('qty', 10, 2);
            $table->decimal('qty_delivered', 10, 2)->default(0.00);
            $table->decimal('price', 15, 2);
            $table->decimal('discount_nominal', 15, 2)->default(0.00);
            $table->decimal('total_price', 15, 2);
            $table->boolean('is_free_item')->default(false);
            $table->unsignedBigInteger('applied_program_id')->nullable();
            $table->timestamps();
        });

        // 67. Tabel sales_programs
        Schema::create('sales_programs', function (Blueprint $table) {
            $table->id();
            $table->string('nama_program');
            $table->date('start_date');
            $table->date('end_date');
            $table->json('target_customer_levels')->nullable();
            $table->longText('target_customer_types')->nullable();
            $table->enum('scope', ['product', 'category', 'global']);
            $table->unsignedBigInteger('category_id')->nullable();
            $table->unsignedBigInteger('product_id')->nullable();
            $table->decimal('min_qty', 10, 2)->default(0.00);
            $table->decimal('min_amount', 15, 2)->default(0.00);
            $table->decimal('discount_percent', 5, 2)->default(0.00);
            $table->decimal('discount_nominal', 15, 2)->default(0.00);
            $table->unsignedBigInteger('free_product_id')->nullable();
            $table->decimal('free_qty', 10, 2)->default(0.00);
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        // 68. Tabel sales_program_tiers
        Schema::create('sales_program_tiers', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('sales_program_id');
            $table->decimal('min_qty', 10, 2)->default(0.00);
            $table->decimal('max_qty', 10, 2)->default(0.00);
            $table->string('reward_type');
            $table->string('reward_value')->nullable();
            $table->boolean('is_multiple')->default(false);
            $table->unsignedBigInteger('bonus_product_id')->nullable();
            $table->decimal('bonus_qty', 10, 2)->default(0.00);
            $table->timestamps();
        });

        // 69. Tabel sales_returns
        Schema::create('sales_returns', function (Blueprint $table) {
            $table->id();
            $table->string('return_number', 50)->unique();
            $table->unsignedBigInteger('branch_id');
            $table->unsignedBigInteger('customer_id');
            $table->unsignedBigInteger('sales_invoice_id')->nullable();
            $table->unsignedBigInteger('created_by');
            $table->enum('status', ['draft', 'pending', 'received', 'completed', 'cancelled'])->default('pending');
            $table->decimal('total_refund_value', 15, 2)->default(0.00)->nullable();
            $table->text('note')->nullable();
            $table->timestamps();
        });

        // 70. Tabel sales_return_items
        Schema::create('sales_return_items', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('sales_return_id');
            $table->unsignedBigInteger('product_id');
            $table->decimal('qty_planned', 15, 2);
            $table->decimal('qty_received', 15, 2)->default(0.00)->nullable();
            $table->string('unit_name', 50);
            $table->decimal('price_at_invoice', 15, 2);
            $table->string('reason', 255)->nullable();
            $table->enum('condition', ['good', 'bad'])->default('good')->nullable();
        });

        // 71. Tabel sale_items
        Schema::create('sale_items', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('sale_id');
            $table->unsignedBigInteger('product_id');
            $table->string('product_name');
            $table->decimal('quantity', 10, 2);
            $table->string('unit')->nullable();
            $table->decimal('unit_price', 15, 2);
            $table->decimal('total_price', 15, 2);
            $table->string('applied_price_level')->nullable();
            $table->decimal('base_conversion_factor', 10, 2);
            $table->timestamps();
        });

        // 72. Tabel sessions
        Schema::create('sessions', function (Blueprint $table) {
            $table->string('id')->primary();
            $table->unsignedBigInteger('user_id')->nullable()->index();
            $table->string('ip_address', 45)->nullable();
            $table->text('user_agent')->nullable();
            $table->longText('payload');
            $table->integer('last_activity')->index();
        });

        // 73. Tabel settings
        Schema::create('settings', function (Blueprint $table) {
            $table->id();
            $table->string('key')->unique();
            $table->string('label');
            $table->string('value')->nullable();
            $table->string('type')->default('number');
            $table->timestamps();
        });

        // 74. Tabel stock_adjustments
        Schema::create('stock_adjustments', function (Blueprint $table) {
            $table->id();
            $table->string('adjustment_number', 50)->unique();
            $table->unsignedBigInteger('branch_id');
            $table->date('adjustment_date');
            $table->decimal('total_surplus_value', 15, 2)->default(0.00);
            $table->decimal('total_deficit_value', 15, 2)->default(0.00);
            $table->text('notes')->nullable();
            $table->unsignedBigInteger('created_by');
            $table->timestamps();
        });

        // 75. Tabel stock_adjustment_items
        Schema::create('stock_adjustment_items', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('stock_adjustment_id');
            $table->unsignedBigInteger('product_id');
            $table->decimal('system_qty', 15, 2);
            $table->decimal('actual_qty', 15, 2);
            $table->decimal('variance_qty', 15, 2);
            $table->string('unit', 50);
            $table->decimal('unit_price', 15, 2);
            $table->enum('variance_type', ['surplus', 'deficit', 'match']);
        });

        // 76. Tabel stock_transactions
        Schema::create('stock_transactions', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('branch_id');
            $table->unsignedBigInteger('product_id');
            $table->string('type');
            $table->decimal('input_quantity', 10, 2);
            $table->string('input_unit');
            $table->decimal('actual_quantity', 10, 2);
            $table->text('note')->nullable();
            $table->unsignedBigInteger('user_id');
            $table->timestamps();
        });

        // 77. Tabel stock_transfers
        Schema::create('stock_transfers', function (Blueprint $table) {
            $table->id();
            $table->string('transfer_number', 50);
            $table->unsignedBigInteger('from_branch_id');
            $table->unsignedBigInteger('to_branch_id');
            $table->date('transfer_date');
            $table->enum('transfer_type', ['direct', 'transit'])->default('direct');
            $table->enum('status', ['completed', 'in_transit'])->default('completed');
            $table->text('notes')->nullable();
            $table->unsignedBigInteger('created_by');
            $table->timestamps();
        });

        // 78. Tabel stock_transfer_items
        Schema::create('stock_transfer_items', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('stock_transfer_id');
            $table->unsignedBigInteger('product_id');
            $table->decimal('qty', 15, 2);
        });

        // 79. Tabel stock_write_offs
        Schema::create('stock_write_offs', function (Blueprint $table) {
            $table->id();
            $table->string('write_off_number', 50)->unique();
            $table->unsignedBigInteger('branch_id');
            $table->decimal('total_loss_value', 15, 2)->default(0.00);
            $table->text('notes')->nullable();
            $table->unsignedBigInteger('created_by');
            $table->timestamps();
        });

        // 80. Tabel stock_write_off_items
        Schema::create('stock_write_off_items', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('stock_write_off_id');
            $table->unsignedBigInteger('product_id');
            $table->decimal('qty', 15, 2);
            $table->string('unit', 50);
            $table->decimal('unit_price', 15, 2);
            $table->enum('source_type', ['sales_return', 'internal_damage'])->default('internal_damage');
            $table->unsignedBigInteger('reference_id')->nullable();
        });

        // 81. Tabel suppliers
        Schema::create('suppliers', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('contact_person')->nullable();
            $table->string('phone')->nullable();
            $table->text('address')->nullable();
            $table->string('email')->nullable();
            $table->boolean('is_pkp')->default(false);
            $table->string('npwp')->nullable();
            $table->text('bank_account_info')->nullable();
            $table->string('term_of_payment')->default('0');
            $table->timestamps();
        });

        // 82. Tabel users
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            // PERBAIKAN: Ubah email menjadi username
            $table->string('username')->unique(); 
            $table->string('whatsapp', 20)->nullable();
            $table->string('role', 50);
            $table->unsignedBigInteger('branch_id')->nullable();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('remember_token', 100)->nullable();
            $table->timestamps();
        });

        // 83. Tabel vehicles
        Schema::create('vehicles', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('license_plate')->unique();
            $table->string('type');
            $table->integer('max_weight')->default(0);
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        // MENGAKTIFKAN KEMBALI FOREIGN KEY CONSTRAINT SETELAH SEMUA TABEL TERBUAT
        Schema::enableForeignKeyConstraints();
    }

    public function down(): void
    {
        // Mematikan konstrain foreign key untuk menghindari error saat melakukan rollback (drop table)
        Schema::disableForeignKeyConstraints();
        
        $tables = [
            'accounting_periods', 'accounting_settings', 'accounts', 'app_settings', 'armadas', 'banners', 
            'branches', 'branch_accounts', 'branch_product', 'cache', 'cache_locks', 'canvas_loadings', 
            'canvas_loading_items', 'canvas_stocks', 'cash_mutations', 'categories', 'cities', 'competitor_brands', 
            'customers', 'customer_types', 'daily_shifts', 'debt_payments', 'delivery_logs', 'delivery_zones', 
            'districts', 'driver_assignments', 'expenses', 'expense_categories', 'failed_jobs', 'hold_carts', 
            'interbranch_transfers', 'jobs', 'job_batches', 'journal_entries', 'journal_items', 'market_intelligences', 
            'master_journey_plans', 'model_has_permissions', 'model_has_roles', 'monthly_stock_balances', 
            'no_order_reasons', 'otp_requests', 'password_reset_tokens', 'permissions', 'personal_access_tokens', 
            'point_histories', 'products', 'product_prices', 'product_stocks', 'provinces', 'purchases', 
            'purchase_items', 'purchase_receipts', 'purchase_receipt_items', 'purchase_returns', 'purchase_return_items', 
            'roles', 'role_has_permissions', 'sales', 'salesman_targets', 'salesman_target_items', 'salesman_visits', 
            'salesmen', 'sales_invoices', 'sales_orders', 'sales_order_items', 'sales_programs', 'sales_program_tiers', 
            'sales_returns', 'sales_return_items', 'sale_items', 'sessions', 'settings', 'stock_adjustments', 
            'stock_adjustment_items', 'stock_transactions', 'stock_transfers', 'stock_transfer_items', 
            'stock_write_offs', 'stock_write_off_items', 'suppliers', 'users', 'vehicles'
        ];

        foreach ($tables as $table) {
            Schema::dropIfExists($table);
        }
        
        Schema::enableForeignKeyConstraints();
    }
};