<?php

namespace App\Http\Controllers;

use App\Services\ExportService;
use Illuminate\Http\Request;

class ExportController extends Controller
{
    protected $exportService;

    public function __construct(ExportService $exportService)
    {
        $this->exportService = $exportService;
    }

    public function downloadXlsx(Request $request)
    {
        $filename = $request->input('filename');

        $headers = $request->input('headers');
        if (is_string($headers)) {
            $headers = json_decode($headers, true);
        }

        $rows = $request->input('rows');
        if (is_string($rows)) {
            $rows = json_decode($rows, true);
        }

        if (empty($filename) || empty($headers) || !is_array($rows)) {
            abort(400, 'Dữ liệu xuất file không hợp lệ');
        }

        $filePath = $this->exportService->generateXlsx($filename, $headers, $rows);

        return response()
            ->download($filePath, $filename . '.xlsx', [
                'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            ])
            ->deleteFileAfterSend(true);
    }
}
