<?php

namespace App\Console\Commands;

use App\Services\ServiceGoogleSheet;
use Illuminate\Console\Command;

class SyncPbgTaskPayments extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sync:pbg-payments';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sync PBG task payments from Google Sheets REALISASI PAD';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('🚀 Starting PBG Task Payments sync...');
        $this->newLine();

        try {
            $service = new ServiceGoogleSheet();
            
            // Show progress bar
            $this->info('📊 Fetching data from Google Sheets...');
            $result = $service->sync_pbg_task_payments();

            // Display results
            $this->newLine();
            $this->info('✅ Sync completed successfully!');
            $this->newLine();
            
            $this->table(
                ['Metric', 'Count'],
                [
                    ['Total rows processed', $result['total_rows']],
                    ['Successful syncs', $result['successful_syncs']],
                    ['Failed syncs', $result['failed_syncs']],
                    ['Tasks not found', $result['not_found_tasks']],
                ]
            );

            // Show success rate
            $success_rate = $result['total_rows'] > 0 
                ? round(($result['successful_syncs'] / $result['total_rows']) * 100, 2) 
                : 0;
            
            $this->info("📈 Success rate: {$success_rate}%");

            // Show errors if any
            if (!empty($result['errors'])) {
                $this->newLine();
                $this->warn('⚠️  Errors encountered:');
                foreach (array_slice($result['errors'], 0, 5) as $error) {
                    $this->line("   Row {$error['row']} ({$error['registration_number']}): {$error['error']}");
                }
                
                if (count($result['errors']) > 5) {
                    $remaining = count($result['errors']) - 5;
                    $this->line("   ... and {$remaining} more errors (check logs for details)");
                }
            }

            $this->newLine();
            $this->info('📝 Check Laravel logs for detailed information.');
            
            return Command::SUCCESS;

        } catch (\Exception $e) {
            $this->newLine();
            $this->error('❌ Sync failed!');
            $this->error('Error: ' . $e->getMessage());
            
            return Command::FAILURE;
        }
    }
}
