<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // ============================================
        // PURCHASES TABLES
        // ============================================
        
        // Main purchases table
        Schema::create('purchases', function (Blueprint $table) {
            $table->id();
            $table->string('purchase_number')->unique(); // PUR-0001, PUR-0002
            $table->foreignId('supplier_id')->constrained('suppliers')->onDelete('cascade');
            $table->foreignId('created_by')->constrained('users')->onDelete('cascade'); // Staff who created
            $table->date('purchase_date');
            $table->decimal('subtotal', 12, 2); // Total before tax
            $table->decimal('tax_amount', 10, 2)->default(0);
            $table->decimal('discount', 10, 2)->default(0);
            $table->decimal('total_amount', 12, 2); // Final total
            $table->decimal('paid_amount', 12, 2)->default(0);
            $table->decimal('due_amount', 12, 2)->default(0);
            $table->enum('payment_status', ['pending', 'partial', 'paid'])->default('pending');
            $table->enum('status', ['draft', 'completed', 'cancelled'])->default('completed');
            $table->string('reference_number')->nullable(); // Supplier invoice number
            $table->text('notes')->nullable();
            $table->timestamps();

            // Indexes
            $table->index('purchase_number');
            $table->index('supplier_id');
            $table->index('purchase_date');
            $table->index('payment_status');
            $table->index('status');
        });

        // Purchase items (details)
        Schema::create('purchase_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('purchase_id')->constrained('purchases')->onDelete('cascade');
            $table->foreignId('inventory_id')->constrained('inventory')->onDelete('cascade');
            $table->integer('quantity');
            $table->boolean('is_device')
                ->default(false);
            $table->decimal('unit_price', 10, 2); // Purchase price per unit
            $table->decimal('subtotal', 10, 2); // quantity * unit_price
            $table->timestamps();

            // Indexes
            $table->index('purchase_id');
            $table->index('inventory_id');
        });

        // Purchase payments (track all payments for a purchase)
        Schema::create('purchase_payments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('purchase_id')->constrained('purchases')->onDelete('cascade');
            $table->decimal('amount', 10, 2);
            $table->date('payment_date');
            $table->enum('payment_method', ['cash', 'bank_transfer', 'cheque', 'card'])->default('cash');
            $table->string('reference_number')->nullable(); // Cheque number, transaction ID
            $table->text('notes')->nullable();
            $table->foreignId('received_by')->constrained('users')->onDelete('cascade'); // Staff who received payment
            $table->timestamps();

            // Indexes
            $table->index('purchase_id');
            $table->index('payment_date');
            $table->index('payment_method');
        });


        // Schema::create('devices', function (Blueprint $table) {
        //     $table->id();

        //     // inventory item this device belongs to
        //     $table->foreignId('inventory_id')
        //           ->constrained('inventory')
        //           ->cascadeOnDelete();

        //     // which purchase line it came from
        //     $table->foreignId('purchase_item_id')
        //           ->constrained('purchase_items')
        //           ->cascadeOnDelete();

        //     $table->string('imei1', 20);
        //     $table->string('imei2', 20)->nullable();

        //     $table->enum('status', [
        //         'pending',
        //         'in_stock',
        //         'reserved',
        //         'sold',
        //         'faulty',
        //         'returned',
        //     ])->default('pending');

        //     $table->text('notes')->nullable();

        //     $table->timestamps();
        // });


        // ============================================
        // SALES TABLES
        // ============================================

        // Main sales table
        Schema::create('sales', function (Blueprint $table) {
            $table->id();
            $table->string('invoice_number')->unique(); // INV-0001, INV-0002
            $table->foreignId('customer_id')->constrained('customers')->onDelete('cascade');
            $table->foreignId('sold_by')->constrained('users')->onDelete('cascade'); // Staff who made the sale
            $table->date('sale_date');
            $table->decimal('subtotal', 12, 2); // Total before tax and discount
            $table->decimal('tax_amount', 10, 2)->default(0);
            $table->decimal('discount', 10, 2)->default(0);
            $table->decimal('total_amount', 12, 2); // Final total
            $table->decimal('paid_amount', 12, 2)->default(0);
            $table->decimal('due_amount', 12, 2)->default(0);
            $table->decimal('profit', 12, 2)->default(0); // Auto-calculated profit
            $table->enum('payment_status', ['pending', 'partial', 'paid'])->default('pending');
            $table->enum('payment_type', ['cash', 'installment'])->default('cash');
            $table->enum('status', ['draft', 'completed', 'cancelled', 'returned'])->default('completed');
            $table->text('notes')->nullable();
            $table->timestamps();

            // Indexes
            $table->index('invoice_number');
            $table->index('customer_id');
            $table->index('sold_by');
            $table->index('sale_date');
            $table->index('payment_status');
            $table->index('payment_type');
            $table->index('status');
        });

        // Sale items (details)
        Schema::create('sale_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('sale_id')->constrained('sales')->onDelete('cascade');
            $table->foreignId('inventory_id')->constrained('inventory')->onDelete('cascade');
            $table->integer('quantity');
            $table->decimal('unit_cost', 10, 2); // Purchase price (for profit calculation)
            $table->decimal('unit_price', 10, 2); // Selling price
            $table->decimal('subtotal', 10, 2); // quantity * unit_price
            $table->decimal('profit', 10, 2)->default(0); // (unit_price - unit_cost) * quantity
            $table->timestamps();

            // Indexes
            $table->index('sale_id');
            $table->index('inventory_id');
        });

        // Sale payments (track all payments for a sale)
        Schema::create('sale_payments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('sale_id')->constrained('sales')->onDelete('cascade');
            $table->decimal('amount', 10, 2);
            $table->date('payment_date');
            $table->enum('payment_method', ['cash', 'bank_transfer', 'cheque', 'card', 'mobile_payment'])->default('cash');
            $table->string('reference_number')->nullable(); // Transaction ID
            $table->text('notes')->nullable();
            $table->foreignId('received_by')->constrained('users')->onDelete('cascade'); // Staff who received payment
            $table->timestamps();

            // Indexes
            $table->index('sale_id');
            $table->index('payment_date');
            $table->index('payment_method');
        });

        // Installments (for installment sales)
        // Schema::create('installments', function (Blueprint $table) {
        //     $table->id();
        //     $table->foreignId('sale_id')->constrained('sales')->onDelete('cascade');
        //     $table->integer('installment_number'); // 1, 2, 3, etc.
        //     $table->decimal('amount', 10, 2); // Amount due for this installment
        //     $table->date('due_date'); // When payment is due
        //     $table->decimal('paid_amount', 10, 2)->default(0);
        //     $table->enum('status', ['pending', 'paid', 'overdue'])->default('pending');
        //     $table->date('paid_date')->nullable();
        //     $table->text('notes')->nullable();
        //     $table->timestamps();

        //     // Indexes
        //     $table->index('sale_id');
        //     $table->index('due_date');
        //     $table->index('status');
        //     $table->index('installment_number');
        // });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Drop in reverse order to respect foreign key constraints
        Schema::dropIfExists('installments');
        Schema::dropIfExists('sale_payments');
        Schema::dropIfExists('sale_items');
        Schema::dropIfExists('sales');
        
        Schema::dropIfExists('purchase_payments');
        Schema::dropIfExists('purchase_items');
        Schema::dropIfExists('purchases');
    }
};