<?php

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

class AddXeroSyncedAtToInvoicesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('invoices', function (Blueprint $table) {
            // Add Xero sync tracking columns only if they don't exist
            if (!Schema::hasColumn('invoices', 'xero_synced_at')) {
                $table->timestamp('xero_synced_at')->nullable()->after('xeroId');
            }
            if (!Schema::hasColumn('invoices', 'xero_sync_error')) {
                $table->string('xero_sync_error')->nullable()->after('xero_synced_at');
            }
            if (!Schema::hasColumn('invoices', 'xero_sync_status')) {
                $table->string('xero_sync_status')->nullable()->after('xero_sync_error');
            }
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('invoices', function (Blueprint $table) {
            // Drop columns only if they exist
            $columnsToDrop = [];
            if (Schema::hasColumn('invoices', 'xero_synced_at')) {
                $columnsToDrop[] = 'xero_synced_at';
            }
            if (Schema::hasColumn('invoices', 'xero_sync_error')) {
                $columnsToDrop[] = 'xero_sync_error';
            }
            if (Schema::hasColumn('invoices', 'xero_sync_status')) {
                $columnsToDrop[] = 'xero_sync_status';
            }
            
            if (!empty($columnsToDrop)) {
                $table->dropColumn($columnsToDrop);
            }
        });
    }
}
