<?php

namespace App\Console\Commands;

use App\Cawangan;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;

class ImportCsv extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'csv:import';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Import CSV file to MySQL table';

    /**
     * Create a new command instance.
     *
     * @return void
     */

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $file = resource_path('data/anggota.csv');
        $handle = fopen($file, 'r');
        $header = fgetcsv($handle);

        $columnMap = [
            'no_anggota' => 'no_anggota',
            'nama'       => 'nama',
            'no_kp'      => 'noic',
            'telefon'    => 'no_tel',
        ];

        $chunk = [];
        $chunkSize = 1000;
        $totalRows = 0;

        $bar = $this->output->createProgressBar();
        $bar->start();

        try {
            while (($row = fgetcsv($handle)) !== false) {
                $csvData = array_combine($header, $row);
                $data = [];

                foreach ($columnMap as $csvCol => $dbCol) {
                    $data[$dbCol] = $csvData[$csvCol] ?? null;
                }

                $data['status'] = 1;
                $chunk[] = $data;

                if (count($chunk) >= $chunkSize) {
                    DB::table('anggota')->insertOrIgnore($chunk);
                    $totalRows += count($chunk);
                    $chunk = [];
                    $bar->advance($chunkSize);
                }
            }

            if (!empty($chunk)) {
                DB::table('anggota')->insertOrIgnore($chunk);
                $totalRows += count($chunk);
            }

            $bar->finish();
            $this->info("\n✅ Successfully imported {$totalRows} rows");
        } catch (\Exception $e) {
            $this->error("\n❌ Error: " . $e->getMessage());
        }

        fclose($handle);
    }
}
