<?php

namespace App\Console\Commands;

use App\Models\CouponRedemption;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

class ExportCouponRedemptions extends Command
{
    protected $signature = 'coupons:export {--days=30 : Number of days to include} {--path= : Relative path inside storage/app}';

    protected $description = 'Export coupon redemptions within the given timeframe to CSV.';

    public function handle(): int
    {
        $days = max(1, (int) $this->option('days'));
        $since = now()->subDays($days);

        $redemptions = CouponRedemption::query()
            ->where('status', CouponRedemption::STATUS_SUCCESS)
            ->where('redeemed_at', '>=', $since)
            ->with(['coupon', 'tenant', 'package'])
            ->orderBy('redeemed_at')
            ->get();

        $rows = [
            ['coupon_code', 'tenant_id', 'package_id', 'amount_discounted', 'currency', 'redeemed_at'],
        ];

        foreach ($redemptions as $redemption) {
            $rows[] = [
                $redemption->coupon?->code ?? '',
                $redemption->tenant_id,
                $redemption->package_id,
                number_format((float) $redemption->amount_discounted, 2, '.', ''),
                $redemption->currency,
                optional($redemption->redeemed_at)->toIso8601String(),
            ];
        }

        $csv = collect($rows)
            ->map(fn (array $row) => collect($row)
                ->map(fn ($value) => '"'.str_replace('"', '""', (string) $value).'"')
                ->implode(','))
            ->implode(PHP_EOL)
            .PHP_EOL;

        $path = $this->option('path') ?: 'reports/coupon-redemptions-'.now()->format('Ymd_His').'.csv';
        Storage::disk('local')->put($path, $csv);

        $this->info(sprintf('Exported %d records to %s', $redemptions->count(), storage_path('app/'.$path)));

        return self::SUCCESS;
    }
}
