<?php

namespace App\DataFixes;

use App\Models\Order;

class FixOrdersNegoPrice extends BaseDataFix
{
    public function key(): string
    {
        return 'orders-nego-price';
    }

    public function description(): string
    {
        return 'Fix nego_price yang menyimpan total akhir, bukan potongan';
    }

    public function fix(): array
    {
        $orders = Order::where('nego_price', '>', 0)
            ->where('status', '!=', 'cancelled')
            ->get();

        $fixed = 0;
        $skipped = 0;
        $details = [];

        foreach ($orders as $order) {
            $oldNego = $order->nego_price;
            $oldTotal = $order->total_amount;

            $correctNego = $order->subtotal - $order->discount - $order->total_amount;

            if ($correctNego < 0) {
                $correctNego = 0;
            }

            if ($oldNego === $correctNego) {
                $skipped++;

                continue;
            }

            $order->update([
                'nego_price' => $correctNego,
            ]);

            $details[] = [
                'Order' => $order->order_number,
                'Subtotal' => number_format($order->subtotal),
                'Discount' => number_format($order->discount),
                'Old Nego' => number_format($oldNego),
                'New Nego' => number_format($correctNego),
                'Total' => number_format($oldTotal),
            ];

            $fixed++;
        }

        if (! empty($details)) {
            $this->command->newLine();
            $this->command->table(
                ['Order', 'Subtotal', 'Discount', 'Old Nego', 'New Nego', 'Total'],
                $details
            );
        }

        return [
            'fixed' => $fixed,
            'skipped' => $skipped,
            'total' => $orders->count(),
        ];
    }
}
