<?php

namespace App\Console\Commands;

use App\Models\Creator;
use App\Support\IdFormatter;
use Illuminate\Console\Command;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class ExportCreatorsExcel extends Command
{
    protected $signature = 'app:export-creators-excel
        {--org= : Organization hex ID (mặc định dùng org của ImportOldKocs)}
        {--o= : Đường dẫn file output (mặc định creators_export.xlsx)}';

    protected $description = 'Xuất danh sách Creator của Organization ra file Excel kèm cột cid trống';

    public function handle(): int
    {
        $orgHex = $this->option('org') ?: '019e90bcf88b7ba13bf40a1ad37afc85';
        $output = $this->option('o') ?: getcwd() . DIRECTORY_SEPARATOR . 'creators_export_huyen.xlsx';

        $orgBin = IdFormatter::hexToBinary($orgHex);
        if (!$orgBin) {
            $this->error('Organization hex ID không hợp lệ');
            return 1;
        }

        $this->info('Đang lấy danh sách Creator...');
        $creators = Creator::where('organization_id', $orgBin)->orderBy('creator_name')->get();

        if ($creators->isEmpty()) {
            $this->warn('Không có Creator nào trong Organization này');
            return 0;
        }

        $this->info('Tổng số Creator: ' . $creators->count());

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle('Creators');

        $headers = ['creator_name', 'cid'];

        foreach ($headers as $colIdx => $header) {
            $sheet->setCellValueByColumnAndRow($colIdx + 1, 1, $header);
        }
        $sheet->getStyle('A1:B1')->getFont()->setBold(true);

        $row = 2;
        foreach ($creators as $creator) {
            $sheet->setCellValueByColumnAndRow(1, $row, $creator->creator_name);
            $sheet->setCellValueByColumnAndRow(2, $row, '');
            $row++;
        }

        foreach (range(1, 2) as $colIdx) {
            $sheet->getColumnDimensionByColumn($colIdx)->setAutoSize(true);
        }

        $writer = new Xlsx($spreadsheet);
        $writer->save($output);

        $this->info('Đã xuất file: ' . realpath($output));
        $this->info('Tổng số dòng: ' . ($row - 2));

        return 0;
    }
}
