<?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
    {
        // Shipping tracking table
        if (!Schema::hasTable('shipment_trackings')) {
            Schema::create('shipment_trackings', function (Blueprint $table) {
                $table->id();
                $table->foreignId('order_id')->constrained()->onDelete('cascade');
                $table->string('carrier');
                $table->string('tracking_number');
                $table->string('status')->default('pending'); // pending, picked_up, in_transit, out_for_delivery, delivered
                $table->timestamp('shipped_at')->nullable();
                $table->timestamp('estimated_delivery')->nullable();
                $table->timestamp('delivered_at')->nullable();
                $table->timestamps();
            });
        }

        // Shipping tracking events/history
        if (!Schema::hasTable('shipment_events')) {
            Schema::create('shipment_events', function (Blueprint $table) {
                $table->id();
                $table->foreignId('shipment_tracking_id')->constrained()->onDelete('cascade');
                $table->string('status');
                $table->text('description');
                $table->string('location')->nullable();
                $table->timestamp('event_time');
                $table->timestamps();
            });
        }

        // Add review images table
        if (!Schema::hasTable('review_images')) {
            Schema::create('review_images', function (Blueprint $table) {
                $table->id();
                $table->foreignId('review_id')->constrained()->onDelete('cascade');
                $table->string('image_path');
                $table->timestamps();
            });
        }

        // Update reviews table to add more fields
        Schema::table('reviews', function (Blueprint $table) {
            if (!Schema::hasColumn('reviews', 'title')) {
                $table->string('title')->nullable()->after('rating');
            }
            if (!Schema::hasColumn('reviews', 'is_verified_purchase')) {
                $table->boolean('is_verified_purchase')->default(false)->after('is_approved');
            }
            if (!Schema::hasColumn('reviews', 'helpful_count')) {
                $table->integer('helpful_count')->default(0)->after('is_verified_purchase');
            }
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('review_images');
        Schema::dropIfExists('shipment_events');
        Schema::dropIfExists('shipment_trackings');
        
        Schema::table('reviews', function (Blueprint $table) {
            $table->dropColumn(['title', 'is_verified_purchase', 'helpful_count']);
        });
    }
};
