<?php

namespace App\Console\Commands;

use App\Http\Services\ConstDef\GeneralConst;
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;
use Illuminate\Console\Command;

class QRGen extends Command
{
    
    protected $signature   = 'qr:gen {--src= : csv path} {--dst= : folder path}';
    protected $description = 'batch generate qrcode';
    
    public function __construct()
    {
        parent::__construct();
    }
    
    /**
     * 脚本入口
     */
    public function handle()
    {
        $src = $this->option('src');
        $dst = $this->option('dst');
        $cnt = [];
        if (($handle = fopen($src, "r")) !== false) {
            while (($data = fgetcsv($handle, 2000, ",")) !== false) {
                // 變數整理
                $folder_name = $data[0] ?? '未命名';
                $url = $data[1] ?? 'https://www.google.com';
                $path = $dst . '/' . $folder_name;
                // 創建資料夾
                if (!file_exists($path)) mkdir($path, 0777, true);
                // 檔名生成
                $cnt[ $folder_name ] = (!isset($cnt[ $folder_name ])) ? 1 : $cnt[ $folder_name ] + 1;
                $file_name = $folder_name . str_pad($cnt[ $folder_name ], 6, '0', STR_PAD_LEFT) . '.png';
                // QRCODE 檔案生成
                $options = new QROptions([
                    'version'     => 5,
                    'outputType'  => QRCode::OUTPUT_IMAGE_PNG,
                    'imageBase64' => false,
                ]);
                $myfile = fopen($path . '/' . $file_name, "w");
                fwrite($myfile, (new QRCode($options))->render($url));
                fclose($myfile);
            }
            fclose($handle);
        }
    }
    
}
