<?php

namespace App\Console\Commands;

use App\Http\Controllers\TailoringProductController;
use App\TailoringProduct;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class SyncTailoringSales extends Command
{
    protected $signature = 'tailoring:sync-sales {--order=}';
    protected $description = 'Create or refresh Sale List records for tailoring orders';

    public function handle(TailoringProductController $controller)
    {
        $query = TailoringProduct::where('is_active', true)
            ->where('type', 'Curtain')
            ->whereNotNull('curtain_id')
            ->orderBy('id');

        if ($this->option('order')) {
            $query->where('id', $this->option('order'));
        }

        $count = 0;
        $query->chunkById(50, function ($orders) use ($controller, &$count) {
            foreach ($orders as $order) {
                DB::transaction(function () use ($controller, $order, &$count) {
                    if ($controller->syncTailoringSaleHistory($order)) {
                        $count++;
                    }
                });
            }
        });

        $this->info("Synchronized {$count} tailoring sale(s).");
        return 0;
    }
}
