<?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('carts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->onDelete('cascade');

            // Status
            $table->enum('status', ['active', 'checked_out', 'abandoned', 'expired'])->default('active');

            // Totals (cached for performance)
            $table->string('currency')->default('KES');
            $table->decimal('subtotal', 14, 2)->default(0.00);
            $table->decimal('platform_fee', 14, 2)->default(0.00);
            $table->decimal('total', 14, 2)->default(0.00);

            $table->timestamp('expires_at')->nullable();
            $table->timestamps();
        });

        Schema::create('cart_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('cart_id')->constrained('carts')->onDelete('cascade');
            $table->foreignId('placement_id')->constrained('placements')->onDelete('cascade');

            // Booking details
            $table->enum('booking_type', ['instant', 'offer'])->default('instant');
            $table->date('start_date');
            $table->date('end_date');

            // DOOH specific
            $table->foreignId('availability_slot_id')->nullable()->constrained('availability_slots')->onDelete('set null');
            $table->string('package_name')->nullable(); // e.g. Standard 15s, Prime hours
            $table->unsignedInteger('spots')->nullable();

            // Pricing snapshot at time of adding to cart
            $table->string('currency')->default('KES');
            $table->decimal('unit_price', 14, 2);
            $table->decimal('quantity', 8, 2)->default(1);
            $table->decimal('subtotal', 14, 2);
            $table->decimal('platform_fee', 14, 2)->default(0.00);
            $table->decimal('total', 14, 2);

            // Offer details (billboard guardrail)
            $table->decimal('offer_price', 14, 2)->nullable();
            $table->enum('offer_status', ['pending', 'accepted', 'countered', 'rejected'])->nullable();
            $table->decimal('counter_price', 14, 2)->nullable();

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

    public function down(): void
    {
        Schema::dropIfExists('cart_items');
        Schema::dropIfExists('carts');
    }
};