<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Anggota;
use Illuminate\Support\Facades\Crypt;

class EncryptExistingData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'encrypt:anggota-data {--force : Force encryption even if data already encrypted}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Encrypt existing anggota data for PDP compliance';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('🔐 Starting data encryption process...');
        
        $force = $this->option('force');
        
        // Get all anggota data
        $anggotas = Anggota::all();
        $total = $anggotas->count();
        
        if ($total === 0) {
            $this->warn('No anggota data found to encrypt.');
            return;
        }
        
        $this->info("Found {$total} anggota records to process.");
        
        $bar = $this->output->createProgressBar($total);
        $bar->start();
        
        $encrypted = 0;
        $skipped = 0;
        $errors = 0;
        
        foreach ($anggotas as $anggota) {
            try {
                $needsEncryption = false;
                
                // Check if data needs encryption
                if ($force || !$anggota->nomor_identitas_anggota_encrypted) {
                    $needsEncryption = true;
                }
                
                if ($needsEncryption) {
                    // Encrypt sensitive data
                    $fields = [
                        'nomor_identitas_anggota',
                        'alamat_jalan',
                        'rt',
                        'rw',
                        'kelurahan',
                        'no_telepon',
                        'email',
                        'penghasilan_per_bulan',
                        'nomor_identitas_pasangan'
                    ];
                    
                    foreach ($fields as $field) {
                        $value = $anggota->getAttribute($field);
                        if ($value) {
                            $encryptedValue = Crypt::encryptString($value);
                            $anggota->setAttribute($field . '_encrypted', $encryptedValue);
                        }
                    }
                    
                    $anggota->save();
                    $encrypted++;
                } else {
                    $skipped++;
                }
                
            } catch (\Exception $e) {
                $this->error("Error encrypting anggota ID {$anggota->id}: " . $e->getMessage());
                $errors++;
            }
            
            $bar->advance();
        }
        
        $bar->finish();
        $this->newLine();
        
        $this->info("✅ Encryption process completed!");
        $this->table(
            ['Status', 'Count'],
            [
                ['Encrypted', $encrypted],
                ['Skipped', $skipped],
                ['Errors', $errors],
                ['Total', $total]
            ]
        );
        
        if ($errors > 0) {
            $this->warn("⚠️  {$errors} records had errors during encryption.");
        }
        
        $this->info('🔒 All sensitive data is now encrypted and PDP compliant!');
    }
}
