<?php

namespace Modules\Lpj\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Modules\Lpj\Models\Inspeksi;

class CleanupInspeksiStatusCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'lpj:cleanup-inspeksi-status 
                            {--permohonan-id= : Filter berdasarkan permohonan ID}
                            {--created-by= : Filter berdasarkan user ID}
                            {--detailed : Tampilkan detail data}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Cek status data inspeksi yang memerlukan cleanup';

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        try {
            $permohonanId = $this->option('permohonan-id');
            $createdBy = $this->option('created-by');
            $detailed = $this->option('detailed');

            $this->info('=== Status Data Inspeksi ===');
            $this->newLine();

            // Ambil statistik umum
            $this->showGeneralStats();

            // Ambil data yang memerlukan cleanup
            $this->showCleanupStats($permohonanId, $createdBy);

            if ($detailed) {
                $this->showDetailedData($permohonanId, $createdBy);
            }

            return Command::SUCCESS;

        } catch (\Exception $e) {
            Log::error('CleanupInspeksiStatusCommand: Terjadi error', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            $this->error('Terjadi kesalahan: ' . $e->getMessage());
            return Command::FAILURE;
        }
    }

    /**
     * Tampilkan statistik umum
     */
    private function showGeneralStats(): void
    {
        $this->info('Statistik Umum:');
        
        $totalData = Inspeksi::count();
        $activeData = Inspeksi::whereNull('deleted_at')->count();
        $deletedData = Inspeksi::whereNotNull('deleted_at')->count();
        $dataWithDokument = Inspeksi::whereNotNull('dokument_id')->count();
        $dataWithoutDokument = Inspeksi::whereNull('dokument_id')->count();

        $this->table(
            ['Metrik', 'Jumlah'],
            [
                ['Total Data', number_format($totalData)],
                ['Data Aktif', number_format($activeData)],
                ['Data Terhapus (Soft)', number_format($deletedData)],
                ['Data dengan Dokument ID', number_format($dataWithDokument)],
                ['Data tanpa Dokument ID', number_format($dataWithoutDokument)],
            ]
        );

        $this->newLine();
    }

    /**
     * Tampilkan statistik cleanup
     */
    private function showCleanupStats(?int $permohonanId = null, ?int $createdBy = null): void
    {
        $this->info('Data yang Memerlukan Cleanup:');

        $query = DB::table('inspeksi as i')
            ->select(
                'i.permohonan_id',
                'i.created_by',
                DB::raw('COUNT(CASE WHEN i.dokument_id IS NOT NULL AND i.deleted_at IS NULL THEN 1 END) as new_data_count'),
                DB::raw('COUNT(CASE WHEN i.dokument_id IS NULL AND i.deleted_at IS NULL THEN 1 END) as old_data_count'),
                DB::raw('MIN(i.created_at) as oldest_data'),
                DB::raw('MAX(i.created_at) as newest_data')
            )
            ->whereNull('i.deleted_at')
            ->groupBy('i.permohonan_id', 'i.created_by');

        if ($permohonanId) {
            $query->where('i.permohonan_id', $permohonanId);
        }

        if ($createdBy) {
            $query->where('i.created_by', $createdBy);
        }

        $results = $query->havingRaw('new_data_count > 0 AND old_data_count > 0')
            ->orderBy('old_data_count', 'desc')
            ->limit(20)
            ->get();

        if ($results->isEmpty()) {
            $this->info('Tidak ada data yang memerlukan cleanup.');
            return;
        }

        $this->table(
            ['Permohonan ID', 'Created By', 'Data Baru', 'Data Lama', 'Data Terlama', 'Data Terbaru'],
            $results->map(function ($item) {
                return [
                    $item->permohonan_id,
                    $item->created_by,
                    $item->new_data_count,
                    $item->old_data_count,
                    $item->oldest_data,
                    $item->newest_data,
                ];
            })->toArray()
        );

        $totalPermohonan = $results->count();
        $totalOldData = $results->sum('old_data_count');

        $this->info("Total permohonan yang perlu cleanup: {$totalPermohonan}");
        $this->info("Total data lama yang akan dihapus: {$totalOldData}");
        $this->newLine();
    }

    /**
     * Tampilkan detail data
     */
    private function showDetailedData(?int $permohonanId = null, ?int $createdBy = null): void
    {
        $this->info('Detail Data (20 data terbaru):');

        $query = Inspeksi::with(['permohonan', 'dokument'])
            ->whereNull('deleted_at');

        if ($permohonanId) {
            $query->where('permohonan_id', $permohonanId);
        }

        if ($createdBy) {
            $query->where('created_by', $createdBy);
        }

        $data = $query->orderBy('created_at', 'desc')
            ->limit(20)
            ->get();

        if ($data->isEmpty()) {
            $this->info('Tidak ada data untuk ditampilkan.');
            return;
        }

        $this->table(
            ['ID', 'Permohonan ID', 'Created By', 'Dokument ID', 'Status', 'Created At'],
            $data->map(function ($item) {
                return [
                    $item->id,
                    $item->permohonan_id,
                    $item->created_by,
                    $item->dokument_id ?? '-',
                    $item->status,
                    $item->created_at,
                ];
            })->toArray()
        );
    }
}