<?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 {
        Schema::create('branches', function (Blueprint $table) {
            $table->id();
            $table->string('name'); $table->string('code')->unique(); $table->string('type')->default('Branch');
            $table->string('address')->nullable(); $table->string('phone')->nullable(); $table->string('email')->nullable(); $table->string('manager_name')->nullable();
            $table->string('invoice_prefix')->nullable(); $table->string('status')->default('Active');
            $table->boolean('is_head_office')->default(false); $table->boolean('is_central_warehouse')->default(false);
            $table->timestamps();
        });
        Schema::create('branch_product_stocks', function (Blueprint $table) {
            $table->id(); $table->foreignId('branch_id')->constrained('branches')->cascadeOnDelete(); $table->foreignId('product_id')->constrained('products')->cascadeOnDelete();
            $table->decimal('stock_qty',14,2)->default(0); $table->decimal('reorder_qty',14,2)->default(0); $table->decimal('selling_price',14,2)->nullable(); $table->decimal('wholesale_price',14,2)->nullable();
            $table->timestamps(); $table->unique(['branch_id','product_id']);
        });
        Schema::create('warranties', function (Blueprint $table) {
            $table->id(); $table->foreignId('customer_id')->nullable()->constrained('customers')->nullOnDelete(); $table->string('sale_invoice_no')->nullable();
            $table->foreignId('product_id')->constrained('products')->cascadeOnDelete(); $table->string('serial_no')->nullable(); $table->integer('warranty_period_months')->default(0);
            $table->date('start_date'); $table->date('end_date'); $table->string('status')->default('Active'); $table->text('notes')->nullable(); $table->timestamps();
        });
        Schema::create('service_claims', function (Blueprint $table) {
            $table->id(); $table->string('claim_no')->unique(); $table->foreignId('customer_id')->nullable()->constrained('customers')->nullOnDelete();
            $table->foreignId('warranty_id')->nullable()->constrained('warranties')->nullOnDelete(); $table->foreignId('product_id')->constrained('products')->cascadeOnDelete();
            $table->foreignId('branch_id')->nullable()->constrained('branches')->nullOnDelete(); $table->string('issue_title'); $table->text('issue_details')->nullable();
            $table->string('repair_ticket_no')->nullable(); $table->string('technician_name')->nullable(); $table->string('status')->default('Received'); $table->decimal('service_cost',14,2)->default(0);
            $table->unsignedBigInteger('replacement_product_id')->nullable(); $table->dateTime('received_at')->nullable(); $table->dateTime('delivered_at')->nullable(); $table->text('notes')->nullable(); $table->timestamps();
        });
        Schema::create('installment_sales', function (Blueprint $table) {
            $table->id(); $table->string('sale_invoice_no')->nullable(); $table->foreignId('customer_id')->constrained('customers')->cascadeOnDelete(); $table->foreignId('branch_id')->nullable()->constrained('branches')->nullOnDelete();
            $table->decimal('principal_amount',14,2)->default(0); $table->decimal('down_payment',14,2)->default(0); $table->decimal('installment_amount',14,2)->default(0); $table->integer('installment_count')->default(1);
            $table->integer('interval_days')->default(30); $table->date('start_date'); $table->decimal('penalty_per_late_day',14,2)->default(0); $table->string('status')->default('Active'); $table->text('notes')->nullable(); $table->timestamps();
        });
        Schema::create('installment_payments', function (Blueprint $table) {
            $table->id(); $table->foreignId('installment_sale_id')->constrained('installment_sales')->cascadeOnDelete(); $table->date('scheduled_date'); $table->date('paid_date')->nullable();
            $table->decimal('amount_due',14,2)->default(0); $table->decimal('amount_paid',14,2)->default(0); $table->decimal('late_fee',14,2)->default(0); $table->string('status')->default('Pending'); $table->text('notes')->nullable(); $table->timestamps();
        });
        Schema::create('dealers', function (Blueprint $table) {
            $table->id(); $table->string('name'); $table->string('code')->unique(); $table->string('phone')->nullable(); $table->string('email')->nullable(); $table->string('address')->nullable();
            $table->string('area_name')->nullable(); $table->string('dealer_type')->default('Dealer'); $table->decimal('commission_percent',8,2)->default(0); $table->decimal('credit_limit',14,2)->default(0);
            $table->string('status')->default('Active'); $table->unsignedTinyInteger('rating')->nullable(); $table->text('notes')->nullable(); $table->timestamps();
        });
        Schema::create('dealer_ledgers', function (Blueprint $table) {
            $table->id(); $table->foreignId('dealer_id')->constrained('dealers')->cascadeOnDelete(); $table->date('txn_date'); $table->string('reference_no')->nullable(); $table->string('type');
            $table->decimal('debit',14,2)->default(0); $table->decimal('credit',14,2)->default(0); $table->text('notes')->nullable(); $table->timestamps();
        });
        Schema::create('staff', function (Blueprint $table) {
            $table->id(); $table->foreignId('branch_id')->nullable()->constrained('branches')->nullOnDelete(); $table->string('name'); $table->string('employee_code')->unique(); $table->string('phone')->nullable(); $table->string('email')->nullable();
            $table->string('designation')->nullable(); $table->string('department')->nullable(); $table->decimal('salary',14,2)->default(0); $table->decimal('commission_percent',8,2)->default(0); $table->decimal('incentive_amount',14,2)->default(0);
            $table->string('status')->default('Active'); $table->date('join_date')->nullable(); $table->decimal('kpi_target_amount',14,2)->default(0); $table->text('notes')->nullable(); $table->timestamps();
        });
        Schema::create('staff_attendances', function (Blueprint $table) {
            $table->id(); $table->foreignId('staff_id')->constrained('staff')->cascadeOnDelete(); $table->date('attendance_date'); $table->string('status')->default('Present'); $table->string('check_in')->nullable(); $table->string('check_out')->nullable(); $table->text('notes')->nullable(); $table->timestamps(); $table->unique(['staff_id','attendance_date']);
        });
        Schema::create('salary_payments', function (Blueprint $table) {
            $table->id(); $table->foreignId('staff_id')->constrained('staff')->cascadeOnDelete(); $table->string('payment_month'); $table->decimal('gross_salary',14,2)->default(0); $table->decimal('commission_amount',14,2)->default(0); $table->decimal('incentive_amount',14,2)->default(0); $table->decimal('deduction_amount',14,2)->default(0); $table->decimal('net_salary',14,2)->default(0); $table->date('paid_date'); $table->string('payment_method')->nullable(); $table->text('notes')->nullable(); $table->timestamps();
        });
        Schema::create('audit_logs', function (Blueprint $table) {
            $table->id(); $table->unsignedBigInteger('admin_id')->nullable(); $table->unsignedBigInteger('branch_id')->nullable(); $table->string('module'); $table->string('action'); $table->string('reference_no')->nullable(); $table->json('old_values')->nullable(); $table->json('new_values')->nullable(); $table->string('ip_address')->nullable(); $table->string('user_agent')->nullable(); $table->timestamps();
        });
        Schema::create('login_logs', function (Blueprint $table) {
            $table->id(); $table->unsignedBigInteger('admin_id')->nullable(); $table->string('email')->nullable(); $table->string('status')->default('Success'); $table->string('ip_address')->nullable(); $table->string('user_agent')->nullable(); $table->string('notes')->nullable(); $table->timestamps();
        });
        Schema::create('suspicious_activities', function (Blueprint $table) {
            $table->id(); $table->unsignedBigInteger('admin_id')->nullable(); $table->string('module')->nullable(); $table->string('activity_type'); $table->string('risk_level')->default('Medium'); $table->string('reference_no')->nullable(); $table->text('details')->nullable(); $table->dateTime('resolved_at')->nullable(); $table->timestamps();
        });
        Schema::create('backup_snapshots', function (Blueprint $table) {
            $table->id(); $table->string('title'); $table->string('file_path')->nullable(); $table->string('status')->default('Ready'); $table->text('notes')->nullable(); $table->unsignedBigInteger('created_by')->nullable(); $table->timestamps();
        });
        Schema::create('automation_runs', function (Blueprint $table) {
            $table->id(); $table->string('automation_key'); $table->date('run_date'); $table->string('status')->default('Completed'); $table->text('result_summary')->nullable(); $table->timestamps();
        });
        Schema::create('customer_follow_ups', function (Blueprint $table) {
            $table->id(); $table->foreignId('customer_id')->constrained('customers')->cascadeOnDelete(); $table->date('followup_date'); $table->string('type')->default('Sales Followup'); $table->text('notes')->nullable(); $table->string('status')->default('Pending'); $table->timestamps();
        });
        foreach ([['admins','branch_id'],['sales','branch_id'],['purchases','branch_id'],['conveyance_bills','branch_id']] as [$table,$col]) {
            if (!Schema::hasColumn($table, $col)) Schema::table($table, function(Blueprint $table) use ($col){ $table->unsignedBigInteger($col)->nullable()->after('id'); });
        }
        if (!Schema::hasColumn('admins','two_factor_enabled')) Schema::table('admins', function(Blueprint $table){ $table->boolean('two_factor_enabled')->default(false)->after('status'); });
        if (!Schema::hasColumn('products','warranty_months')) Schema::table('products', function(Blueprint $table){ $table->integer('warranty_months')->default(0)->after('selling_price'); $table->decimal('dealer_price',14,2)->nullable()->after('selling_price'); });
        if (!Schema::hasColumn('customers','dealer_id')) Schema::table('customers', function(Blueprint $table){ $table->unsignedBigInteger('dealer_id')->nullable()->after('id'); });
    }
    public function down(): void {
        foreach (['customer_follow_ups','automation_runs','backup_snapshots','suspicious_activities','login_logs','audit_logs','salary_payments','staff_attendances','staff','dealer_ledgers','dealers','installment_payments','installment_sales','service_claims','warranties','branch_product_stocks','branches'] as $table) { Schema::dropIfExists($table); }
    }
};
