<?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
    {
        // Delivery zones define distance ranges from source
        Schema::create('delivery_zones', function (Blueprint $table) {
            $table->id();
            $table->string('name'); // e.g., "Local", "Regional", "National"
            $table->integer('min_distance_km')->default(0); // Minimum distance in km
            $table->integer('max_distance_km'); // Maximum distance in km
            $table->decimal('base_rate', 10, 2)->default(0); // Base delivery fee
            $table->decimal('rate_per_km', 10, 2)->default(0); // Additional rate per km
            $table->decimal('rate_per_kg', 10, 2)->default(0); // Rate per kg of weight
            $table->integer('estimated_days_min')->default(1); // Min delivery days
            $table->integer('estimated_days_max')->default(3); // Max delivery days
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        // Delivery rates can be customized per supplier
        Schema::create('supplier_delivery_rates', function (Blueprint $table) {
            $table->id();
            $table->foreignId('supplier_id')->constrained()->onDelete('cascade');
            $table->foreignId('delivery_zone_id')->constrained()->onDelete('cascade');
            $table->decimal('base_rate', 10, 2)->nullable(); // Override base rate
            $table->decimal('rate_per_km', 10, 2)->nullable(); // Override rate per km
            $table->decimal('rate_per_kg', 10, 2)->nullable(); // Override rate per kg
            $table->decimal('free_delivery_threshold', 10, 2)->nullable(); // Free delivery above this amount
            $table->boolean('is_active')->default(true);
            $table->timestamps();
            
            $table->unique(['supplier_id', 'delivery_zone_id']);
        });

        // Store location coordinates for distance calculation
        Schema::create('locations', function (Blueprint $table) {
            $table->id();
            $table->string('city');
            $table->string('province')->nullable();
            $table->string('postal_code')->nullable();
            $table->decimal('latitude', 10, 8)->nullable();
            $table->decimal('longitude', 11, 8)->nullable();
            $table->timestamps();
            
            $table->index(['city', 'province']);
            $table->index('postal_code');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('locations');
        Schema::dropIfExists('supplier_delivery_rates');
        Schema::dropIfExists('delivery_zones');
    }
};
