<?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
    {
        Schema::create('cultural_tour_dates', function (Blueprint $table) {
            $table->id();

            // Cultural Tour relationship
            $table->unsignedBigInteger('cultural_tour_id');
            $table->unsignedBigInteger('cultural_tour_pricing_id')->nullable(); // Which pricing to use

            // Date and Time Information
            $table->string('code', 20); // Tour date code
            $table->date('start_date'); // Start date
            $table->time('start_time')->nullable(); // Start time
            $table->date('end_date'); // End date
            $table->time('end_time')->nullable(); // End time
            $table->integer('duration_days')->nullable(); // Total days
            $table->integer('duration_nights')->nullable(); // Total nights

            // Capacity and Availability
            $table->integer('total_capacity')->default(0); // Total capacity
            $table->integer('adult_capacity')->default(0); // Adult capacity
            $table->integer('child_capacity')->default(0); // Child capacity
            $table->integer('infant_capacity')->default(0); // Infant capacity
            $table->integer('remaining_capacity')->default(0); // Remaining capacity
            $table->integer('sold_count')->default(0); // Sold count
            $table->integer('reserved_count')->default(0); // Reserved count

            // Pricing (can override tour default pricing) - Simplified to only adult, child, infant
            $table->decimal('adult_price', 10, 2)->nullable();
            $table->decimal('child_price', 10, 2)->nullable();
            $table->decimal('infant_price', 10, 2)->nullable();

            // Currency and financial info
            $table->string('currency', 3)->default('TRY');
            $table->decimal('exchange_rate', 10, 4)->default(1.0000); // Exchange rate
            $table->boolean('prices_include_tax')->default(true);
            $table->decimal('tax_rate', 5, 2)->default(0);

            // Age restrictions for this specific date
            $table->integer('child_min_age')->nullable();
            $table->integer('child_max_age')->nullable();
            $table->integer('infant_max_age')->nullable();

            // Special conditions for this date
            $table->boolean('infant_allowed')->default(true);
            $table->boolean('child_allowed')->default(true);
            $table->boolean('group_bookings_only')->default(false);
            $table->integer('min_group_size')->nullable();
            $table->integer('max_group_size')->nullable();

            // Booking deadlines (can override tour defaults)
            $table->integer('booking_deadline_hours')->nullable();
            $table->integer('cancellation_deadline_hours')->nullable();
            $table->date('early_booking_deadline')->nullable(); // Early booking deadline
            $table->date('last_minute_booking_start')->nullable(); // Last minute booking start

            // Discounts and promotions for this date
            $table->decimal('early_booking_discount', 5, 2)->default(0);
            $table->decimal('last_minute_discount', 5, 2)->default(0);
            $table->decimal('group_discount', 5, 2)->default(0);
            $table->decimal('special_discount', 5, 2)->default(0);
            $table->string('discount_reason')->nullable(); // Discount reason

            // Seasonal information
            $table->enum('season_type', ['low', 'medium', 'high', 'peak'])->default('medium');
            $table->decimal('season_multiplier', 5, 3)->default(1.000);
            $table->json('special_events')->nullable(); // Special events
            $table->json('local_holidays')->nullable(); // Local holidays

            // Weather and conditions
            $table->json('weather_forecast')->nullable(); // Weather forecast
            $table->text('special_notes')->nullable(); // Special notes
            $table->text('travel_conditions')->nullable(); // Travel conditions

            // Guide and service assignments
            $table->unsignedBigInteger('assigned_guide_id')->nullable(); // Assigned guide
            $table->unsignedBigInteger('assigned_vehicle_id')->nullable(); // Assigned vehicle
            $table->json('assigned_services')->nullable(); // Assigned services

            // Accommodation details for this date
            $table->json('accommodation_details')->nullable(); // Accommodation details
            $table->boolean('accommodation_confirmed')->default(false);
            $table->timestamp('accommodation_confirmed_at')->nullable();

            // Meal arrangements for this date
            $table->json('meal_arrangements')->nullable(); // Meal arrangements
            $table->boolean('meals_confirmed')->default(false);
            $table->timestamp('meals_confirmed_at')->nullable();

            // Transportation details
            $table->json('transportation_details')->nullable(); // Transportation details
            $table->boolean('transportation_confirmed')->default(false);
            $table->timestamp('transportation_confirmed_at')->nullable();

            // Booking and payment terms for this specific date
            $table->decimal('deposit_percentage', 5, 2)->nullable();
            $table->date('deposit_deadline')->nullable();
            $table->date('full_payment_deadline')->nullable();
            $table->json('payment_schedule')->nullable(); // Payment schedule

            // Cancellation policy for this date
            $table->json('cancellation_policy')->nullable(); // Date-specific cancellation policy
            $table->decimal('cancellation_fee', 10, 2)->default(0);

            // External bookings and integrations
            $table->json('external_bookings')->nullable(); // External system bookings
            $table->string('external_tour_code')->nullable(); // External system tour code
            $table->json('supplier_details')->nullable(); // Supplier details

            // Group and allocation management
            $table->json('room_allocations')->nullable(); // Room allocations
            $table->json('passenger_manifest')->nullable(); // Passenger list
            $table->boolean('manifest_locked')->default(false); // Is manifest locked?
            $table->timestamp('manifest_locked_at')->nullable();

            // Quality and feedback
            $table->decimal('expected_rating', 3, 2)->nullable(); // Expected rating
            $table->json('past_feedback')->nullable(); // Past feedback
            $table->text('improvement_notes')->nullable(); // Improvement notes

            // Status and workflow
            $table->enum('status', ['draft', 'published', 'booking_open', 'booking_closed', 'confirmed', 'in_progress', 'completed', 'cancelled'])->default('draft');
            $table->boolean('is_active')->default(true);
            $table->boolean('is_published')->default(false);
            $table->boolean('is_bookable')->default(false);
            $table->boolean('is_confirmed')->default(false);
            $table->boolean('auto_confirm')->default(false); // Auto confirm
            $table->timestamp('published_at')->nullable();
            $table->timestamp('confirmed_at')->nullable();
            $table->unsignedBigInteger('confirmed_by')->nullable();

            // Minimum requirements for this date
            $table->integer('min_participants')->nullable();
            $table->integer('max_participants')->nullable();
            $table->boolean('guarantee_departure')->default(false); // Guaranteed departure
            $table->date('guarantee_deadline')->nullable(); // Guarantee deadline

            // Analytics and tracking
            $table->unsignedInteger('view_count')->default(0); // View count
            $table->unsignedInteger('inquiry_count')->default(0); // Inquiry count
            $table->unsignedInteger('booking_attempt_count')->default(0); // Booking attempt count
            $table->decimal('conversion_rate', 5, 2)->default(0); // Conversion rate

            // Cost and profitability analysis
            $table->decimal('total_cost', 10, 2)->default(0); // Total cost
            $table->decimal('expected_revenue', 10, 2)->default(0); // Expected revenue
            $table->decimal('actual_revenue', 10, 2)->default(0); // Actual revenue
            $table->decimal('profit_margin', 5, 2)->default(0); // Profit margin

            // Emergency and safety
            $table->json('emergency_contacts')->nullable(); // Emergency contacts
            $table->text('safety_instructions')->nullable(); // Safety instructions
            $table->json('insurance_details')->nullable(); // Insurance details

            // Audit fields
            $table->unsignedBigInteger('created_by')->nullable();
            $table->unsignedBigInteger('updated_by')->nullable();
            $table->timestamps();
            $table->softDeletes();

            // Foreign Keys
            $table->foreign('cultural_tour_id')->references('id')->on('cultural_tours')->onDelete('cascade');
            $table->foreign('cultural_tour_pricing_id')->references('id')->on('cultural_tour_pricings')->onDelete('set null');
            $table->foreign('assigned_guide_id')->references('id')->on('definitions')->onDelete('set null');
            $table->foreign('assigned_vehicle_id')->references('id')->on('definitions')->onDelete('set null');
            $table->foreign('confirmed_by')->references('id')->on('users')->onDelete('set null');
            $table->foreign('created_by')->references('id')->on('users')->onDelete('set null');
            $table->foreign('updated_by')->references('id')->on('users')->onDelete('set null');

            // Indexes
            $table->index(['cultural_tour_id', 'is_active']);
            $table->index(['cultural_tour_id', 'status']);
            $table->index(['start_date', 'end_date']);
            $table->index(['is_published', 'is_bookable']);
            $table->index(['status', 'start_date']);
            $table->index(['cultural_tour_pricing_id']);
            $table->index(['season_type', 'start_date']);
            $table->index(['guarantee_departure', 'start_date']);
            $table->index(['created_at']);
            $table->index(['adult_price', 'currency']);

            // Unique constraints
            $table->unique(['cultural_tour_id', 'code'], 'unique_cultural_tour_date_code');
        });
    }

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